Repository navigation
[GC] GC09: Every parked writer reaches a terminal status that matches one-WAL semantics - #3
Closed
JustinGaoF wants to merge 1 commit into
Closed
JustinGaoF wants to merge 1 commit into
JustinGaoF wants to merge 1 commit into
Conversation
… one-WAL semantics
Summary:
[GC] GC09 (Lane B8; D-1; D-N71 option (b))
**Reviewer question:** at `wal_partitions > 1`, does a write parked in its completion gate now leave the gate only in three ways? Those are: covered → OK; a failed range at or below its target → that failure's background error, and this still holds after recovery releases the range; shutdown → `ShutdownInProgress`. And does a write that failed at its gate never become visible, live or after reopen? Check four places: `WaitForWalDurability` (its exits), `InstallWalGateFence` / `ClearWalDurabilityBGError` (fence lifetime), `FlushJob::DropEntriesAtOrAbove` with `UnreleasedWalGateFenceLow` (recovery's flush), and `ErrorHandler::HandleKnownErrors` (no suppression of an N>1 WAL failure).
Checklist items closed: G-13, N-2-4, N-2-5, N-7-1 (review F013), plus the GC08 carry-over Q5 (no success above a released failed range) and Q6 (file-scoped live resume at N>1: the rejection stays, analysis below). Still open, not addressed here: G-18, G-19, N-3-1, N-3-2, G-11.
## Why
The completion gate parks a write after its own append and memtable insert until every lower sequence on every partition is WAL-durable. At the base (GC08 winner, 59771e158a15), a parked writer could still end four ways that one WAL never produces:
- **G-13:** a listener could suppress a WAL append failure in `HandleKnownErrors` (plain IOError, NoSpace, Busy/Incomplete, IOFenced). No error was stored, the failed range stayed pinned, and every later gated write on every partition parked forever.
- **N-2-4:** `Close()` never woke parked gates. Teardown then freed `wal_durability_cv_` and `sequence_wal_index_mutex_` under the parked threads.
- **N-2-5:** a write B that appended and inserted above a failed write A got the gate error. GC08 then released A's range at `ClearBGError`, which published past B, and Resume's atomic flush wrote B into an SST. The DB held a write that had reported failure, sitting above a hole. A write held between its write-queue exit and its gate across a whole auto-resume found its target covered and returned OK (GC08 carry-over Q5).
- **N-7-1 / F013:** the gate failed on any stored background error, including a soft compaction NoSpace or a hard flush error. Those writes were durable, inserted and published, and one WAL would have returned OK for them.
## New behaviour
**Gate exits (D-N71 (b))**
| Exit | When | Returns |
|---|---|---|
| covered | `LastSequence() >= target` (and the durability safe point, for a group with a WAL record), and no fence holds `target` | OK |
| fenced | a fence holds `target`: a WAL range (append or leadership sync) or a memtable insert at or below `target` failed. The fence is open-ended while the error stands; once recovery releases the range, it closes at the last allocated sequence. | the background error recorded with that failure |
| shutdown | `shutting_down_` is set while still uncovered | `ShutdownInProgress("parked write")` |
- Any other background error (soft or hard, from flush, compaction, MANIFEST or async open) only wakes a parked gate to recheck. The gate parks again; it does not spin, and it returns OK once covered. New writes still fail in `PreprocessWrite` exactly as at N=1.
- At N=1 no gate exists (`CompletionGateNeverInstallsAtOnePartition`). Every other new branch is gated on `NumWalPartitions() > 1`.
**Q1: an N>1 WAL failure cannot be suppressed (G-13).**
- In `HandleKnownErrors`, after listeners run, a WAL write error from the write path (`kWriteCallback`, `wal_related`) at N>1 is restored to its computed status if a listener cleared it or lowered its severity. Listeners are still notified.
- This is GC08's classification point: `WALIOStatusCheck` is the only caller with that pair, and at N>1 it already escalates every failure (D-1).
- The other suppressible branches (`!allow_auto_recovery`) are reachable only through `SetBGErrorNoAutoRecovery`, which no WAL path uses. Retryable, file-scoped, data-loss and `manual_wal_flush` WAL errors are stored before listeners run.
- Unchanged: N=1 suppression, suppression of non-WAL errors, and the F-101 `>` guard.
**Q2: Close wakes every parked write and teardown waits for them (N-2-4).**
- `CancelAllBackgroundWork` signals the gate's cv under its mutex right after setting `shutting_down_`. A parked write returns OK if covered, else `ShutdownInProgress`, the same status as a stalled write.
- `CloseHelper` then waits on the same cv until `wal_durability_waiters_` (now counted under the gate mutex) is 0, and only then goes on to teardown. The last waiter out signals.
- Scope: the guarantee covers every write parked when shutdown begins. A write that reaches its gate after the drain is a write concurrent with `Close()`, which stays unsupported.
- Whether a `ShutdownInProgress` write survives reopen is left to recovery's prefix rule. In `CloseWakesParkedWrite`, the lower held write completes before teardown, so the prefix is complete; no promise is made either way.
**Q3: a gate-failed write is never exposed (N-2-5).**
- While an unreleased fence stands, every flush drops memtable entries at or above the fence's start. The flush picks up the floor under `mutex_` right before `PickMemTable` (`UnreleasedWalGateFenceLow`). `FlushJob` hides point entries at or above it through a forward-only `SequenceFloorIterator` (its count keeps the memtable entry-count check honest) and reads range tombstones at `floor - 1`.
- Why exactly those entries:
- Nothing at or above an unreleased fence can be acknowledged (the gate fails it), so every such entry belongs to a doomed write.
- Every acknowledged write sits below every unreleased fence.
- Why recovery's flush catches every doomed entry:
- A write allocated before recovery clears the error held its partition's write-queue leadership from `PreprocessWrite` through its insert.
- Resume's atomic flush enters every partition's write queue, so those inserts land in memtables that the flush covers.
- A write admitted after the error fails in `PreprocessWrite`.
- `ClearBGError` now calls `ClearWalDurabilityBGError` before it clears `is_db_stopped_`. So any write the cleared flag admits allocates above the closed fences.
- A flush already running when the error is recorded cannot hold B. Its memtables were switched before the error, with the switch gate closed and no error standing, so every allocated range was published (`AssertLastSequenceCoversAllocated`). A, failing later, was therefore allocated after that switch, and so was B above it. Non-recovery flushes that finish while background work is stopped are rolled back anyway.
- `GetUpdatesSince`: when recovery closes a fence, `RecordIndeterminateWriteSequence` records [low, high] (WAL number 1, since the records may lie in any partition's WAL), so every iterator stops before it, as for N=1 file-scoped recovery.
- Sequence reuse: within the process, `LastAllocatedSequence` never moves back, so no fenced sequence is reissued. After a crash, the abandoned records sit only in WALs that Resume's atomic flush moved every column family past, so recovery never reads them.
- Reopen with the error still set: point-in-time recovery cuts at the failed range (GC08), so B is not replayed.
- D-1 limit, unchanged: if A's record landed whole, a crash replays A and B. `DISABLED_CrashAfterLandedFailedAppendRecoversNoFailedWrite` stays disabled, and the crash legs here use a record that never landed.
**Q4: only a failure that can never be covered fails a parked write (N-7-1, F013).** This is the fence exit above. A failed memtable insert also pins its range for good (fatal error), so `HandleMemTableInsertFailure` now takes the group's first sequence and installs a fence that recovery never closes (`released_by_recovery=false`). Without that fence, (b) would leave a write parked above a failed insert forever.
**Q5: no success above a released range (GC08 carry-over).** Fences outlive recovery: `ClearWalDurabilityBGError` closes each open one at `LastAllocatedSequence()` before releasing the trackers. Every path that finds a write covered (fast path, spin, park loop) then checks the fences. Two atomics (`wal_gate_fence_low_`, `wal_gate_fence_high_`) keep that check to two loads for any target outside every fence; that includes every write allocated after recovery.
**Q6: file-scoped live resume at N>1. Option (a): the rejection stays.**
- Upstream added the `track_and_verify_wals_in_manifest` / `track_and_verify_wals` rejection in 05779d2bff70 (PR 15193, "Recover from poisoned WAL handles"). It is part of a fail-closed supported envelope, next to WAL recycling, retention, 2PC and others, and no failure mechanism is named.
- That diff's own stress mode turns WAL tracking off, so the combination is unvalidated upstream.
- The mechanisms it touches all exist per partition at N>1:
- quarantined handles retired without their own MANIFEST WAL deletion, relying on the atomic flush's log-number advance;
- `SyncWAL` skipping quarantined writers while still recording healthy WALs' synced sizes;
- predecessor-WAL info stamped into the replacement WAL while the failed WAL's true size is indeterminate.
N>1 adds a cutoff that also covers healthy WALs of other partitions.
- No reason was established that would make the exclusion safe to drop at N>1. GC08's loser lifted it without one. So `FileScopedFailureStaysStoppedAsAtOnePartition` passes unchanged. The `ResumeImpl` change and `WalFileScopeErrorResumeRestoresWrites` from D127099968 are not ported.
## Evidence (each neuter was run on this code; the failure is as shown)
- **Q1** `ListenerCannotSuppressPartitionedAppendFailure`:
- N=2 with a listener that clears every error: a plain IOError and a retryable IOError (auto-resume off) on partition 0.
- In both cases the listener is called, the stored error has the N=1 severity (fatal and hard), the write parked above fails with exactly that error, and a new write fails.
- At N=1 the same listener still suppresses the plain IOError (the retryable one is stored first at N=1 too).
- Neuter, override removed: the debug assertion in `WALIOStatusCheck` that the error is stored aborts. With the assertion also removed, `bg_n` is OK.
- **Q2** `CloseWakesParkedWrite` and `CloseWakesParkedWriteUnderBackgroundError`:
- A is held on partition 0 and W is parked on partition 1. In the second test, C then fails its append on partition 1 above W (retryable, hard error), and W stays parked under (b).
- `Close()` runs on another thread. W returns `ShutdownInProgress` while A is still held.
- `Close()` passes the waiter drain and is held there until A, released, has returned OK. Close then finishes, and a reopen has A.
- Run under TSan and ASan.
- Neuter, shutdown leg removed: "a write never returned" (abort after 30 s).
- **Q3** `GateFailedWriteNeverSurvivesRecovery`:
- Three legs: `Resume()`, auto-resume, and reopen with the error still set (PIT). In each, A on partition 0 fails (retryable) after B on partition 1 has inserted above it.
- After recovery: `Get(B)` is NotFound, no live SST holds B (scanned with `SstFileReader`), and writes resume on both partitions.
- A crash-like reopen (no flush at close) then has every acknowledged write and still not B.
- Neuter, floor removed (`UnreleasedWalGateFenceLow` returns max): `Get(B)` is "value" and an SST holds it.
- Crash before Resume: GC08's `CrashAtPartitionFailureRecoversAcknowledgedSet`, unchanged.
- **Q4** `UnrelatedErrorLeavesParkedWriteToComplete`:
- Soft (compaction NoSpace): a held write at N=1 returns OK (parity). At N=2, W parked behind held A wakes, parks again exactly once (no spin over a 100 ms window), and returns OK after A.
- Fatal (flush IOError): the same at N=2, and a new write fails with the error.
- The converted `CompactionErrorWakesParkedGate` shows the same with a real fatal compaction error.
- Neuter, fail on any recorded error: W fails on the wake instead of parking again (park count 1, waiter count 0).
- **Q5** `WriteHeldPastRecoveryStillFails`:
- B is held at `DBImpl::RunCompletionGate:BeforeWait` (new test-only sync point) after its insert. A fails (retryable) and auto-resume completes.
- `Get(B)` is NotFound. B, released, returns the IOError. After a reopen B is still absent, and later writes succeed.
- Neuter, covered path skips the fence: B returns OK.
- **Insert fence**: `MemtableInsertFailureFailsParkedWrite` (GC08) passes unchanged. Neuter, no insert fence: "a write never returned".
- **`ClearBGError` ordering** (fences closed before `is_db_stopped_` clears): argued, not tested. The race it closes needs a leader to pass `PreprocessWrite` and allocate inside one `ClearBGError` hold.
## Changes to existing tests (Invariants 4 and 7)
Every change replaces "fail on a background error no failed append backs" with the (b) outcome, or drives the wake with a real append failure. All of these tests are D123701876's (`sl annotate`: f0e61e43f769).
- `DurabilityWaitErrorBeforeAdvanceFailsWaiter`: three partitions. W parks behind held A and held F; F's append (below W) fails while A is held. W fails promptly with that error, and A completes OK afterwards.
- `CheckThenParkRaceWakesWaiter`: three partitions. W is held at `BeforePark` after its check; F's append below W then fails, and its wake and fence block on the mutex W holds. W, released, must fail (a lost signal hangs the test).
- `CompactionErrorWakesParkedGate` (round 12.1): the real compaction error still wakes W through the hook (one wake). W parks again exactly once, returns OK after A, and a new write fails with the error.
- `SuppressedErrorLeavesGateUndisturbed`: the first two legs are unchanged. In the last leg the unsuppressed synthetic error still lands and wakes, but W returns OK after A. Q1's "passes unmodified" conflicts with (b) for this leg; see Assumptions.
- `LeadershipSyncFailureWakesParkedGate`: C's failed leadership sync fences C's range, which lies above W, so W returns OK after A. That matches one WAL acknowledging an async write whose append landed before a later sync failed.
- `GatePostWaitSyncFailureWakesParkedGate`: B's post-wait sync failure (no range) wakes W, which parks again once while M is held. M's append below W then fails W.
- `DurabilityWaitAdvanceRacesError`: unchanged and passing. Its OK branch is the (b) outcome.
- GC08's tests all pass unmodified, including the disabled landed-record test (still disabled) and `FileScopedFailureStaysStoppedAsAtOnePartition`.
## Fold-back split (for M3; hunk → absorbing diff)
- **D123551605 (completion gating):**
- `db_impl.cc`: the `CancelAllBackgroundWork` signal, the `CloseHelper` drain and its `WalDurabilityWaitersLeft` sync point (new code).
- `WaitForWalDurability`: the shutdown leg, the waiter count moved under the gate mutex, and the last-out signal.
- `RunCompletionGate:BeforeWait` sync point.
- `db_impl.h`: the cv and waiter-count comments.
- **D123701876 (wake gates on background error; D-1 for gates):**
- `WaitForWalDurability`: the fence checks on all three covered paths, and the bg-error exit replaced by the fence exit. **Exception to the map:** they are D123551605 lines, but the fence is fed by D123701876's failed-range recording.
- Fence state and functions: `InstallWalGateFence`, `WalGateFenceStatus(Locked)`, `UnreleasedWalGateFenceLow`, members and declarations.
- Fence install in `WALIOStatusCheck`; fence close and iterator gap in `ClearWalDurabilityBGError`.
- The hook and flag comments.
- `HandleMemTableInsertFailure`: the fence, its signature, and its five call sites (upstream lines, D1 purpose).
- `error_handler.{h,cc}`: the `HandleKnownErrors` override plus its `wal_related` parameter, and the `ClearBGError` reorder (GC08's line).
- `flush_job.{h,cc}`: `SequenceFloorIterator`, `DropEntriesAtOrAbove` and the count adjustment (new code); `db_impl_compaction_flush.cc`: the two `DropEntriesAtOrAbove` calls.
- Tests: the 6 converted ones; the new tests on GC08's `DBWalAppendFailureTest` fixture, plus `SuppressAllBgErrorsListener`, `LiveSstHasKey` and the `sst_file_reader.h` include. **Exception:** the Q2 tests belong to D123551605's purpose, but the fixture exists only from D123701876.
- **D123079329:** none (insert and publish ordering unchanged).
- **Q6:** no code.
## Assumptions (`AB-Implementation-Requirement.md` §4)
1. D-N71's dispatcher cell was blank, so I implemented (b) (rule 2).
2. `SuppressedErrorLeavesGateUndisturbed`, `LeadershipSyncFailureWakesParkedGate` and `GatePostWaitSyncFailureWakesParkedGate` also had to change. Each fails a parked write on an error that no failed range at or below it backs. Invariant 4 says "at least", and (b) decides (rule 2). Q1's "passes unmodified" for the first one conflicts with (b); (b) wins as the explicit decision.
3. Q1's `!allow_auto_recovery` evidence leg: no WAL append path can reach it. The retryable / auto-resume-off case is tested as already unsuppressible at both N (rule 2/5).
4. Q1 scope: every write-path WAL error at N>1 (all `WALIOStatusCheck` errors, which GC08 already escalates), not only pinned appends. This is the single classification point and the least code (rule 5).
5. A failed memtable insert counts as "a range at or below the target failed" for (b). Otherwise a write parked above it never returns (rule 5, fail closed).
6. Q2 guarantee scope: writes parked when shutdown begins. The test holds `Close()` after the drain until the held lower write finishes, because a write still running during teardown is concurrent with `Close()` (rule 2: "writes concurrent with Close() remain unsupported").
7. Q3 resume legs use a retryable error that is not file-scoped: file-scoped live resume is NotSupported at N>1 (Q6 (a)). "Crash" is a process crash, i.e. a close with no flush on GC08's failing-FS fixture, not `FaultInjectionTestFS` power loss. The pre-Resume crash leg is GC08's unchanged test (rule 5).
8. The flush floor applies to every flush while an unreleased fence stands, which in practice means only recovery flushes (rule 5).
9. Gate failure status: the background error recorded with the failure, kept with the fence, so it is still returned after recovery clears the error. No new status (rule 2, Q5 "expected outcome is the background error").
10. Q6: option (a) (rule 5: fail closed, keep upstream policy).
11. Notes commit `JustinGaoNotesChanges` (`7a4629ff63a5`) was found; the on-disk doc is identical.
## Not done
- None of Q1–Q6 is open. Residuals outside this doc:
- D-1 landed-record replay (`DISABLED_CrashAfterLandedFailedAppendRecoversNoFailedWrite`).
- Archived-WAL `GetUpdatesSince` after a reopen (the gap tracker is per process, as upstream's; GC12).
- The open hazards G-18, G-19, N-3-1, N-3-2, G-11.
Test Plan:
At this commit (dev mode, ASan/UBSan unless noted):
- `buck2 test fbcode//internal_repo_rocksdb/repo:{db_write_test,db_wal_test,error_handler_fs_test,db_basic_test,db_log_iter_test,transaction_test,db_flush_test,flush_job_test}`: Pass 6009, Fail 0. That run predates the last amend, which only changed `ExpectCloseWakesParkedWrite`'s synchronization (TSan). `db_write_test` was rerun in full on the final tree: Pass 277, Fail 0.
- TSan (`@fbcode//mode/dev-tsan`): every new and changed test, plus all of `DBWalAppendFailureTest` and `DurabilityWaitAdvanceRacesError`. Pass 34, Fail 0, no reports. An earlier run caught a test-only race (the parked writer's `handles_` read vs. the closing thread, ordered only by a relaxed counter); it is fixed by confirming the park under a mutex.
- ASan: the Q2 tests in the suite run and the 100-repeat run.
- 100 repeats (`--gtest_repeat=100`, ASan): the 7 new tests, the 6 converted tests, `DurabilityWaitAdvanceRacesError` and `MemtableInsertFailureFailsParkedWrite`: 100/100 iterations, 2100 test runs (21 instances per iteration; the `/1` two-write-queue variants of `DBWritePartitionTest` bypass themselves), 0 failures.
- Neuters: each listed under Evidence, each run and failing as described.
- N=1 byte identity (`db_bench fillseq --num=10000 --seed=20260928 --threads=1 --disable_auto_compactions=1`, dev mode, one live WAL):
- Indexing off: `6d1351117a289a2784449a68d5421b1aa385ab0b383273c2c5918befa9181b09`.
- `partition_by_column_family`: `9a69a3fc66777fadce05e8a999479a5f57364aca27cd6d22aa00e4631adfc796`.
- Both equal the values GC08 measured on this base tree (59771e158a15) and earlier rounds. The base was not rebuilt here.
- Blackbox crash test: `tools/db_crashtest.py blackbox --duration=180 --interval=30 --wal_partitions=1 --partition_wal_usage=partition_by_column_family` with `--stress_cmd` set to db_stress from this commit (dev mode): 7 db_stress runs, exit 0.
- Format and lint:
- Repo-pinned clang-format 21.1.2 is clean on every touched file (`arc f` runs nothing here). Pre-existing violation left alone: `db_impl.cc` include order.
- `arc lint -a`: no lint issues.
- `make check-sources` was not run; the only non-ASCII in touched files is pre-existing (`db_write_test.cc` comments).
- Not run: `@mode/opt` builds, and a performance benchmark. The hot-path cost is two acquire loads after the covered check.
Differential Revision: https://phabricator.intern.facebook.com/D127204780
fbsource-commit: 9f54ad1b30b1
Owner
Author
|
Folded at M3 into pwal/m3 (see M3-FoldTasks.md). |
JustinGaoF
added a commit
that referenced
this pull request
Nov 9, 2026
…partitions (M2.9) Summary: **Question for the reviewer:** should every partition keep rotating whenever any partition does (the base's coupled policy), or should each partition rotate on its own? This diff keeps coupled rotation. The measurement below shows that independent rotation would save file creates but would make WALs unreclaimable or lose data on recovery, unless the MANIFEST gains per-partition log numbers. **Measurement (skewed workload, N=4).** 2,000 x 1 KB writes go to partition 1, 20 small writes to partition 2, and none to partitions 0 and 3. Write buffer is 64 KB and flushes are held so every WAL is still alive when counted. This produced 35 memtable switches. | | coupled (measured) | independent, rotate only if non-empty (modeled from the same per-file sizes) | |---|---|---| | WAL files created | 144 (36 per partition) | 59 (hot 36, cold 21, idle 1 + 1); 39 with a size floor above 25 B | | files with no data | 88 (both idle partitions' 72, plus 16 of the cold one's) | 2 | | bytes in quiet partitions | cold: 488 B over 20 files; idle: 0 B | same | | WALs left after flushing every CF | 4 (one current per partition) | 59: nothing reclaimable | The independent column is a model, not an implementation, and its retention row is why. Routing sends a write to the partition of its batch's lowest CF id, so one CF's records can land in any partition. Recovery skips a record whose WAL number is below the CF's log number (`write_batch.cc:2255`). A partition that skips rotation keeps an old-numbered WAL that later writes still append to. So either the CF log number stays at or below every partition's current WAL, and an idle partition's first WAL pins the global floor forever (invariant 2 broken: none of the 55 closed files can be reclaimed, and one more is pinned per hot rotation), or the CF log number advances and those later records are silently skipped on recovery (invariant 1 broken). Fixing that takes per-partition floors persisted in the MANIFEST. Coupled rotation pays only file creates: 3 extra per switch at N=4, each empty file 0 B unindexed or one 7/11 B marker indexed. Reclamation stays a single global floor, and partition 0's deque front stays the global oldest WAL, which `SwitchWAL` relies on. **Changes** - **Keep:** coupled rotation in `SwitchMemtable`, unchanged. `min_log_number_to_keep` stays global. - **Add (R5): recovered WALs return to the partition that wrote them.** The WAL index marker gains an optional fixed32 payload holding the partition. It is written only for partitions above 0, so partition 0's file, and every single-partition WAL, keeps the empty marker byte for byte. `CreateWAL` takes the partition. The classification pass that already reads each WAL's head at recovery (`CheckWALFilesCarryWALIndex`) records it, and `RestoreAliveLogFiles` pushes each closed WAL into that partition's deque. WALs with no marker (unindexed, written before partitioning), an empty payload, or a partition at or above the current N go to partition 0. Deques stay ascending because recovery walks WAL numbers in order, and each partition's new current WAL is still created at open, numbered above every recovered file. - **Fix (R6):** when `CreateWAL`/`StartWALFile` fails during rotation, `SwitchMemtable` now wakes parked completion gates (`SignalWalDurabilityWaitersOnBGError`, with `mutex_` released) the same way an append failure does. Before, it set the background error without the durability flag or the wake. It wakes only when the background error is actually non-OK, so it does not take on 09's listener-suppression issue (09.1 #3). - **Change (R7):** the N>1 rejection message drops "WAL rotation". It now reads "unindexed multi-WAL recovery is not implemented". The rejection itself stays. - **Test-only:** `WalAppendOutcome` gains `wal_number`; adds `TEST_AliveWalFiles(p)` and `TEST_CurrentWalNumber(p)`. **Placement is policy; the current WAL is correctness.** A recovered WAL is closed and never written again. `FindObsoleteFiles` checks every deque entry against the same global floor, so the deque only decides retirement order. What must be right is each partition's `back()`, the file `SelectWalForWrite` appends to. Open already creates those, and the tests check them. **Compatibility.** Readers from before this diff never parse the marker payload. They still read p>=1 files and place everything in partition 0, the base behaviour. New readers treat an empty payload as partition 0. No filename, MANIFEST, backup, or checkpoint change. Paths that skip the classification pass (`track_and_verify_wals` with indexed WALs) also fall back to partition 0. **R6 analysis.** Rotation waits behind every in-flight leader: write-path switches wait in `CloseMemTableSwitchGate`, and external switches enter all N queues. So a held append delays the rotation; it is never an error and never deadlocks. Its record lands in the pre-switch WAL and memtable, and that WAL stays alive. One consequence: when `CreateWAL` runs, no completion gate can be parked on an unfinished range. The wake therefore mainly matters for gates arriving afterwards, which now fail fast on the flag instead of the 1 ms poll. The test records zero parked waiters at the moment of failure. **Not changed:** when memtables rotate, flush policy, `db_stress`/crashtest wiring, unindexed multi-WAL recovery, production N>1, and 09's known issues (scheduled as 09.1). **Folded in from round 12 (D124911745) and round 12.1 (D125113461)** - R6: a rotation `CreateWAL` failure wakes gates through the shared error-handler hook (see D123701876). `SwitchMemtable` therefore has no explicit wake and no mutex dance, which replaces the R6 Fix bullet above. `RotationWalCreationFailureWakesGates` also checks that a write after the failure fails fast with IOError while waiters stay 0. - Durability on the filesystem: `SyncWriteMakesPriorPartitionAppendSurviveCrash`. - Setup: an async write A, then a sync write B. A is released only after B parks in its gate, so only the post-wait sync can save A. - Crash: unsynced data is dropped and the DB recovers indexed at N=2. A and B are present, and a later unsynced control write is absent. - A `Defer` closes the DB on every exit path. - Neuter: disable the post-wait sync -> `key_a` NOT_FOUND -> fail. M1: absorbs 25 entries: GC01 N>1 gate + marker size check + log_test (6), GC02 `SupersessionsAreDurableWhenOpenReturns` + include (2), GC04 void seeding/clause/tests (8, with GC05's enable), GC05 void read/clamp/ tests (5), GC13 `LeadershipSyncRecordsWalsBelowClaimHorizon`, GC16 Q7 skew-test change (3). X5-X7 moved here (need `recovered_wal_partitions_`); GC04#57-clamp remainder stale (already at D120649665, dropped). `TEST_WalSyncMarks` decl moved after `TEST_CurrentWalNumber` (T0 spot; empties GC03#136). `kWalPartitionsRe- jection` updated to T0 text (X10). Gate: lib builds; `db_write_test` 189/0; `db_wal_test` 2069/0; `log_test`+`db_options_test` 538/0. M2 fold (2026-10-22, `M2-FoldTasks.md` + `M2-Amendment.md`): Absorbs (M2) GC11 Q1/Q4/Q5: predecessor spans at `CreateWAL` and rotation (exception X8: the rotation lambda uses `WalLogs(p).back()` here; D123971668 rewrites it), progress seal, `HeadBounded`, routing by markers and guard, `merge_from`, kNone-opener flush (exception X7), `NewestWalPerPartition`, recovery tests, `SwitchedWALCarriesWALIndexOnDisk` (exception X9); GC06 Q10 cut tests and helpers, gate comment/message/constant (AMB-M2-1), clamp comment (exception X1); GC07 `RotationWaitsForHeldAppendAndKeepsItsWal` and `ChangeStreamStopsBelowHeldLowerWrite`; GC07a (D127011765) test `FailedSyncTrackingReleasesItsRange` (exception: it needs N>1 rotation, first here). M3 fold: Absorbs - GC12 Q6 history-floor call (it reads recovered_wal_partitions_) with FirstSessionBottomLossIsDetected and HistoryFloorOffAfterFlush; Q7 StartWALFile:WriteSpan sync point; Q8 test edits (GapWALCut comment, FrontierWALCut literal keys, DeletedOldestPartitionWalIsDetected cut assertion, ManifestTrackedMissingWALFailsEveryMode, SupersessionNamingTrackedMissingWALFailsOpen). Exception X1: GC12's Q1 copy tests CheckpointAndBackupCopyEveryPartitionsWal, ConcurrentCheckpointIsAPrefixOfAckedWrites and GetCurrentWalFileRefusesAtNAboveOne, with ReadFromCopy and their includes. Exception X2: ConcurrentIngestionKeepsWritesAndIngestedKeys. - GC08: the paranoid_checks edits of five cut tests; exception X6 (AMB-M3-5): the FailingWalFS / DBWalAppendFailureTest fixture with all 15 of GC08's fixture tests (FenceHidesFailedWriteFromWalIterator in GC08's pre-S2 form, X7, AMB-M3-13). - GC09: its 6 fixture tests, SuppressAllBgErrorsListener, LiveSstHasKey and the sst_file_reader.h include (X6). - GC14a Q5: RotationWalCreationFailureWakesGates comment. - GC17: WriteAdmittedByRecoveryAllocatesAboveFences (X6); SyncWriteAboveAsyncWriteSurvivesCrash and AckedAsyncWriteAboveUnsyncedHoleIsCut (exception X10). Test Plan: Base: `794d778d7d94` (pinned 09, D123701876). Commit created with `--config commit.modify-obsolete-mode=warn` (user-approved) because the pinned hash has newer versions; nothing below it was touched. **Required suites** (`buck2 test`, dev mode), 7 targets: 3,212 pass, 0 fail, 0 timeout. - `db_wal_test`, `db_flush_test`, `deletefile_test`, `db_basic_test`, `db_write_test`, `log_test`: pass. - `db_test2`: that target does not exist at this base (`Unknown target`). `DBTest2` now lives in `db/db_etc2_test.cc`, so `db_etc2_test` was run in its place: pass. - Every test passing on the parent still passes, unmodified (invariant 6). Existing tests were only extended through new fixture helpers. **New tests** (`DBWritePartitionTest`, both `two_write_queues` params; N>1 reopen cases use the `AllowWalPartitions` hook, `partition_wal_usage`, and `two_write_queues=false`, and return early when the parameter is true): - `SkewedWritesRotateEveryPartitionAndReclaim` (R1/R3, invariants 1-3): per-partition file counts, empty quiet files, nothing deleted before flush, every partition down to its current WAL afterwards. Produced the measurement in the summary. - `RotationWaitsForHeldAppendAndKeepsItsWal` (R6): A is held either inside its append (B on another partition parks behind it) or between append and memtable insert. The switch waits with no rotation and no error over a bounded 200 ms window. After release, all writes complete; `AppendOutcome` shows A and B in their partitions' pre-switch WALs; A's WAL is still alive; reopen recovers both. - `RotationWalCreationFailureWakesGates` (R6): partition 1's `StartWALFile` fails mid-rotation. The flush returns IOError, the wake fires exactly once, the flag is set, 0 waiters were parked at the failure, no partition's deque changed, and the next write fails. - `ReopenRestoresWalsToTheirPartitions` (R5, invariants 3-4): 3 WALs per partition at N=4 return to their own deques in order, followed by the new current. New appends land in `TEST_CurrentWalNumber(p)` (checked through `AppendOutcome`). Partition 0's front is the global minimum. A full flush retires every recovered WAL, on disk too. - `ReopenPlacesUnpartitionedWalsInPartitionZero` (R5): WALs from N=1, both unindexed and indexed, go to partition 0 at N=2; data intact; retirement empties partition 0. - `ReopenWithFewerPartitionsPlacesOrphansInZero` (R5): N=4 WALs reopened at N=2. Partitions 2 and 3 merge into partition 0 in ascending order; FIFO retirement holds. - `CrashMidRotationUnderSkewRecoversPrefix`: `FaultInjectionTestFS`, skewed history over two rotations, a synced write at 119 of 150, then a rotation dies after partition 0's new WAL starts and before partition 1's. Unsynced data is dropped and the DB reopened through the hook. Recovered keys form a prefix that includes everything up to the synced write; deques are consistent. - `LogTest.WALIndexMarkerRecordsPartition`: the payload is 4 bytes and round-trips through both readers. The existing `WALIndexMarkerRecordIsEmpty` still pins partition 0's empty marker. - Flakiness: the 14 new cases with `--gtest_repeat=20`: 280/280 pass. **Neuter checks** (each production change reverted locally, test rerun): - `RestoreAliveLogFiles` always uses partition 0: `ReopenRestoresWalsToTheirPartitions` and `ReopenWithFewerPartitionsPlacesOrphansInZero` fail. - Writer never emits the payload: the same two fail, plus `WALIndexMarkerRecordsPartition` under every parameter. - Partition >= N bound removed: `ReopenWithFewerPartitionsPlacesOrphansInZero` aborts on the `AliveWalFiles` bounds assert. - `SwitchMemtable` wake removed: `RotationWalCreationFailureWakesGates` fails (0 wakes, flag false). - `CloseMemTableSwitchGate` made not to wait for leaders: `RotationWaitsForHeldAppendAndKeepsItsWal` fails (a rotation lands while A is held). Holding A only inside its append is not enough by itself, because `WalWriteMutex(0)` also serializes the switch; that is why the test also holds between append and insert, plus the bounded window. - No neuter: `SkewedWritesRotateEveryPartitionAndReclaim` and `CrashMidRotationUnderSkewRecoversPrefix` pin base behaviour this diff keeps. `ReopenPlacesUnpartitionedWalsInPartitionZero` expects partition-0 placement, so it passes under neuter 1 by design. **R4, byte identity at N=1:** `db_bench --benchmarks=fillseq --num=10000 --threads=1 --seed=20260928 --compression_type=none --avoid_flush_during_shutdown=true`, built at base and at this diff. - Unindexed WAL: `cmp` identical, SHA-256 `6d1351117a289a2784449a68d5421b1aa385ab0b383273c2c5918befa9181b09`, 1,380,286 B. This matches the hash reported by the diffs below. - Same command with `--partition_wal_usage=kPartitionByColumnFamily`: identical, SHA-256 `9a69a3fc66777fadce05e8a999479a5f57364aca27cd6d22aa00e4631adfc796`, 1,460,277 B. **TSAN:** `@fbcode//mode/dev-tsan` `db_write_test --gtest_filter='DBWritePartitionTest*'`: 58/58 pass, no ThreadSanitizer reports. **db_stress blackbox / crashtest:** not run. The tool lacks `wal_partitions` support, and adding it is out of scope. **Known 09 issues (09.1):** none observed; no new test was flaky or slow through them. **Formatting / lint:** repo-pinned clang-format 21.1.2 via `clang-format-diff.py` over every changed range: no changes. `arc f`: "No linters to run" for this subtree. `arc lint -a` on all 11 files: no lint issues. No non-ASCII in added lines. **Not run:** CMake/Make builds, macOS, Windows. **After folding in round 12 / 12.1 (D124911745, D125113461):** - `buck2 test fbcode//internal_repo_rocksdb/repo:db_write_test fbcode//internal_repo_rocksdb/repo:error_handler_fs_test` at this commit: Pass 238, Fail 0 (https://www.internalfb.com/intern/testinfra/testrun/1125900446553732). - Neuter, TSan and byte-identity evidence for the folded-in items: see the Test Plans of D124911745 and D125113461. They ran on the same code, now split across this stack. M1: absorbs 25 entries: GC01 N>1 gate + marker size check + log_test (6), GC02 `SupersessionsAreDurableWhenOpenReturns` + include (2), GC04 void seeding/clause/tests (8, with GC05's enable), GC05 void read/clamp/ tests (5), GC13 `LeadershipSyncRecordsWalsBelowClaimHorizon`, GC16 Q7 skew-test change (3). X5-X7 moved here (need `recovered_wal_partitions_`); GC04#57-clamp remainder stale (already at D120649665, dropped). `TEST_WalSyncMarks` decl moved after `TEST_CurrentWalNumber` (T0 spot; empties GC03#136). `kWalPartitionsRe- jection` updated to T0 text (X10). Gate: lib builds; `db_write_test` 189/0; `db_wal_test` 2069/0; `log_test`+`db_options_test` 538/0. M1 re-verification (2026-10-20, after rebasing the stack onto master f0c3a35689fc and clang-formatting): per-diff gate at this diff passed (CI format check, `rocksdb_lib` build, touched test targets); tip suites 8126/0; N=1 byte identity equals T0. M2 fold: new or moved tests here: Torn/Gap/Frontier/SkipMode cut tests, FrontierCutKeepsIgnoredRecordBelowSeedLive, DataLessTornPartitionWalIsABoundedTail, DeletedOldestPartitionWalIsDetected, DamagedPartitionWalHeadIsBoundedPerMode, ReopenWithChangedPartitionsWritesSpans, RotationSealsEveryRetiringPartitionWal, SkipModeFailsOnPristineHoleAndSaysWhy, MissingTrackedWalFailsTheOpen, OpenerUsageDoesNotDecideTheMerge, RecoveryTrimsEachPartitionsNewestWal, ChangeStreamStopsBelowHeldLowerWrite, DeletedOldestWALIsDetectedAtOneWAL, SpanlessWALsRecoverAloneAndWithNewOnes, PreparedUnindexedWalSurvivesPartitioning, FailedSyncTrackingReleasesItsRange. B.1 at this diff (format check, `rocksdb_lib`, touched test targets): PASS; db_options_test + db_wal_test + db_write_test + log_test + transaction_test 5959 pass. M3 B.1 at this diff (clang-format 21.1.2 on its changed lines, make check-sources, debug build, touched test binaries): PASS; db_options_test + db_wal_test + db_write_test + log_test + transaction_test: 6018 pass. M4 fold: Absorbs - Fixture tests of GC18, GC20, GC21 and GC24 and their GC25 rewrites (exception X7): FailedGateSyncWriteStaysInvisible, SyncZeroCountWriteAfterSyncWriteSyncs, FailedGateSyncStaysInvisibleAtNPartitions, FailedGateSyncFenceGoesInWithItsError, ResumeFailsWhenBurnedIndexCannotBeExplained, FailedGateSyncRangeDeletionStaysHidden, FailedZeroCountGateSyncRecordsNoIndeterminate, the GC24 ports; WriteAdmittedByRecoveryAllocatesAboveFences' fence assertions; the H1 repro SyncPrepareAfterSyncCommitSurvivesCrash (keeps its test hook below the flip). - GC25: SyncWriteVisibleOnlyOnceDurable, FailedSyncReopenWithoutResumeMayRecoverIt, FailedSyncCommitAndPrepareNeverVisible (exception X20). - GC21 Q1: ResumeImpl calls ExplainBurnedWALIndices; GC26 Q5(b): ResumeImpl takes the full recovery path while a burned index is pending at N>1 (exception X21, AMB-M4-17); GC24RetryFlushRecoveryWithBurnedIndexProgresses. - GC19 Q3/Q5 (exception X10, AMB-M4-12): merge_from filter, supersession routing and legacy prefix, with their DBWALIndexTest tests and GC23 Q5's InterleavedMixedSetWithSupersessionsFailsClosed (exception X27: moved up from D120415420); GC24 Q1 WriteWALIndexHeadFloors (exception X13: hand-ported with CurrentWalOrNull(p) written inline, AMB-M4-3) and Q6's void refusal. - GC26 Q2: RecoveredWALIndexPredecessors and WriteFurtherWALIndexPredecessors; Q3: the true-alternation gate, the unindexed suffix replayed after the merge, the prepare pin; FailingWalFS::Landing, AssertSkipOpensCopy and the D-10 skip cells of this diff's tests; GC26ColumnFamilyRefusalsHoldAfterOpen. - Net-zero pairs dropped (rule 2.7): none. M4 B.1: PASS (clang-format 21.1.2 on the changed lines, make check-sources, debug build of db_options_test, db_wal_test, db_write_test, log_test, transaction_test, write_prepared_transaction_test); 6913 tests, 0 failed. M5 fold: Absorbs 110 A.1 entries (GC28 1, GC27 17, GC30 10, GC29a 11, GC31 4, GC32 30, GC29b 37): GC27 Q1 (floors, record_cut at the seed, the end-check refusal), Q5 (a) (merge selection), FailingWalFS edits, GC31's per-partition size account in RestoreAliveLogFiles (X17-M5), tests on DBWalAppendFailureTest and ReopenWithPartitions; the GC32 test block (all but three) and its changed tests; GC32's ExplainBurnedWALIndices call; GC29b Q8 tests and T3; tests of GC30/GC31 that need this fixture. Not here after B.1: SyncFailureWithoutBackgroundErrorAfterInsertNeverPublishes and DBStatsExactUnderConcurrentLeaders go to D123971668 (X40-M5, X41-M5); FenceHidesFailedWriteFromWalIterator's T7 leg, FileScopedFailureResumesLive, FileScopedResumeKeepsManifestWalSetConsistent, FailedSyncLedGroupReleasesEveryRegisteredRange and FileScopedResumeHoldsAllocationUntilFencesClose go to D127093323 (X39-M5). M5-F1 (A.8): F1.1: FileScopedResumeStragglerAboveReservation (each recovery mode reopened); F1.2 (Close lost wakeup, X24-M5): ClearBGError signals bg_cv_, CloseHelper's WaitForRecovery sync point, DBErrorHandlingFSTest.CloseWaitingOnDirectErrorClearReturns; F1.3: join-first edits of SyncLedGroupAsyncMembersReturnBeforeFsync and ImportWaitsForPendingSyncGroup. Exceptions: X34-M5: GC30LiveSstHasKey, SyncFailureWithoutBackgroundErrorAfterInsertNeverPublishes, SwitchWaitsForGroupInsertedBeforeAppend (GC30#245, with GC29b#609 and meta#611) and FailedSyncDropKeepsBelowFenceRangeTombstone (GC31#407, with GC29b#634) moved here from D123701876: rocksdb/sst_file_reader.h is included from this commit (B.1: 'SstFileReader' was not declared); X38-M5: SyncCommitCallbacksWaitUntilGroupCannotFail (GC30#268, with GC29b#684) moved from D123701876 to D123928339: its reopen after the failed sync, Resume() and rollback needs this commit's recovery of the retired WAL (B.1 at D123701876: "SST file contains data beyond the point of corruption"); X39-M5: GC32#447 (WALIOStatusCheck skips the indeterminate-sequence record above one partition) moved from D123701876 to D127093323, with the tests that need it: FenceHidesFailedWriteFromWalIterator's T7 leg (GC29a#291, GC32#452), GC32#455's FileScopedFailureResumesLive, FileScopedResumeKeepsManifestWalSetConsistent and FailedSyncLedGroupReleasesEveryRegisteredRange (with GC29b#550, meta#652, meta#653) from D123928339, FileScopedResumeRacesSyncWalAndSyncWrite (with GC29b#648-meta#651 and F1.3's edits) from D123971668, and F1.1's FileScopedResumeHoldsAllocationUntilFencesClose from D123928339. GC32#447 rests on GetUpdatesSince being refused above one partition, which this commit brings; below it M4's FenceHidesFailedWriteFromWalIterator reads the record's fence through the iterator (B.1 at D123928339: the iteration ended OK, not NotFound), and without GC32#447 the release's gap record meets the per-failure record in every N>1 file-scoped resume those tests drive (B.1: "Assertion it->second.wal_number == wal_number failed"); X40-M5: SyncFailureWithoutBackgroundErrorAfterInsertNeverPublishes (GC30#245, with GC29b#609) moved from D123928339 (X34-M5) to D123971668, the lowest commit where it passes (B.1 at D123928339: the sync write did not fail Aborted and the key read back); X41-M5: DBStatsExactUnderConcurrentLeaders (GC31#407, with GC29b#623) moved from D123928339 to D123971668, the lowest commit where it passes (B.1 at D123928339: WAL_FILE_SYNCED counted more syncs than db.wal_syncs). X14-M5 hook (rule 2.4): the AllowWalPartitions callback before the first N>1 open of WritePreparedPartitionedWalTest.SyncCommitCallbacksWaitUntilGroupCannotFail (X38-M5; after its ClearAllCallBacks: before Reopen and before the next iteration's Open); FLIP removes it. M5 B.1: PASS (clang-format 21.1.2 on the changed lines, make check-sources, debug build of db_options_test, db_wal_test, db_write_test, error_handler_fs_test, log_test, transaction_test, write_prepared_transaction_test); 7070 tests, 0 failed. M6 fold: Absorbs the GC34 Q1 `record_cut` comment; the rewritten `ExpectCloseWakesParkedWrite` (GC34 Q3) and the `WalOnlyWrite` helper; the `DBWalAppendFailureTest` stack-owner follow-up (`Writer` joins in its destructor after abandoning test holds, `Writer::WaitDone`, `HoldNextAppend` and the test-local holds wait through `WaitForReleaseOrAbandon`, the fixture clears the flag); GC34 Q5 (b) release-and-bail paths and EXPECT sweeps in tests owned here. M6 B.1: PASS (debug build and build_tools/gtest-parallel run of db_options_test db_wal_test db_write_test error_handler_fs_test log_test transaction_test write_prepared_transaction_test: 7070/7070). Differential Revision: https://phabricator.intern.facebook.com/D123928339
JustinGaoF
added a commit
that referenced
this pull request
Nov 10, 2026
…partitions (M2.9) Summary: **Question for the reviewer:** should every partition keep rotating whenever any partition does (the base's coupled policy), or should each partition rotate on its own? This diff keeps coupled rotation. The measurement below shows that independent rotation would save file creates but would make WALs unreclaimable or lose data on recovery, unless the MANIFEST gains per-partition log numbers. **Measurement (skewed workload, N=4).** 2,000 x 1 KB writes go to partition 1, 20 small writes to partition 2, and none to partitions 0 and 3. Write buffer is 64 KB and flushes are held so every WAL is still alive when counted. This produced 35 memtable switches. | | coupled (measured) | independent, rotate only if non-empty (modeled from the same per-file sizes) | |---|---|---| | WAL files created | 144 (36 per partition) | 59 (hot 36, cold 21, idle 1 + 1); 39 with a size floor above 25 B | | files with no data | 88 (both idle partitions' 72, plus 16 of the cold one's) | 2 | | bytes in quiet partitions | cold: 488 B over 20 files; idle: 0 B | same | | WALs left after flushing every CF | 4 (one current per partition) | 59: nothing reclaimable | The independent column is a model, not an implementation, and its retention row is why. Routing sends a write to the partition of its batch's lowest CF id, so one CF's records can land in any partition. Recovery skips a record whose WAL number is below the CF's log number (`write_batch.cc:2255`). A partition that skips rotation keeps an old-numbered WAL that later writes still append to. So either the CF log number stays at or below every partition's current WAL, and an idle partition's first WAL pins the global floor forever (invariant 2 broken: none of the 55 closed files can be reclaimed, and one more is pinned per hot rotation), or the CF log number advances and those later records are silently skipped on recovery (invariant 1 broken). Fixing that takes per-partition floors persisted in the MANIFEST. Coupled rotation pays only file creates: 3 extra per switch at N=4, each empty file 0 B unindexed or one 7/11 B marker indexed. Reclamation stays a single global floor, and partition 0's deque front stays the global oldest WAL, which `SwitchWAL` relies on. **Changes** - **Keep:** coupled rotation in `SwitchMemtable`, unchanged. `min_log_number_to_keep` stays global. - **Add (R5): recovered WALs return to the partition that wrote them.** The WAL index marker gains an optional fixed32 payload holding the partition. It is written only for partitions above 0, so partition 0's file, and every single-partition WAL, keeps the empty marker byte for byte. `CreateWAL` takes the partition. The classification pass that already reads each WAL's head at recovery (`CheckWALFilesCarryWALIndex`) records it, and `RestoreAliveLogFiles` pushes each closed WAL into that partition's deque. WALs with no marker (unindexed, written before partitioning), an empty payload, or a partition at or above the current N go to partition 0. Deques stay ascending because recovery walks WAL numbers in order, and each partition's new current WAL is still created at open, numbered above every recovered file. - **Fix (R6):** when `CreateWAL`/`StartWALFile` fails during rotation, `SwitchMemtable` now wakes parked completion gates (`SignalWalDurabilityWaitersOnBGError`, with `mutex_` released) the same way an append failure does. Before, it set the background error without the durability flag or the wake. It wakes only when the background error is actually non-OK, so it does not take on 09's listener-suppression issue (09.1 #3). - **Change (R7):** the N>1 rejection message drops "WAL rotation". It now reads "unindexed multi-WAL recovery is not implemented". The rejection itself stays. - **Test-only:** `WalAppendOutcome` gains `wal_number`; adds `TEST_AliveWalFiles(p)` and `TEST_CurrentWalNumber(p)`. **Placement is policy; the current WAL is correctness.** A recovered WAL is closed and never written again. `FindObsoleteFiles` checks every deque entry against the same global floor, so the deque only decides retirement order. What must be right is each partition's `back()`, the file `SelectWalForWrite` appends to. Open already creates those, and the tests check them. **Compatibility.** Readers from before this diff never parse the marker payload. They still read p>=1 files and place everything in partition 0, the base behaviour. New readers treat an empty payload as partition 0. No filename, MANIFEST, backup, or checkpoint change. Paths that skip the classification pass (`track_and_verify_wals` with indexed WALs) also fall back to partition 0. **R6 analysis.** Rotation waits behind every in-flight leader: write-path switches wait in `CloseMemTableSwitchGate`, and external switches enter all N queues. So a held append delays the rotation; it is never an error and never deadlocks. Its record lands in the pre-switch WAL and memtable, and that WAL stays alive. One consequence: when `CreateWAL` runs, no completion gate can be parked on an unfinished range. The wake therefore mainly matters for gates arriving afterwards, which now fail fast on the flag instead of the 1 ms poll. The test records zero parked waiters at the moment of failure. **Not changed:** when memtables rotate, flush policy, `db_stress`/crashtest wiring, unindexed multi-WAL recovery, production N>1, and 09's known issues (scheduled as 09.1). **Folded in from round 12 (D124911745) and round 12.1 (D125113461)** - R6: a rotation `CreateWAL` failure wakes gates through the shared error-handler hook (see D123701876). `SwitchMemtable` therefore has no explicit wake and no mutex dance, which replaces the R6 Fix bullet above. `RotationWalCreationFailureWakesGates` also checks that a write after the failure fails fast with IOError while waiters stay 0. - Durability on the filesystem: `SyncWriteMakesPriorPartitionAppendSurviveCrash`. - Setup: an async write A, then a sync write B. A is released only after B parks in its gate, so only the post-wait sync can save A. - Crash: unsynced data is dropped and the DB recovers indexed at N=2. A and B are present, and a later unsynced control write is absent. - A `Defer` closes the DB on every exit path. - Neuter: disable the post-wait sync -> `key_a` NOT_FOUND -> fail. M1: absorbs 25 entries: GC01 N>1 gate + marker size check + log_test (6), GC02 `SupersessionsAreDurableWhenOpenReturns` + include (2), GC04 void seeding/clause/tests (8, with GC05's enable), GC05 void read/clamp/ tests (5), GC13 `LeadershipSyncRecordsWalsBelowClaimHorizon`, GC16 Q7 skew-test change (3). X5-X7 moved here (need `recovered_wal_partitions_`); GC04#57-clamp remainder stale (already at D120649665, dropped). `TEST_WalSyncMarks` decl moved after `TEST_CurrentWalNumber` (T0 spot; empties GC03#136). `kWalPartitionsRe- jection` updated to T0 text (X10). Gate: lib builds; `db_write_test` 189/0; `db_wal_test` 2069/0; `log_test`+`db_options_test` 538/0. M2 fold (2026-10-22, `M2-FoldTasks.md` + `M2-Amendment.md`): Absorbs (M2) GC11 Q1/Q4/Q5: predecessor spans at `CreateWAL` and rotation (exception X8: the rotation lambda uses `WalLogs(p).back()` here; D123971668 rewrites it), progress seal, `HeadBounded`, routing by markers and guard, `merge_from`, kNone-opener flush (exception X7), `NewestWalPerPartition`, recovery tests, `SwitchedWALCarriesWALIndexOnDisk` (exception X9); GC06 Q10 cut tests and helpers, gate comment/message/constant (AMB-M2-1), clamp comment (exception X1); GC07 `RotationWaitsForHeldAppendAndKeepsItsWal` and `ChangeStreamStopsBelowHeldLowerWrite`; GC07a (D127011765) test `FailedSyncTrackingReleasesItsRange` (exception: it needs N>1 rotation, first here). M3 fold: Absorbs - GC12 Q6 history-floor call (it reads recovered_wal_partitions_) with FirstSessionBottomLossIsDetected and HistoryFloorOffAfterFlush; Q7 StartWALFile:WriteSpan sync point; Q8 test edits (GapWALCut comment, FrontierWALCut literal keys, DeletedOldestPartitionWalIsDetected cut assertion, ManifestTrackedMissingWALFailsEveryMode, SupersessionNamingTrackedMissingWALFailsOpen). Exception X1: GC12's Q1 copy tests CheckpointAndBackupCopyEveryPartitionsWal, ConcurrentCheckpointIsAPrefixOfAckedWrites and GetCurrentWalFileRefusesAtNAboveOne, with ReadFromCopy and their includes. Exception X2: ConcurrentIngestionKeepsWritesAndIngestedKeys. - GC08: the paranoid_checks edits of five cut tests; exception X6 (AMB-M3-5): the FailingWalFS / DBWalAppendFailureTest fixture with all 15 of GC08's fixture tests (FenceHidesFailedWriteFromWalIterator in GC08's pre-S2 form, X7, AMB-M3-13). - GC09: its 6 fixture tests, SuppressAllBgErrorsListener, LiveSstHasKey and the sst_file_reader.h include (X6). - GC14a Q5: RotationWalCreationFailureWakesGates comment. - GC17: WriteAdmittedByRecoveryAllocatesAboveFences (X6); SyncWriteAboveAsyncWriteSurvivesCrash and AckedAsyncWriteAboveUnsyncedHoleIsCut (exception X10). Test Plan: Base: `794d778d7d94` (pinned 09, D123701876). Commit created with `--config commit.modify-obsolete-mode=warn` (user-approved) because the pinned hash has newer versions; nothing below it was touched. **Required suites** (`buck2 test`, dev mode), 7 targets: 3,212 pass, 0 fail, 0 timeout. - `db_wal_test`, `db_flush_test`, `deletefile_test`, `db_basic_test`, `db_write_test`, `log_test`: pass. - `db_test2`: that target does not exist at this base (`Unknown target`). `DBTest2` now lives in `db/db_etc2_test.cc`, so `db_etc2_test` was run in its place: pass. - Every test passing on the parent still passes, unmodified (invariant 6). Existing tests were only extended through new fixture helpers. **New tests** (`DBWritePartitionTest`, both `two_write_queues` params; N>1 reopen cases use the `AllowWalPartitions` hook, `partition_wal_usage`, and `two_write_queues=false`, and return early when the parameter is true): - `SkewedWritesRotateEveryPartitionAndReclaim` (R1/R3, invariants 1-3): per-partition file counts, empty quiet files, nothing deleted before flush, every partition down to its current WAL afterwards. Produced the measurement in the summary. - `RotationWaitsForHeldAppendAndKeepsItsWal` (R6): A is held either inside its append (B on another partition parks behind it) or between append and memtable insert. The switch waits with no rotation and no error over a bounded 200 ms window. After release, all writes complete; `AppendOutcome` shows A and B in their partitions' pre-switch WALs; A's WAL is still alive; reopen recovers both. - `RotationWalCreationFailureWakesGates` (R6): partition 1's `StartWALFile` fails mid-rotation. The flush returns IOError, the wake fires exactly once, the flag is set, 0 waiters were parked at the failure, no partition's deque changed, and the next write fails. - `ReopenRestoresWalsToTheirPartitions` (R5, invariants 3-4): 3 WALs per partition at N=4 return to their own deques in order, followed by the new current. New appends land in `TEST_CurrentWalNumber(p)` (checked through `AppendOutcome`). Partition 0's front is the global minimum. A full flush retires every recovered WAL, on disk too. - `ReopenPlacesUnpartitionedWalsInPartitionZero` (R5): WALs from N=1, both unindexed and indexed, go to partition 0 at N=2; data intact; retirement empties partition 0. - `ReopenWithFewerPartitionsPlacesOrphansInZero` (R5): N=4 WALs reopened at N=2. Partitions 2 and 3 merge into partition 0 in ascending order; FIFO retirement holds. - `CrashMidRotationUnderSkewRecoversPrefix`: `FaultInjectionTestFS`, skewed history over two rotations, a synced write at 119 of 150, then a rotation dies after partition 0's new WAL starts and before partition 1's. Unsynced data is dropped and the DB reopened through the hook. Recovered keys form a prefix that includes everything up to the synced write; deques are consistent. - `LogTest.WALIndexMarkerRecordsPartition`: the payload is 4 bytes and round-trips through both readers. The existing `WALIndexMarkerRecordIsEmpty` still pins partition 0's empty marker. - Flakiness: the 14 new cases with `--gtest_repeat=20`: 280/280 pass. **Neuter checks** (each production change reverted locally, test rerun): - `RestoreAliveLogFiles` always uses partition 0: `ReopenRestoresWalsToTheirPartitions` and `ReopenWithFewerPartitionsPlacesOrphansInZero` fail. - Writer never emits the payload: the same two fail, plus `WALIndexMarkerRecordsPartition` under every parameter. - Partition >= N bound removed: `ReopenWithFewerPartitionsPlacesOrphansInZero` aborts on the `AliveWalFiles` bounds assert. - `SwitchMemtable` wake removed: `RotationWalCreationFailureWakesGates` fails (0 wakes, flag false). - `CloseMemTableSwitchGate` made not to wait for leaders: `RotationWaitsForHeldAppendAndKeepsItsWal` fails (a rotation lands while A is held). Holding A only inside its append is not enough by itself, because `WalWriteMutex(0)` also serializes the switch; that is why the test also holds between append and insert, plus the bounded window. - No neuter: `SkewedWritesRotateEveryPartitionAndReclaim` and `CrashMidRotationUnderSkewRecoversPrefix` pin base behaviour this diff keeps. `ReopenPlacesUnpartitionedWalsInPartitionZero` expects partition-0 placement, so it passes under neuter 1 by design. **R4, byte identity at N=1:** `db_bench --benchmarks=fillseq --num=10000 --threads=1 --seed=20260928 --compression_type=none --avoid_flush_during_shutdown=true`, built at base and at this diff. - Unindexed WAL: `cmp` identical, SHA-256 `6d1351117a289a2784449a68d5421b1aa385ab0b383273c2c5918befa9181b09`, 1,380,286 B. This matches the hash reported by the diffs below. - Same command with `--partition_wal_usage=kPartitionByColumnFamily`: identical, SHA-256 `9a69a3fc66777fadce05e8a999479a5f57364aca27cd6d22aa00e4631adfc796`, 1,460,277 B. **TSAN:** `@fbcode//mode/dev-tsan` `db_write_test --gtest_filter='DBWritePartitionTest*'`: 58/58 pass, no ThreadSanitizer reports. **db_stress blackbox / crashtest:** not run. The tool lacks `wal_partitions` support, and adding it is out of scope. **Known 09 issues (09.1):** none observed; no new test was flaky or slow through them. **Formatting / lint:** repo-pinned clang-format 21.1.2 via `clang-format-diff.py` over every changed range: no changes. `arc f`: "No linters to run" for this subtree. `arc lint -a` on all 11 files: no lint issues. No non-ASCII in added lines. **Not run:** CMake/Make builds, macOS, Windows. **After folding in round 12 / 12.1 (D124911745, D125113461):** - `buck2 test fbcode//internal_repo_rocksdb/repo:db_write_test fbcode//internal_repo_rocksdb/repo:error_handler_fs_test` at this commit: Pass 238, Fail 0 (https://www.internalfb.com/intern/testinfra/testrun/1125900446553732). - Neuter, TSan and byte-identity evidence for the folded-in items: see the Test Plans of D124911745 and D125113461. They ran on the same code, now split across this stack. M1: absorbs 25 entries: GC01 N>1 gate + marker size check + log_test (6), GC02 `SupersessionsAreDurableWhenOpenReturns` + include (2), GC04 void seeding/clause/tests (8, with GC05's enable), GC05 void read/clamp/ tests (5), GC13 `LeadershipSyncRecordsWalsBelowClaimHorizon`, GC16 Q7 skew-test change (3). X5-X7 moved here (need `recovered_wal_partitions_`); GC04#57-clamp remainder stale (already at D120649665, dropped). `TEST_WalSyncMarks` decl moved after `TEST_CurrentWalNumber` (T0 spot; empties GC03#136). `kWalPartitionsRe- jection` updated to T0 text (X10). Gate: lib builds; `db_write_test` 189/0; `db_wal_test` 2069/0; `log_test`+`db_options_test` 538/0. M1 re-verification (2026-10-20, after rebasing the stack onto master f0c3a35689fc and clang-formatting): per-diff gate at this diff passed (CI format check, `rocksdb_lib` build, touched test targets); tip suites 8126/0; N=1 byte identity equals T0. M2 fold: new or moved tests here: Torn/Gap/Frontier/SkipMode cut tests, FrontierCutKeepsIgnoredRecordBelowSeedLive, DataLessTornPartitionWalIsABoundedTail, DeletedOldestPartitionWalIsDetected, DamagedPartitionWalHeadIsBoundedPerMode, ReopenWithChangedPartitionsWritesSpans, RotationSealsEveryRetiringPartitionWal, SkipModeFailsOnPristineHoleAndSaysWhy, MissingTrackedWalFailsTheOpen, OpenerUsageDoesNotDecideTheMerge, RecoveryTrimsEachPartitionsNewestWal, ChangeStreamStopsBelowHeldLowerWrite, DeletedOldestWALIsDetectedAtOneWAL, SpanlessWALsRecoverAloneAndWithNewOnes, PreparedUnindexedWalSurvivesPartitioning, FailedSyncTrackingReleasesItsRange. B.1 at this diff (format check, `rocksdb_lib`, touched test targets): PASS; db_options_test + db_wal_test + db_write_test + log_test + transaction_test 5959 pass. M3 B.1 at this diff (clang-format 21.1.2 on its changed lines, make check-sources, debug build, touched test binaries): PASS; db_options_test + db_wal_test + db_write_test + log_test + transaction_test: 6018 pass. M4 fold: Absorbs - Fixture tests of GC18, GC20, GC21 and GC24 and their GC25 rewrites (exception X7): FailedGateSyncWriteStaysInvisible, SyncZeroCountWriteAfterSyncWriteSyncs, FailedGateSyncStaysInvisibleAtNPartitions, FailedGateSyncFenceGoesInWithItsError, ResumeFailsWhenBurnedIndexCannotBeExplained, FailedGateSyncRangeDeletionStaysHidden, FailedZeroCountGateSyncRecordsNoIndeterminate, the GC24 ports; WriteAdmittedByRecoveryAllocatesAboveFences' fence assertions; the H1 repro SyncPrepareAfterSyncCommitSurvivesCrash (keeps its test hook below the flip). - GC25: SyncWriteVisibleOnlyOnceDurable, FailedSyncReopenWithoutResumeMayRecoverIt, FailedSyncCommitAndPrepareNeverVisible (exception X20). - GC21 Q1: ResumeImpl calls ExplainBurnedWALIndices; GC26 Q5(b): ResumeImpl takes the full recovery path while a burned index is pending at N>1 (exception X21, AMB-M4-17); GC24RetryFlushRecoveryWithBurnedIndexProgresses. - GC19 Q3/Q5 (exception X10, AMB-M4-12): merge_from filter, supersession routing and legacy prefix, with their DBWALIndexTest tests and GC23 Q5's InterleavedMixedSetWithSupersessionsFailsClosed (exception X27: moved up from D120415420); GC24 Q1 WriteWALIndexHeadFloors (exception X13: hand-ported with CurrentWalOrNull(p) written inline, AMB-M4-3) and Q6's void refusal. - GC26 Q2: RecoveredWALIndexPredecessors and WriteFurtherWALIndexPredecessors; Q3: the true-alternation gate, the unindexed suffix replayed after the merge, the prepare pin; FailingWalFS::Landing, AssertSkipOpensCopy and the D-10 skip cells of this diff's tests; GC26ColumnFamilyRefusalsHoldAfterOpen. - Net-zero pairs dropped (rule 2.7): none. M4 B.1: PASS (clang-format 21.1.2 on the changed lines, make check-sources, debug build of db_options_test, db_wal_test, db_write_test, log_test, transaction_test, write_prepared_transaction_test); 6913 tests, 0 failed. M5 fold: Absorbs 110 A.1 entries (GC28 1, GC27 17, GC30 10, GC29a 11, GC31 4, GC32 30, GC29b 37): GC27 Q1 (floors, record_cut at the seed, the end-check refusal), Q5 (a) (merge selection), FailingWalFS edits, GC31's per-partition size account in RestoreAliveLogFiles (X17-M5), tests on DBWalAppendFailureTest and ReopenWithPartitions; the GC32 test block (all but three) and its changed tests; GC32's ExplainBurnedWALIndices call; GC29b Q8 tests and T3; tests of GC30/GC31 that need this fixture. Not here after B.1: SyncFailureWithoutBackgroundErrorAfterInsertNeverPublishes and DBStatsExactUnderConcurrentLeaders go to D123971668 (X40-M5, X41-M5); FenceHidesFailedWriteFromWalIterator's T7 leg, FileScopedFailureResumesLive, FileScopedResumeKeepsManifestWalSetConsistent, FailedSyncLedGroupReleasesEveryRegisteredRange and FileScopedResumeHoldsAllocationUntilFencesClose go to D127093323 (X39-M5). M5-F1 (A.8): F1.1: FileScopedResumeStragglerAboveReservation (each recovery mode reopened); F1.2 (Close lost wakeup, X24-M5): ClearBGError signals bg_cv_, CloseHelper's WaitForRecovery sync point, DBErrorHandlingFSTest.CloseWaitingOnDirectErrorClearReturns; F1.3: join-first edits of SyncLedGroupAsyncMembersReturnBeforeFsync and ImportWaitsForPendingSyncGroup. Exceptions: X34-M5: GC30LiveSstHasKey, SyncFailureWithoutBackgroundErrorAfterInsertNeverPublishes, SwitchWaitsForGroupInsertedBeforeAppend (GC30#245, with GC29b#609 and meta#611) and FailedSyncDropKeepsBelowFenceRangeTombstone (GC31#407, with GC29b#634) moved here from D123701876: rocksdb/sst_file_reader.h is included from this commit (B.1: 'SstFileReader' was not declared); X38-M5: SyncCommitCallbacksWaitUntilGroupCannotFail (GC30#268, with GC29b#684) moved from D123701876 to D123928339: its reopen after the failed sync, Resume() and rollback needs this commit's recovery of the retired WAL (B.1 at D123701876: "SST file contains data beyond the point of corruption"); X39-M5: GC32#447 (WALIOStatusCheck skips the indeterminate-sequence record above one partition) moved from D123701876 to D127093323, with the tests that need it: FenceHidesFailedWriteFromWalIterator's T7 leg (GC29a#291, GC32#452), GC32#455's FileScopedFailureResumesLive, FileScopedResumeKeepsManifestWalSetConsistent and FailedSyncLedGroupReleasesEveryRegisteredRange (with GC29b#550, meta#652, meta#653) from D123928339, FileScopedResumeRacesSyncWalAndSyncWrite (with GC29b#648-meta#651 and F1.3's edits) from D123971668, and F1.1's FileScopedResumeHoldsAllocationUntilFencesClose from D123928339. GC32#447 rests on GetUpdatesSince being refused above one partition, which this commit brings; below it M4's FenceHidesFailedWriteFromWalIterator reads the record's fence through the iterator (B.1 at D123928339: the iteration ended OK, not NotFound), and without GC32#447 the release's gap record meets the per-failure record in every N>1 file-scoped resume those tests drive (B.1: "Assertion it->second.wal_number == wal_number failed"); X40-M5: SyncFailureWithoutBackgroundErrorAfterInsertNeverPublishes (GC30#245, with GC29b#609) moved from D123928339 (X34-M5) to D123971668, the lowest commit where it passes (B.1 at D123928339: the sync write did not fail Aborted and the key read back); X41-M5: DBStatsExactUnderConcurrentLeaders (GC31#407, with GC29b#623) moved from D123928339 to D123971668, the lowest commit where it passes (B.1 at D123928339: WAL_FILE_SYNCED counted more syncs than db.wal_syncs). X14-M5 hook (rule 2.4): the AllowWalPartitions callback before the first N>1 open of WritePreparedPartitionedWalTest.SyncCommitCallbacksWaitUntilGroupCannotFail (X38-M5; after its ClearAllCallBacks: before Reopen and before the next iteration's Open); FLIP removes it. M5 B.1: PASS (clang-format 21.1.2 on the changed lines, make check-sources, debug build of db_options_test, db_wal_test, db_write_test, error_handler_fs_test, log_test, transaction_test, write_prepared_transaction_test); 7070 tests, 0 failed. M6 fold: Absorbs the GC34 Q1 `record_cut` comment; the rewritten `ExpectCloseWakesParkedWrite` (GC34 Q3) and the `WalOnlyWrite` helper; the `DBWalAppendFailureTest` stack-owner follow-up (`Writer` joins in its destructor after abandoning test holds, `Writer::WaitDone`, `HoldNextAppend` and the test-local holds wait through `WaitForReleaseOrAbandon`, the fixture clears the flag); GC34 Q5 (b) release-and-bail paths and EXPECT sweeps in tests owned here. M6 B.1: PASS (debug build and build_tools/gtest-parallel run of db_options_test db_wal_test db_write_test error_handler_fs_test log_test transaction_test write_prepared_transaction_test: 7070/7070). Differential Revision: https://phabricator.intern.facebook.com/D123928339
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
[GC] GC09: Every parked writer reaches a terminal status that matches one-WAL semantics
Summary:
[GC] GC09 (Lane B8; D-1; D-N71 option (b))
Reviewer question: at
wal_partitions > 1, does a write parked in its completion gate now leave the gate only in three ways? Those are: covered → OK; a failed range at or below its target → that failure's background error, and this still holds after recovery releases the range; shutdown →ShutdownInProgress. And does a write that failed at its gate never become visible, live or after reopen? Check four places:WaitForWalDurability(its exits),InstallWalGateFence/ClearWalDurabilityBGError(fence lifetime),FlushJob::DropEntriesAtOrAbovewithUnreleasedWalGateFenceLow(recovery's flush), andErrorHandler::HandleKnownErrors(no suppression of an N>1 WAL failure).Checklist items closed: G-13, N-2-4, N-2-5, N-7-1 (review F013), plus the GC08 carry-over Q5 (no success above a released failed range) and Q6 (file-scoped live resume at N>1: the rejection stays, analysis below). Still open, not addressed here: G-18, G-19, N-3-1, N-3-2, G-11.
Why
The completion gate parks a write after its own append and memtable insert until every lower sequence on every partition is WAL-durable. At the base (GC08 winner, 59771e158a15), a parked writer could still end four ways that one WAL never produces:
HandleKnownErrors(plain IOError, NoSpace, Busy/Incomplete, IOFenced). No error was stored, the failed range stayed pinned, and every later gated write on every partition parked forever.Close()never woke parked gates. Teardown then freedwal_durability_cv_andsequence_wal_index_mutex_under the parked threads.ClearBGError, which published past B, and Resume's atomic flush wrote B into an SST. The DB held a write that had reported failure, sitting above a hole. A write held between its write-queue exit and its gate across a whole auto-resume found its target covered and returned OK (GC08 carry-over Q5).New behaviour
Gate exits (D-N71 (b))
LastSequence() >= target(and the durability safe point, for a group with a WAL record), and no fence holdstargettarget: a WAL range (append or leadership sync) or a memtable insert at or belowtargetfailed. The fence is open-ended while the error stands; once recovery releases the range, it closes at the last allocated sequence.shutting_down_is set while still uncoveredShutdownInProgress("parked write")PreprocessWriteexactly as at N=1.CompletionGateNeverInstallsAtOnePartition). Every other new branch is gated onNumWalPartitions() > 1.Q1: an N>1 WAL failure cannot be suppressed (G-13).
HandleKnownErrors, after listeners run, a WAL write error from the write path (kWriteCallback,wal_related) at N>1 is restored to its computed status if a listener cleared it or lowered its severity. Listeners are still notified.WALIOStatusCheckis the only caller with that pair, and at N>1 it already escalates every failure (D-1).!allow_auto_recovery) are reachable only throughSetBGErrorNoAutoRecovery, which no WAL path uses. Retryable, file-scoped, data-loss andmanual_wal_flushWAL errors are stored before listeners run.>guard.Q2: Close wakes every parked write and teardown waits for them (N-2-4).
CancelAllBackgroundWorksignals the gate's cv under its mutex right after settingshutting_down_. A parked write returns OK if covered, elseShutdownInProgress, the same status as a stalled write.CloseHelperthen waits on the same cv untilwal_durability_waiters_(now counted under the gate mutex) is 0, and only then goes on to teardown. The last waiter out signals.Close(), which stays unsupported.ShutdownInProgresswrite survives reopen is left to recovery's prefix rule. InCloseWakesParkedWrite, the lower held write completes before teardown, so the prefix is complete; no promise is made either way.Q3: a gate-failed write is never exposed (N-2-5).
mutex_right beforePickMemTable(UnreleasedWalGateFenceLow).FlushJobhides point entries at or above it through a forward-onlySequenceFloorIterator(its count keeps the memtable entry-count check honest) and reads range tombstones atfloor - 1.PreprocessWritethrough its insert.PreprocessWrite.ClearBGErrornow callsClearWalDurabilityBGErrorbefore it clearsis_db_stopped_. So any write the cleared flag admits allocates above the closed fences.AssertLastSequenceCoversAllocated). A, failing later, was therefore allocated after that switch, and so was B above it. Non-recovery flushes that finish while background work is stopped are rolled back anyway.GetUpdatesSince: when recovery closes a fence,RecordIndeterminateWriteSequencerecords [low, high] (WAL number 1, since the records may lie in any partition's WAL), so every iterator stops before it, as for N=1 file-scoped recovery.LastAllocatedSequencenever moves back, so no fenced sequence is reissued. After a crash, the abandoned records sit only in WALs that Resume's atomic flush moved every column family past, so recovery never reads them.DISABLED_CrashAfterLandedFailedAppendRecoversNoFailedWritestays disabled, and the crash legs here use a record that never landed.Q4: only a failure that can never be covered fails a parked write (N-7-1, F013). This is the fence exit above. A failed memtable insert also pins its range for good (fatal error), so
HandleMemTableInsertFailurenow takes the group's first sequence and installs a fence that recovery never closes (released_by_recovery=false). Without that fence, (b) would leave a write parked above a failed insert forever.Q5: no success above a released range (GC08 carry-over). Fences outlive recovery:
ClearWalDurabilityBGErrorcloses each open one atLastAllocatedSequence()before releasing the trackers. Every path that finds a write covered (fast path, spin, park loop) then checks the fences. Two atomics (wal_gate_fence_low_,wal_gate_fence_high_) keep that check to two loads for any target outside every fence; that includes every write allocated after recovery.Q6: file-scoped live resume at N>1. Option (a): the rejection stays.
Upstream added the
track_and_verify_wals_in_manifest/track_and_verify_walsrejection in 05779d2bff70 (PR 15193, "Recover from poisoned WAL handles"). It is part of a fail-closed supported envelope, next to WAL recycling, retention, 2PC and others, and no failure mechanism is named.That diff's own stress mode turns WAL tracking off, so the combination is unvalidated upstream.
The mechanisms it touches all exist per partition at N>1:
SyncWALskipping quarantined writers while still recording healthy WALs' synced sizes;N>1 adds a cutoff that also covers healthy WALs of other partitions.
No reason was established that would make the exclusion safe to drop at N>1. GC08's loser lifted it without one. So
FileScopedFailureStaysStoppedAsAtOnePartitionpasses unchanged. TheResumeImplchange andWalFileScopeErrorResumeRestoresWritesfrom D127099968 are not ported.Evidence (each neuter was run on this code; the failure is as shown)
ListenerCannotSuppressPartitionedAppendFailure:WALIOStatusCheckthat the error is stored aborts. With the assertion also removed,bg_nis OK.CloseWakesParkedWriteandCloseWakesParkedWriteUnderBackgroundError:Close()runs on another thread. W returnsShutdownInProgresswhile A is still held.Close()passes the waiter drain and is held there until A, released, has returned OK. Close then finishes, and a reopen has A.GateFailedWriteNeverSurvivesRecovery:Resume(), auto-resume, and reopen with the error still set (PIT). In each, A on partition 0 fails (retryable) after B on partition 1 has inserted above it.Get(B)is NotFound, no live SST holds B (scanned withSstFileReader), and writes resume on both partitions.UnreleasedWalGateFenceLowreturns max):Get(B)is "value" and an SST holds it.CrashAtPartitionFailureRecoversAcknowledgedSet, unchanged.UnrelatedErrorLeavesParkedWriteToComplete:CompactionErrorWakesParkedGateshows the same with a real fatal compaction error.WriteHeldPastRecoveryStillFails:DBImpl::RunCompletionGate:BeforeWait(new test-only sync point) after its insert. A fails (retryable) and auto-resume completes.Get(B)is NotFound. B, released, returns the IOError. After a reopen B is still absent, and later writes succeed.MemtableInsertFailureFailsParkedWrite(GC08) passes unchanged. Neuter, no insert fence: "a write never returned".ClearBGErrorordering (fences closed beforeis_db_stopped_clears): argued, not tested. The race it closes needs a leader to passPreprocessWriteand allocate inside oneClearBGErrorhold.Changes to existing tests (Invariants 4 and 7)
Every change replaces "fail on a background error no failed append backs" with the (b) outcome, or drives the wake with a real append failure. All of these tests are D123701876's (
sl annotate: f0e61e43f769).DurabilityWaitErrorBeforeAdvanceFailsWaiter: three partitions. W parks behind held A and held F; F's append (below W) fails while A is held. W fails promptly with that error, and A completes OK afterwards.CheckThenParkRaceWakesWaiter: three partitions. W is held atBeforeParkafter its check; F's append below W then fails, and its wake and fence block on the mutex W holds. W, released, must fail (a lost signal hangs the test).CompactionErrorWakesParkedGate(round 12.1): the real compaction error still wakes W through the hook (one wake). W parks again exactly once, returns OK after A, and a new write fails with the error.SuppressedErrorLeavesGateUndisturbed: the first two legs are unchanged. In the last leg the unsuppressed synthetic error still lands and wakes, but W returns OK after A. Q1's "passes unmodified" conflicts with (b) for this leg; see Assumptions.LeadershipSyncFailureWakesParkedGate: C's failed leadership sync fences C's range, which lies above W, so W returns OK after A. That matches one WAL acknowledging an async write whose append landed before a later sync failed.GatePostWaitSyncFailureWakesParkedGate: B's post-wait sync failure (no range) wakes W, which parks again once while M is held. M's append below W then fails W.DurabilityWaitAdvanceRacesError: unchanged and passing. Its OK branch is the (b) outcome.FileScopedFailureStaysStoppedAsAtOnePartition.Fold-back split (for M3; hunk → absorbing diff)
db_impl.cc: theCancelAllBackgroundWorksignal, theCloseHelperdrain and itsWalDurabilityWaitersLeftsync point (new code).WaitForWalDurability: the shutdown leg, the waiter count moved under the gate mutex, and the last-out signal.RunCompletionGate:BeforeWaitsync point.db_impl.h: the cv and waiter-count comments.WaitForWalDurability: the fence checks on all three covered paths, and the bg-error exit replaced by the fence exit. Exception to the map: they are D123551605 lines, but the fence is fed by D123701876's failed-range recording.InstallWalGateFence,WalGateFenceStatus(Locked),UnreleasedWalGateFenceLow, members and declarations.WALIOStatusCheck; fence close and iterator gap inClearWalDurabilityBGError.HandleMemTableInsertFailure: the fence, its signature, and its five call sites (upstream lines, D1 purpose).error_handler.{h,cc}: theHandleKnownErrorsoverride plus itswal_relatedparameter, and theClearBGErrorreorder (GC08's line).flush_job.{h,cc}:SequenceFloorIterator,DropEntriesAtOrAboveand the count adjustment (new code);db_impl_compaction_flush.cc: the twoDropEntriesAtOrAbovecalls.DBWalAppendFailureTestfixture, plusSuppressAllBgErrorsListener,LiveSstHasKeyand thesst_file_reader.hinclude. Exception: the Q2 tests belong to D123551605's purpose, but the fixture exists only from D123701876.Assumptions (
AB-Implementation-Requirement.md§4)SuppressedErrorLeavesGateUndisturbed,LeadershipSyncFailureWakesParkedGateandGatePostWaitSyncFailureWakesParkedGatealso had to change. Each fails a parked write on an error that no failed range at or below it backs. Invariant 4 says "at least", and (b) decides (rule 2). Q1's "passes unmodified" for the first one conflicts with (b); (b) wins as the explicit decision.!allow_auto_recoveryevidence leg: no WAL append path can reach it. The retryable / auto-resume-off case is tested as already unsuppressible at both N (rule 2/5).WALIOStatusCheckerrors, which GC08 already escalates), not only pinned appends. This is the single classification point and the least code (rule 5).Close()after the drain until the held lower write finishes, because a write still running during teardown is concurrent withClose()(rule 2: "writes concurrent with Close() remain unsupported").FaultInjectionTestFSpower loss. The pre-Resume crash leg is GC08's unchanged test (rule 5).JustinGaoNotesChanges(7a4629ff63a5) was found; the on-disk doc is identical.Not done
DISABLED_CrashAfterLandedFailedAppendRecoversNoFailedWrite).GetUpdatesSinceafter a reopen (the gap tracker is per process, as upstream's; GC12).Test Plan:
At this commit (dev mode, ASan/UBSan unless noted):
buck2 test fbcode//internal_repo_rocksdb/repo:{db_write_test,db_wal_test,error_handler_fs_test,db_basic_test,db_log_iter_test,transaction_test,db_flush_test,flush_job_test}: Pass 6009, Fail 0. That run predates the last amend, which only changedExpectCloseWakesParkedWrite's synchronization (TSan).db_write_testwas rerun in full on the final tree: Pass 277, Fail 0.@fbcode//mode/dev-tsan): every new and changed test, plus all ofDBWalAppendFailureTestandDurabilityWaitAdvanceRacesError. Pass 34, Fail 0, no reports. An earlier run caught a test-only race (the parked writer'shandles_read vs. the closing thread, ordered only by a relaxed counter); it is fixed by confirming the park under a mutex.--gtest_repeat=100, ASan): the 7 new tests, the 6 converted tests,DurabilityWaitAdvanceRacesErrorandMemtableInsertFailureFailsParkedWrite: 100/100 iterations, 2100 test runs (21 instances per iteration; the/1two-write-queue variants ofDBWritePartitionTestbypass themselves), 0 failures.db_bench fillseq --num=10000 --seed=20260928 --threads=1 --disable_auto_compactions=1, dev mode, one live WAL):6d1351117a289a2784449a68d5421b1aa385ab0b383273c2c5918befa9181b09.partition_by_column_family:9a69a3fc66777fadce05e8a999479a5f57364aca27cd6d22aa00e4631adfc796.tools/db_crashtest.py blackbox --duration=180 --interval=30 --wal_partitions=1 --partition_wal_usage=partition_by_column_familywith--stress_cmdset to db_stress from this commit (dev mode): 7 db_stress runs, exit 0.arc fruns nothing here). Pre-existing violation left alone:db_impl.ccinclude order.arc lint -a: no lint issues.make check-sourceswas not run; the only non-ASCII in touched files is pre-existing (db_write_test.cccomments).@mode/optbuilds, and a performance benchmark. The hot-path cost is two acquire loads after the covered check.Differential Revision: https://phabricator.intern.facebook.com/D127204780
fbsource-commit: 9f54ad1b30b1