Skip to content

[M4] Fold GC18–GC26 into the original diffs - #26

Draft
JustinGaoF wants to merge 30 commits into
pwal/m3from
pwal/m4
Draft

JustinGaoF wants to merge 30 commits into
pwal/m3from
pwal/m4

Conversation

@JustinGaoF

Copy link
Copy Markdown
Owner

Pure absorb of GC18–GC26 (the 13 commits above pwal/m3) into the original PartitionWAL diffs. GC18's flip (Q1–Q5) stays a standalone top commit, "[rocksdb] Lift the N>1 gate: indexed WAL partitions open in production builds". The tree of pwal/m4 (7a31be32520b3178044bfbd5071f583a002ec5f4) is identical to pwal/gc26-join (5775622a01a7, tree f865020b5608): no behaviour change. Rows 1–9 keep their pwal/m3 hashes; the eight GC commits and four repro commits are empty after the fold and dropped. Each absorbing commit's message has an "M4 fold: Absorbs …" paragraph (exceptions, net-zero pairs dropped) and its "M4 B.1:" row; every Differential Revision: line is kept exactly once (37).

Commits (39)

# sha D-number absorbs
1 1f326073b3a0 D118367634 unchanged (same hash as pwal/m3)
2 ec8dc2eb023a D118369740 unchanged (same hash as pwal/m3)
3 ff63298d59af D118369607 unchanged (same hash as pwal/m3)
4 cd8eab277472 D118369608 unchanged (same hash as pwal/m3)
5 aba992908749 D119600943 unchanged (same hash as pwal/m3)
6 ae08e5aad3cd D118371518 unchanged (same hash as pwal/m3)
7 ef8fa416ffba D119751506 unchanged (same hash as pwal/m3)
8 f64c228862ec D120171238 unchanged (same hash as pwal/m3)
9 cb9fda246e5c D120408456 unchanged (same hash as pwal/m3)
10 77e1d99b03e6 D120415420 GC23 Q1/Q4 writer-side supersession asserts (its Q5 test moves to D123928339, X27)
11 22566989e93b D120621828 GC26 Q2 reader side: strictly ascending further predecessor spans, WALIndexFurtherPredecessorSpansAscend; X24
12 6107bde3a31a D120624825 GC26 Q2 merge side: AttestedSpans, ComputeLowerBound over every attested span (its test moves to D120649665, X25)
13 81976b5fd60e D120649665 GC19 Q1/Q2 and Q4 floor term; GC23 Q4 and ports; GC24 Q1 merge-side head floors and Q6; GC26 Q4 D-10 skip mode and docs; FurtherSpanExplainsRetiredFoldedHead; X11, X23, X25
14 19e7dec277da D121636079 GC23 Q1 misplaced-supersession detection and guards; GC24 sequential-replay port
15 eb1a8249694d D126533192 restacked, no content change
16 1e150d73fc75 D121674557 restacked, no content change
17 57106889df55 D117251769 GC20 Q9 default assertion; GC26 Q4 recovery-modes paragraph of the wal_partitions doc; X23
18 ca28be60eaeb D117251770 restacked, no content change
19 a1b01d8fadc4 D117251771 restacked, no content change
20 8c3d5ac99a86 D117274583 restacked, no content change
21 449724702081 D117280372 restacked, no content change
22 daded1d71504 D121858039 restacked, no content change
23 b0e6d2376203 D122274088 restacked, no content change
24 b8b5b9d84013 D122412677 GC20 Q4 cover serialization under the partition WAL mutex and call sites; X5 (hand-port: wal_context.wal_partition until D122869562)
25 c1cedd35a434 D122660502 restacked, no content change
26 d74c64de4e53 D122869562 restacked; takes over X5's call-site argument as the local wal_partition (X5)
27 bc9c69c559ed D123079329 restacked, no content change
28 d7f4acb4821f D123476301 GC20 Q3 empty zero-count ranges, clamp hand-port, tests; GC25 leading_sequence_count; X4, X7, X17
29 704046223c0a D123551605 GC18 low plumbing, Q10 sync point, Q11 renames; GC20 Q1 epochs; GC22 Q1; GC23 Q7; GC25 D-9 core; X1, X2, X17, X18; 6 net-zero pairs
30 a2cfc5cc8a5f D123701876 GC18 Q8 fences, GC20 Q8, GC21 Q1 (X8), GC26 Q1 read-back and zeroing, GC25 FailUnpublishedSyncRange, fence-close rework, D-9 doc; X2, X8, X17, X20; 77 net-zero pairs
31 b0799220ca45 D123928339 GC18/GC20/GC21/GC24 fixture tests and GC25 rewrites; GC25 visibility tests; GC21/GC26 ResumeImpl; GC19 Q3/Q5 and GC23 Q5 test; GC24 Q1 writer hand-port and Q6; GC26 Q2/Q3; X7, X10, X13, X20, X21, X27
32 e419bb7a5b6b D123971668 GC18 Q9 sync point and Q10 tests; GC20 Q2 and its repro; X8/X13 accessor forms; CoalescedFailedGateSyncFencedWithItsError; X3, X7, X9; 1 net-zero pair
33 0f0a230dbf14 D126533193 GC18 Q10 GateSyncToleratesCoupledRotation, Q11 trigger rename; GC24 oracle self-test edits; X1
34 79c40082223f D126533194 GC26 Q5(e) sanitizer: no secondary and no continuous verification at N>1
35 c7aef61cdf0b D126533195 restacked, no content change
36 427d34a871ab D127093323 GC22 Q2 secondary refusal; GC23 Q6 tests; H7 repro and RepeatedTwoPCHolesStayExplainedAfterCrash; GC26 DBWalLandedAppendTest; FailedGateSyncAbsentUnderTransactionDB; X9, X22, X26
37 cb4d5dd13aaa D127275775 GC18 Q6/Q7 and AsyncOnSyncingPartitionWaitsForItsFsync; FailedGateSyncFailsWritesAbove; GC22 M-b repro; GC23 Q9; X1, X7, X14, X15; 1 net-zero pair
38 7e1123447dee NEW-GC14a every DBWalPartitionCoverageTest test and helper of GC19/GC23/GC24/GC26 (incl. DBWalPrepareAcrossChangeTest); X12, X14
39 7a31be32520b FLIP GC18 Q1–Q5 + X6/X19 entries + hook removals

Verification (§8)

Step T0 5775622a01a7 M4 tip 7a31be32520b
1. Shape — 39 commits; rows 1–9 = pwal/m3; GC/repro commits gone; top = FLIP, no D-line; 37 Differential Revision: lines, none duplicated; git grep AllowWalPartitions empty
2. Tree identity tree f865020b5608 git diff --stat 5775622a01a7 <tip> empty (tree f865020b5608)
3. Per-commit gate (B.1) — 39/39 PASS (clang-format 21.1.2 on changed lines, make check-sources, debug build of touched binaries/tools, gtest-parallel of touched tests); no pre-existing failures
4. Tip suites (B.2, 32 binaries) build 0; 9817/9817 pass build 0; 9817/9817 pass
5. Release builds (db_bench, db_stress, ldb) exit 0 exit 0 (db_stress built, never run)
6. N=1 byte identity none 6d1351117a28…, indexed 9a69a3fc6677… none 6d1351117a28…, indexed 9a69a3fc6677…; check_wal_byte_identity.sh MATCH none / indexed / partitions
7. Oracle RecoveredStateIsPrefixOfHistory 1000 cycles strict PASS; CHECK_PUBLISHED=1 1000 cycles PASS 1000 cycles strict PASS; CHECK_PUBLISHED=1 1000 cycles PASS; TSan 40 cycles PASS, 0 warnings
8. ×1000 MixedSyncWrites… 2000/2000 (2 params ×1000); CheckpointRacingLockWAL N=8 1000/1000 MixedSyncWrites… 2000/2000; CheckpointRacingLockWAL N=8 1000/1000 (rerun at -w 16: my first run at -w 83 filled the disk with test DBs and I killed it; no test had failed)
9. TSan + ×100 (B.4, 61 tests, 8 binaries) — 0 TSan warnings in all 8 binaries; ×100 exit 0 for backup_engine_test, transaction_test, latency_injection_fs_test, db_wal_oracle_test, db_wal_test, write_prepared_transaction_test, db_write_test (50 tests), db_wal_partitions_open_test
10. check-format / check-sources / check-c-api-gen 0 / 0 / 0 (4 pre-existing header flags: wal_durability_tracker.h, log_merge.cc/.h, log_merge_test.cc) 0 / 0 / 0 (same 4 files); clang-format 21.1.2
11. GC16 trigger cell t16 (report only) ratio 0.9702 FIRES (load avg 87.42) ratio 0.8576 FIRES (load avg 68.47)
12. Blame spot-check — 27/27 sampled moved lines attribute to the commit §5 names

B.1–B.4, B.8 and the blame check ran on 86e467b86c20, before the B.9 rewrite, which changed only the messages (same tree f865020b5608); §8 steps 1–2 were re-checked on the final tip.

Not run (per the plan): db_stress runs, crash tests, db_crashtest.py (deferred to the DS session).

Folds and closes #8 #10 #12 #14 #16 #18 #20 #22 #25

JustinGaoF and others added 30 commits October 30, 2026 12:00
Summary:
Indexed WAL recovery currently seeds `next_wal_index_` from the highest index still present on disk. When recovery deliberately stops early, that preserves an obsolete suffix and requires reading beyond the recovery cut.

Seed `next_wal_index_` from records actually accepted by recovery. Emit bearer-scoped, open-ended supersession records for every WAL suffix skipped by tolerated-tail, point-in-time, and WAL-filter recovery, and fail open when indexed recovery cannot identify or persist the cut. Point-in-time recovery can still resume in a later WAL without superseding that later file.

Read-only and secondary opens are exempt, not failed. They create no WAL and allocate no `wal_index`, so they reissue nothing and the supersessions have nothing to protect; recovery drops them instead of failing the open. Failing would have rejected `DB::OpenForReadOnly` on any indexed DB with a tolerated tail, which is the normal state after a crash. `ReadOnlyOpenToleratesStopWithoutSupersession` pins the open succeeding and serving the records below the cut.

Decision, no forced flush: the earlier void-range design forced the post-recovery flush past `avoid_flush_during_recovery` so the truncated files left the recovery set. Under bearer-scoped supersession the record is the declaration, so it does not depend on those files being gone, and the option stays honored. The cost is that a superseded WAL remains in the recovery set until an ordinary flush retires it, and each open until then re-reads it and redeclares the same cut. `SecondOpenAfterSupersessionRedeclaresTheSameCut` pins that repeat: the second open seeds above the index the first open reissued, redeclares the same one-file lower bound, never supersedes the WAL the first open wrote, and the data survives a third open.

Reuse resolves at the DB layer, not only in `log_test`: `RecoveryMarkersResolveReusedIndices` builds a real collision -- point-in-time recovery skips an intact WAL, then hands out one of its indices again in the new WAL -- and asserts a reader of the new WAL calls the skipped file's copy obsolete, the reissued copy live, and the first WAL's records below its cut live. Enforcement during replay is still deferred to gap detection; nothing here depends on it, because a suffix left above a cut is either unreadable or skipped by the same stop that produced the cut.

`hasReadError()` reflects only a failed `file_->Read`: all three assignments in `log_reader.cc` sit under `!status.ok()` from that call, and corruption, drops, and old records go through the reporter without touching it. That distinction is load-bearing under `kSkipAnyCorruptedRecords`, where the reporter status is null and a read failure would otherwise be swallowed, leaving the rest of the WAL unseen and the cut wrong. `ReadIOErrorFailsRecoveryUnderSkipMode` injects a read error at `LogReader::ReadMore:AfterReadFile` during recovery and pins the open failing with `IOError`; without the check the open succeeds.

Scope of the guarantee: the live recovery set. `WAL_ttl_seconds` and `WAL_size_limit_MB` move retired WALs to `archive/` instead of deleting them, and those files keep the indices they were written with while sitting below `min_log_number_to_keep` and outside `wal_numbers`; bringing them into the scan would mean reading the whole archive on every open. A future consumer that merges `wal_index` streams must therefore read the live set only, because archived WALs can repeat indices the live set reissues. This caveat was written for D120055892 and lost when that diff was abandoned; it is restored here, in the summary and as a comment at `SetNextWALIndexAfterRecovery`, because this is the diff that seeds from the recovery cut.

A read-only or secondary open is now also asserted, not just branched on: `assert(!read_only || recovery_ctx == nullptr)` states the invariant the supersession hand-off relies on, so a future caller that passes a recovery context on a read-only open trips in debug rather than silently dropping the supersessions.

Housekeeping: D120055892 is abandoned. This stack bypasses it rather than revising it, so it was orphaned on the same parent touching the same files. Muse's D120409192 was already abandoned.

M1: Absorbs GC02 Q4: fsync in `WriteWALIndexSupersessions` (its test lives in D123928339).

Test Plan:
- `buck2 build @fbcode//mode/dev-nosan fbcode//internal_repo_rocksdb/repo:db_wal_test fbcode//internal_repo_rocksdb/repo:log_test fbcode//internal_repo_rocksdb/repo:options_test fbcode//internal_repo_rocksdb/repo:db_stress`
- `db_wal_test`: 2,008 passed, including 26 `DBWALIndexTest` cases
- `log_test`: 379 passed; `options_test`: 80 passed
- `python3 tools/db_crashtest.py blackbox --partition_wal_usage=wal_index_single_file --two_write_queues=0 --duration=180 --interval=30 --max_key=10000 --ops_per_thread=20000`: exit 0; crash-recovery verification passed
- Neuter checks, each restored afterwards: making `IsWALIndexSuperseded` ignore the WAL it names turns `RecoveryMarkersResolveReusedIndices` red (the reissued copy reads as obsolete); removing the `hasReadError()` check turns `ReadIOErrorFailsRecoveryUnderSkipMode` red (the open returns OK)
- `arc lint -a` on the changed files: clean. Formatting verified with `clang-format <f> | diff - <f>`: empty

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

Reviewers: anand76, rbanerjee2, dyao, kinbertchou, huixiao, #rocksdb, taopeng, rajivharlalka, xbw

Subscribers: jewoongh, rbanerjee2, anand76

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_wal_test: 2014 pass.

M4 fold: Absorbs
- GC23 Q1/Q4: writer-side asserts in WriteWALIndexSupersessions (GC23#270, GC23#276 part). The Q5 test InterleavedMixedSetWithSupersessionsFailsClosed lands in D123928339 instead (exception X27: it needs GC19 Q5's interleaved fail-closed check, first there).
- 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_wal_test); 2014 tests, 0 failed.

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

Tags: sentinelized
fbsource-commit: da6a7fd50485
Summary:
Reviewer question: does every new record fail closed, and is void lo-ordering (rejecting trailing covers) the right constraint for a streaming merge?

This is the first of a three-diff stack building the read side of partitioned WALs on top of D120415420: D1 completes the on-disk vocabulary, D2 adds the N-file merge, D3 switches recovery to it. D1 is reviewable against log_test alone and changes no DB recovery behavior.

What it adds: (1) burn-cover coverage: the reader retains decoded void ranges (not just a maximum) and answers IsWALIndexVoidCovered, which the merge asks at every hole; both readers inherit the change from the shared decode path. (2) idle progress assertions (types 26/27): a file with nothing below some index still coming asserts a bound so a merge waiting on it can advance; bounds are nondecreasing and a progress record closes the head. (3) predecessor span attestation (types 28/29): each file's head attests its numeric predecessor's index span so the merge can detect a damaged head instead of absorbing the gap into its lower bound. All four types sit below kRecordTypeSafeIgnoreMask, so older readers fail closed.

Decisions from the Step 0 merge prototype (built against real log files, validated, then discarded): void covers are lo-ordered -- a cover must not trail behind higher-index data, because a streaming merge decides the hole before scanning a trailing cover and stops spuriously; this rewrites WALIndexVoidRecordMayTrailTheHighWaterMark, which pinned trailing covers as legal. Real burns are singletons emitted at the fresh watermark (CoverBurnedWALIndex) and always comply. The span carries the predecessor's start, not just its end: R1.3 as written (end only) cannot satisfy its own acceptance test, since nothing else attests the lost start. The span is a new record rather than an extension of PredecessorWALInfo because track_and_verify_wals defaults off and the merge needs the attestation unconditionally. Data below an asserted progress bound is a merge-level contradiction enforced in D2, not a reader rejection, so the reader stays a pure cursor. Nobody in this stack writes progress or span records (nothing writes partitioned WALs yet); the writer APIs exist for tests and as the contract the future writer builds against.

Also moves the supersession head-position check into the shared decode so both readers inherit the same rule (behavior identical; the existing after-data test still matches).

Test Plan:
- `buck2 test fbcode//internal_repo_rocksdb/repo:log_test`: Pass 467, Fail 0 (379 base + 88 from 22 new TEST_P x4 params covering both readers and both framings; 2 tests rewritten for the void-ordering change).
- `buck2 test fbcode//internal_repo_rocksdb/repo:db_wal_test fbcode//internal_repo_rocksdb/repo:options_test`: Pass 2088, Fail 0. No DB recovery behavior changes.
- `clang-format <file> | diff - <file>` empty for all six changed files (verified per file, not asserted).
- Neuter checks (behavior removed, rebuilt, test red, restored): void-range tracking removed -> WALIndexVoidCoverageAnswersInsideBelowAbove red (4/4 params); progress-bound tracking removed -> WALIndexProgressRoundTrips, WALIndexProgressBeforeDataIsLegal, WALIndexProgressBackwardReportsCorruption red (12 total); span head-position check removed -> WALIndexPredecessorSpanAfterDataReportsCorruption, WALIndexPredecessorSpanAfterProgressReportsCorruption red (8 total, all other span tests stay green). Every other rejection test asserts both the corruption message and that the record contributes nothing (bound/span/coverage unchanged), so each goes red if its validation is removed.

`arc lint -a` on the changed files reports no issues.

Build size: the `log_test` build-size signal flags this diff as the blame, and that is expected rather than incidental. This diff adds 22 new parameterized `log_test` cases (88 instantiations), so `db/log_test.cc` object size grows. The regression is confined to the test binary; no shipping target is affected. Left in place rather than trimmed, because the coverage is the point of the diff.

Reviewers: xbw, #rocksdb, rajivharlalka, taopeng, anand76, kinbertchou, dyao, rbanerjee2, jkangs, jewoongh

Subscribers: jewoongh, rbanerjee2

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

M4 fold: Absorbs
- GC26 Q2 (reader side): log::Reader accepts strictly ascending further predecessor spans (GetFurtherWALIndexPredecessorSpans) and reports a repeated or backward span as corruption; test WALIndexFurtherPredecessorSpansAscend (exception X24: the test goes with this diff's reader code; the round's split said D123928339).
- 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 log_test); 471 tests, 0 failed.

Differential Revision: https://phabricator.intern.facebook.com/D120621828
fbsource-commit: ac0e030b59bd
Summary:
Reviewer question: is every category of hole accounted for -- burn-covered (skip), superseded-copy (consume silently, never skip an absence), below-bound (vacuous by construction, documented below), or the frontier (stop)?

This is the second of a three-diff stack building the read side of partitioned WALs: D1 completed the on-disk vocabulary, D2 adds the N-file merge, D3 switches recovery to it. D2 integrates with nothing and is reviewable against the merge's own tests.

`log::WALIndexMerger` sits above `log::Reader` and owns N readers (adopting the design's leaning so `Reader` stays a single-file cursor). It pulls every member to each expected index in turn and emits sequence-ordered record payloads with the index stripped, so the stream offers the same contract a single-file scan offers. Outcomes are explicit: kRecord, kCleanEnd, kFrontier (first unexplained hole with members holding records above it), kError (contradiction or unreadable member), kWaiting (one idle member needs re-pulling later -- the only keep-waiting state; clean EOF finishes, read errors fail). The merge derives its lower bound from first indices and D1 predecessor spans, unions supersessions across the set, checks an injected witness sequence strictly increases across indexed emissions, and exposes per-member end states (clean vs torn stop) for the recovery-mode mapping in D3.

Deviations from R2.3 as written, all learned from the Step 0 prototype: a supersession explains the copies it names, not the absence of a live copy -- skipping an absent index "because it is superseded" would hide a lost reissue, so a missing live copy resolves via void cover or frontier even when superseded copies exist (SupersededOnlyWithLiveAboveStops pins the stop). Below-bound is vacuous: the expected index starts at the derived bound, so no examined hole can be below it. Members are abstract (pull-based) with a Reader-backed implementation because a persistent idle is unproducible with closed real files -- real readers resolve a transient idle on re-pull (verified by tracing FragmentBufferedReader's UnmarkEOF paths) -- so R1.2/R2.4's deliberate idle testing needs scripted members. Data below a member's own progress bound fails the merge (the D1-deferred check). Membership: the merge takes the expected set and fails on a named-but-unheld file; D3 supplies it from the MANIFEST recovery set with no track_and_verify_wals changes. Obsolescence needs no separate enforcement during replay (the section 7 question): the merge emits live records only, so a consumer of the stream enforces it by construction.

Two reader behaviors this had to accommodate: recycled torn tails stop silently by design (no corruption reported), so head integrity checks the stopped flag too, not just reported corruption -- otherwise a torn head looks intact-but-empty. And the fragment-buffered reader treats a torn tail as growable (its pre-existing tailing semantic) rather than a stop, so the torn-tail end state is reader-dependent while the merged stream is identical; D3 uses plain readers and is unaffected.

M1: Absorbs GC15 Q4 merge hook + include (AMB-9 position; verified after D120649665 restack).

M2 fold (2026-10-22, `M2-FoldTasks.md` + `M2-Amendment.md`): Absorbs GC11 Q1 (M2): retirement bound, lost predecessor, `HeadBounded`, `min_anchoring_wal_`; tests `DataLessIdleMemberWithProgressDoesNotPinStream`, `DamagedHeadBoundedByLowerMemberSpan`.

Test Plan:
- `buck2 test fbcode//internal_repo_rocksdb/repo:log_merge_test fbcode//internal_repo_rocksdb/repo:log_test fbcode//internal_repo_rocksdb/repo:db_wal_test fbcode//internal_repo_rocksdb/repo:options_test`: Pass 2663, Fail 0 (108 new = 27 TEST_P x4 covering recyclable/non-recyclable framing and both reader flavors; 2555 pre-existing all green).
- `clang-format <file> | diff - <file>` empty for all three new files (verified per file, not asserted).
- Neuter checks (behavior removed, rebuilt, test red, restored): supersession filtering removed -> SupersessionRedirectsToNewerFile and SupersededOnlyWithLiveAboveStops red (8/8 params); witness comparison removed -> SequenceWitnessRejectsReorder red (4/4); attestation ignored -> TruncatedHeadWithSpanFailsClosed and DamagedHeadWithSpanReportsGap red (8/8) while the other head/span tests stay green.

`arc lint -a` on the changed files reports no issues.

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

M2 fold: new or moved tests here: DataLessIdleMemberWithProgressDoesNotPinStream, DamagedHeadBoundedByLowerMemberSpan. B.1 at this diff (format check, `rocksdb_lib`, touched test targets): PASS; log_merge_test 116 pass.

Reviewers: anand76, xbw, kinbertchou, huixiao, rbanerjee2, #rocksdb, rajivharlalka, taopeng, dyao

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

M4 fold: Absorbs
- GC26 Q2 (merge side): Member::AttestedSpans (default: the one span), the ReaderMember override, and ComputeLowerBound folding and anchoring over every attested span. Its test FurtherSpanExplainsRetiredFoldedHead lands in D120649665 instead (exception X25: here it reports kHole, not kCleanEnd).
- 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 log_merge_test); 116 tests, 0 failed.

Differential Revision: https://phabricator.intern.facebook.com/D120624825
fbsource-commit: 202194ec57fa
Summary:
Reviewer question: is every category of hole accounted for -- burn-covered (skip), swallowed (skip), superseded-only (skip, or frontier under a torn tail), tail gap (mode-mapped), pristine (frontier), below-bound (never asked), damaged head (fail)?

This is the third of a three-diff stack building the read side of partitioned WALs: D1 completed the on-disk vocabulary, D2 added the N-file merge, D3 switches recovery to it. D3 is reviewable against db_wal_test.

What it does: RecoverLogFiles routes indexed WAL sets (kWALIndexSingleFile, without track_and_verify_wals) through log::WALIndexMerger instead of the sequential per-file loop. The drive replays merged records through the shared ProcessLogRecord, so filtering, resume, memtable insertion, and consistency checks are unchanged; only the record source and the cut/seeding logic are new. Cuts become supersessions and the seed follows the cut exactly as D120415420: one past the highest index accounted (replayed or explained-skipped). kNone takes the untouched sequential path (byte-identical, pinned by the DefaultUsage tests), and the clean path reads each WAL once as before -- no extra recovery I/O.

Mode mapping (R3.2), the heart of the review. Trailing loss (every member finished) ends the stream and opens with a cut under tolerate/PIT/skip, fails under absolute when reported. A tail gap (torn/swallowed tail with members holding records above it) fails under tolerate and absolute -- this is the R3.2 behavior change: a hole only counts as a tail if nothing anywhere is above it, so opens that previously succeeded by replaying across the gap now fail with "cannot replay across the gap". Point-in-time cuts and resumes when sequences continue; skip replays across, cutting torn stops only. A pristine hole fails under tolerate/absolute/skip and opens at the cut under PIT. Skip forgives observed corruption but not unobserved absence: replaying across a gap nobody saw is the silent loss the merge exists to prevent. An unattested damaged head fails in every mode including skip: the loss below the first readable record is unbounded and undeclared.

Two merger behaviors from D2 changed, both forced by real histories found while writing the truth table. (1) The sequence witness is non-decreasing, not strictly increasing: an empty batch consumes an index but no sequence, so the recovery dummy and a user-written empty batch both repeat the sequence the next record reuses. Strictness fails the second open after any PIT cut. SequenceWitnessRejectsReorder still passes (it perturbs downward). (2) A superseded-only hole with no torn tail covering it skips instead of stopping: no member lost anything, so the index was never reissued after the cut and the merge re-trusts that declaration. Without this, the second open after any filter-stop cut fails in three modes. With a torn tail covering it the hole stays a frontier (fail-closed: the tail may hold the live copy), and skip opts out via continue_past_discarded_holes to extract the surviving stream. SupersededOnlyWithLiveAboveStops is amended to stop its member (same assertions, one flag) since its destroyed record is now a bounded swallowed span, which skips; SwallowedHoleSkipsSilently pins the skip as its neuter pair.

New explained category: swallowed loss. A member that reads past reports (skip or non-paranoid modes) attests the spans it skipped between positioned pulls, and the merge skips them silently -- unlike a void, a swallow never contradicts a holder, since the destroyed record may have been unindexed. This keeps skip's core promise (open a DB with mid-file corruption) while the frontier still stops unobserved holes. Pending-at-finish (reports after the last positioned pull, e.g. past an unindexed record) counts as tail impurity, closing the hole the per-read flag would miss.

Section 7 decisions. Membership: the merger checks the set it is given; D3 gives it the held live WALs (an unopenable WAL fails before the merge runs), and MANIFEST-named files compose with the pre-existing CheckWals under track_and_verify_wals_in_manifest, which fails the open first. Live WAL numbers are not contiguous (SSTs consume the same file-number space), so no range check is possible; a span-plus-min-log extension is future work, noted in code. Obsolescence is enforced at the merge (replay sees live records only), confirming the design's assumption. The merge sits above log::Reader (D2's leaning): Reader stays a single-file cursor, and recovery uses plain readers only -- a fragment-buffered idle is unreachable, and kWaiting fails closed.

R3.4 argument for the one modified test: WALIndexAtTypeLimitFailsRecovery wrote two records then overwrote the last index to Max, making the file {1, Max}. The sequential path never checked contiguity, so it replayed both and failed incidentally on counter exhaustion. The merge sees the 1-to-Max jump as the pristine hole it is and stops at the frontier first -- failing closed on massive silent loss, which is the point of the merge. The test's purpose is counter exhaustion, so it now uses one record (a hole-free {Max}); both old and new code fail recovery with Corruption on genuinely corrupt input, and genuine single-file histories recover identically.

Also replaces a non-ASCII em dash in a `db_wal_test.cc` comment introduced by this diff with `--`. RocksDB's `make check-sources` rejects non-ASCII characters in sources, so this would have failed that check on the OSS side.

M1: Absorbs 43 entries: GC01 Q1 merge rule + Q2/Q3 recovery + Q4 reporters (X1), GC02 Q2/Q3/Q5/Q6/Q8 + reader accessors (X2/X3), GC04 clean-member clamp part + Q7 test. X5-X7 (void seeding/clause/read needing `recovered_wal_partitions_`) moved to D123928339; recorded there too.

M2 fold (2026-10-22, `M2-FoldTasks.md` + `M2-Amendment.md`): Absorbs GC11 Q2/Q3/Q6 (M2): MANIFEST expected set, `SetRetirementBound(min_wal_number)`, hole message, seed before cut; lost-floor stop in `Next` and `LostPredecessorStopsAtItsFirstIndex` (exception X10: placed here, not D120624825, because the test reads `DriveResult::gaps`).

Test Plan:
- `db_wal_test`: 2018 passed (36 DBWALIndexTest: 26 pre-existing incl. the 1 argued above, 10 new truth-table tests covering void/superseded/shifted-start/pristine-hole/damaged-head/mixed/tail-gap/swallowed/dummy-second-open across modes)
- `log_merge_test`: 152 passed (136 pre-existing + 16 = 4 new TEST_P x4 params: swallowed skip, non-decreasing witness, discarded-hole split both ways); `log_test`: 467 passed; `options_test`: 80 passed
- `python3 tools/db_crashtest.py blackbox --simple --duration=300 --interval=30 --partition_wal_usage=wal_index_single_file --initial_random_seed_override=12345`: exit 0; crash-recovery verification passed. One unseeded run hit an ingestion assert in VersionSet::SetLastAllocatedSequence (stack has no merge/recovery frames; this stack touches neither path) and passed on rerun with fixed seeds
- Neuter checks (behavior removed, rebuilt, test red, restored): strict witness restored -> SecondOpenAfterPointInTimeCutReplaysDummy red (Corruption: does not advance the sequence); swallow spans removed -> SwallowedTypeCorruptionReplaysAcrossInSkipMode red (skip leg fails the open); sup-split removed (sup-only always frontier) -> SupersededAbsenceExplainedInAllModes red in tolerate/absolute/skip; tail-gap tolerate failure removed -> TailGapWithDataAboveIsNotATail red (tolerate opens); skip flag removed -> SecondOpenAfterPointInTimeCutReplaysDummy red (skip leg fails at the frontier)
- `arc lint -a` on the changed files: clean. `clang-format <f> | diff - <f>` empty for all six changed files (verified per file, not asserted)

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

M2 fold: new or moved tests here: LostPredecessorStopsAtItsFirstIndex. B.1 at this diff (format check, `rocksdb_lib`, touched test targets): PASS; db_wal_test + log_merge_test 2211 pass.

Reviewers: rbanerjee2, xbw, taopeng, anand76, rajivharlalka, dyao, #rocksdb, kinbertchou, jkangs, jewoongh, virajthakur, generatedunixname1816288208882371

Subscribers: jewoongh, rbanerjee2

M3 fold: Absorbs GC12 Q9 (the merge captures each record's checksum when it is pulled, including records buffered in the unindexed queue; recovery reads merger.GetLastEmittedChecksum()), GC12 Q6 (SetHistoryFloor: the history floor bounds ComputeLowerBound when no member attests a predecessor), GC12 Q10 (retired spans: an index a retired predecessor bore is skipped after the tail-gap check) and the Q9 extension of EmittedRecordsCarrySourceAndChecksum. Exception X3 (AMB-M3-2): these land here, not in D120624825, because last_emitted_member_, Member::LastRecordChecksum, have_lower and kTailGap first exist in this diff.

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_wal_test + log_merge_test: 2211 pass.

M4 fold: Absorbs
- GC19 Q1 (a reported gap stops point-in-time replay) and Q2 (superseded-only, void-skip, lost-floor and pristine frontiers; StopAtFrontier; pending_discarded_), its log_merge_test changes, and Q4's HeadBounded floor term (exception X11: reads history_floor_, first here).
- GC23 Q4: SkippedUnexplainedDiscard and the flush in ProcessLogFilesMerged's clean-end branch; test SkippedSupersededHoleSurvivesLaterWrites and the log_merge_test ports.
- GC24 Q1 merge-side head floors (ReaderMember::HeadFloor, ComputeLowerBound's floor term, exception X11) and Q6 (pending-discard stop, live-index refusal).
- GC26 Q4 (D-10): skip mode skips unexplained holes in the merge and ProcessLogFilesMerged (SetSkipUnexplainedHoles, GetSkippedHoles, GetFirstSkippedHole); the WALRecoveryMode docs and the partition_wal_usage sentence (exception X23: doc with behaviour, AMB-M4-18); the DBWALIndexTest skip cells; test SkipUnexplainedHolesEmitsAboveThem.
- GC26 Q2: test FurtherSpanExplainsRetiredFoldedHead (exception X25: moved up from D120624825; it needs this diff's frontier and head-floor code).
- 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_wal_test, log_merge_test); 2232 tests, 0 failed.

Differential Revision: https://phabricator.intern.facebook.com/D120649665
fbsource-commit: 57aba17d9759
Summary:
Reviewer question: does every marker/index contradiction fail while every legal transition shape still opens -- in particular, is failing indexed-without-marker only over an intact head (routing damaged heads to attestation) the right split, and is fail-open-plus-warning right for the undecidable marker-less/damaged-head/index-less case?

This is a new commit stacked on D120649665 ([Muse Spark][rocksdb][3/3] Recover indexed WALs through the merge); the diffs below are unamended.

What it does: the merge assumed every file it is handed carries indices, and a fully unindexed member's records drained first in encounter order regardless of global position -- silently wrong after a disable/re-enable sandwich (indexed, unindexed, indexed). This diff adds the gate in two layers. Recovery peeks at each live WAL's first record before replay (CheckWALFilesCarryWALIndex): marker-less files with unindexed first records route the whole set to the sequential path, which is the correct order while one WAL is written at a time; indexed data without a marker over an intact head fails fast with Corruption in every mode. The merge enforces the same contract on its own members (CheckMemberCoherence): an unindexed member fails before anything is emitted, indexed-without-marker fails after the attestation checks when the head is intact, and marker-with-all-unindexed-data fails at member finish. Every new failure names the WAL number and the broken invariant.

Decisions. R1b is head-conditioned: the head-damage suite below (DamagedHeadWithSpanReportsGap pins kFrontier, TruncatedHeadWithSpanFailsClosed pins the mismatch message) requires indexed-without-marker to reach attestation when the head is damaged, so only the intact-head case -- which no legal write sequence produces, since the writer emits the marker first -- is corruption. R1a fires only when a marker'd member finishes with unindexed data and zero indexed records, keeping legal mixed files and marker-only files open. R4's error carries the R5 evidence (head intact => predates the option; damaged => lost marker not ruled out). R5 verdict: the indexed side is decidable via head integrity as above; marker-less/damaged-head/index-less is genuinely ambiguous from the file alone, so it routes sequential with an info-log warning (failing closed would strand R2 upgrades and contradict the sequential path's tolerate/skip contract). A MANIFEST-persisted index epoch (first WAL number written with the option on) would decide it; proposed as future work. Empty and metadata-only files stay merge-side and inert. kNone and track_and_verify_wals skip the pre-pass entirely: byte-identical, no extra I/O, no new failures. The per-file answer travels on new Member virtuals (pass-through defaults keep scripted members compiling untouched) plus one additive reader flag per implementation; no format, ordering, or recovery-mode mapping changes.

Tests (10 new, existing suites unmodified): log_test WALIndexMarkerKnownAfterFirstRecord + WALIndexMarkerAbsentAfterFirstRecordInLegacyFile (R3, both reader impls via fixture params); log_merge_test UnindexedFileFailsMergeBeforeAnyEmission (R4, asserts empty emission) + UnindexedFileWithDamagedHeadNamesLostMarker (R5 evidence clause, scripted: real files cannot put an unindexed pull after a head report on demand) + MarkerWithoutIndicesFailsAtMemberFinish (R1a) + IndexedDataWithoutMarkerFailsWhenHeadIntact (R1b); db_wal_test MixedRecoverySetOpensAfterEnablingWALIndex (R2 upgrade incl. a true {unindexed, indexed} mixed set) + IndexedWALsOpenAfterDisablingWALIndex (R2 rollback) + MarkerWithoutIndicesFailsRecovery (R1a via marker prepend onto valid kNone batches, all 4 modes) + IndexedDataWithoutMarkerFailsRecovery (R1b via boundary-clean marker excision, all 4 modes).

Test Plan:
- buck2 test fbcode//internal_repo_rocksdb/repo:log_test fbcode//internal_repo_rocksdb/repo:log_merge_test fbcode//internal_repo_rocksdb/repo:db_wal_test fbcode//internal_repo_rocksdb/repo:options_test => Pass 2745, Fail 0 (DBWALIndexTest: 39/39 incl. 4 new, 35 pre-existing unmodified)
- python3 tools/db_crashtest.py blackbox --partition_wal_usage=record_ordering_single_file --two_write_queues=0 --duration=180 --interval=30 --max_key=10000 --ops_per_thread=20000 (from internal_repo_rocksdb/repo, db_stress rebuilt from this commit) => Crash-recovery verification passed
- clang-format <file> | diff - <file> empty for all 9 changed files (base was clean under the same binary, so the reflow touched only new hunks); arc lint -a clean
- Neuter checks, each verified by temporarily removing the behavior, watching the named test fail, then reverting: R4 gate removed => UnindexedFileFailsMergeBeforeAnyEmission fails (4/4 params); pre-pass R1b removed => IndexedDataWithoutMarkerFailsRecovery fails (falls through to the merge message, "before replay" assertion fails); routing forced to merge => MixedRecoverySetOpensAfterEnablingWALIndex fails (R4 error on reopen); finish gate removed => MarkerWithoutIndicesFailsAtMemberFinish (4/4) and MarkerWithoutIndicesFailsRecovery fail (open succeeds); lower-bound R1b removed => IndexedDataWithoutMarkerFailsWhenHeadIntact fails (4/4). UnindexedFileWithDamagedHeadNamesLostMarker shares the R4 gate neuter; the R3 tests are compile-coupled to the new getter; IndexedWALsOpenAfterDisablingWALIndex pins kNone behavior and has no neuter by construction.

Reviewers: #rocksdb, dyao, rajivharlalka, taopeng, kinbertchou, xbw, anand76, rbanerjee2, jkangs, virajthakur, jewoongh, generatedunixname1816288208882371

Subscribers: jewoongh, rbanerjee2

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_wal_test + log_merge_test + log_test: 2706 pass.

M4 fold: Absorbs
- GC23 Q1: misplaced-supersession detection (log::Reader SawMisplacedWALIndexSupersession, MisplacedSupersessionStatus) and its guards in ProcessLogFile and ProcessLogFilesMerged; test SupersessionAfterDataFailsClosed.
- GC24 Q9: the sequential-replay port, MoveWALSupersessionsLast and GC23MisplacedSupersessionFailsSequentialReplay.
- 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_wal_test, log_merge_test, log_test); 2733 tests, 0 failed.

Differential Revision: https://phabricator.intern.facebook.com/D121636079
fbsource-commit: 6d8b6af40730
Summary:
M1 standalone S-A (S-GC04), carved from GC04 Q1-Q3 plus GC05 Q8 (see those
round summaries for question evidence):
- MANIFEST `kWALIndexGuard` tag (500): VersionEdit encode/decode/debug,
  VersionSet state, `ReadWALIndexGuard`, rollover carry, handler apply,
  `UpdateWALIndexGuard`/`ClearWALIndexGuard` and the `Open` hook.
- `ldb check_wal_index` (empty/damaged WAL report) with `--wal_dir` and the
  configured-WAL-dir rule.
- Rollback procedure docs: `options.h` guard paragraph + steps 5-7,
  `log_format.h` guard sentence, release-note guard/`ldb` clauses.
- Tests: `VersionEditTest.WALIndexGuardFailsClosedOnUnawareReaders`,
  `WALIndexGuard*`, `NeverIndexedDBWritesNoWALIndexGuard`,
  `KNoneOpenThatFlushesIndexedWALsClearsTheGuard`,
  `CheckWALIndexReportsEmptyAndDamagedWALs`,
  `RollbackProcedureLeavesNoIndexedWAL`,
  `CheckWALIndexScansTheConfiguredWALDir`, helpers + includes.

Placed directly above D121636079 (lowest compiling position: the `ldb`
check needs `Reader::SawWALIndexMarker()`).

M2 fold (2026-10-22, `M2-FoldTasks.md` + `M2-Amendment.md`): Absorbs GC06 Q11 (M2): `check_wal_index` fails without OPTIONS, help text, `RunCheckWALIndexWithArgs`, `CheckWALIndexFailsWithoutTheOptionsFile`; GC11 Q7: `--wal_dir` after a failed OPTIONS load, test extension.

Test Plan:
gate at placement: `rocksdb_lib` builds; `db_wal_test` +
`version_edit_test` + `ldb_cmd_test` 2092 pass / 0 fail. Tip suites pass.

M2 fold: new or moved tests here: CheckWALIndexFailsWithoutTheOptionsFile. B.1 at this diff (format check, `rocksdb_lib`, touched test targets): PASS; db_wal_test + version_edit_test + ldb_cmd_test 2095 pass.

M3 fold: Absorbs GC12 Q8: the ldb check_wal_index help text (round-log correction of GC12's fold-back map).

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_wal_test + version_edit_test: 2077 pass.

Differential Revision: https://phabricator.intern.facebook.com/D126533192
fbsource-commit: f77113f2a1f0
Summary:
Why the change is required:
Indexed WAL recovery routes the recovery set to one of two replay engines: the N-file merge, which reconstructs a single ordered history across files, or sequential replay. The merge is only correct when every file in the set carries a WAL index, so a classification pass decides the route before either engine opens a file. That pass was built with its own reader construction, which could drift from the construction replay uses: a new reader option could reach replay and not classification, silently changing the basis of the route decision.

Previous behavior:
Classification built its readers inline and opened WALs through a path separate from both replay engines. The undecidable marker-less damaged-head case logged at INFO, where an operator investigating data loss would not see it. Nothing pinned the claim that a `kNone` open performs no classification I/O, or that classification visits each live WAL only once.

New behavior:
Classification and merged replay construct readers through one function, and classification, merged replay, and sequential replay all open WALs through `OpenWALForRecovery`. Routing decisions are unchanged. The undecidable case now logs at WARN. The cost claims are enforced by tests rather than asserted in prose.

Implementation:
- `NewWALIndexRecoveryMember` is the shared reader-construction seam for classification and merged replay; `OpenWALForRecovery` is the shared open seam for all three paths.
- A `DBImpl::CheckWALFilesCarryWALIndex:PerFile` sync point fires once per file the pass examines, carrying the WAL number, so a test can pin the visit count per file.
- `HeadIntact()` replaces the earlier `saw_corruption()` read at both marker-less decision points. This substitution is deliberate, not a rename. The pass makes exactly one pull per file, so any corruption the member has counted is at or before the first returned data record; `HeadIntact()` is the member's own expression of that bound. Reading it keeps the premise in one place rather than re-deriving it from a raw corruption flag whose meaning widens as the member reads further.
- The `kIdle` pull kind is now documented as unreachable here rather than silently folded into the no-data branch: idling is a merge-side concept for waiting on a member that may yet produce a record, and the plain recovery member this pass builds reads its file straight through. The merge re-pulls its own idles, so the case never crosses into classification.

Safety, compatibility, and limitations:
No on-disk format change and no routing change; this diff is hardening and observability only. A `kNone` open does no classification work at all. `track_and_verify_wals` continues to force the sequential path, because predecessor verification chains one file's replay into the next and the merge's concurrent pulls cannot reproduce that. The marker-less damaged-head case remains fail-open and sequential -- the WARN makes it visible, it does not change the outcome.

Classification reads at most one logical record per live WAL, including its physical fragments and configured readahead, and only during indexed non-manifest-verified recovery. That second read is retained deliberately: reusing partially consumed readers would couple classification to both replay engines and their distinct reporter and lifetime state, substantially widening a hardening change.

M1: Absorbs GC01 `TruncatingRecoveryLogsWALAndCut` + GC02 `TruncationSummaryCountsAndCleanCompletion` (X4: need `RecordingLogger`, first exists here).

Test Plan:
Built and run against `fbcode//internal_repo_rocksdb/repo:db_wal_test` (dev build).

- Full `db_wal_test`: 2,026 tests passed, exit 0 (1,015 s). `DBWALIndexTest` alone: 43 passed.
- New `PrePassExaminesEachLiveWALOnce` pins one classification visit per live WAL, keyed by WAL number so a repeat visit is distinguishable from an extra file being drawn into the pass. Scope is stated in the test: the hook fires once per loop iteration, so it pins visits, not reads per visit.
- `DamagedUnindexedHeadLogsWarning` now also asserts the routing decision itself -- the INFO `Recovering WALs sequentially` -- instead of inferring the route from the presence of the warning. It still requires exactly one WARN and zero INFO for the undecidable message, and that the WAL number appears in the warning.
- `WALIndexDecisionLogger` is replaced by `RecordingLogger`, which captures (level, message) pairs and exposes `saw(level, substr)` and `count(level, substr)`. The old helper filtered to one hardcoded substring and therefore could not express the routing assertion above.
- `MergeBackstopRejectsUnindexedWALAfterClassification` is unchanged in behavior. Its ordering dependency on the `:AfterClassification` hook is now written down, because moving that hook into the classification loop would leave the test green while silently changing what it exercises.

Neuter accounting, each restored afterwards:

- Re-run in this revision: removing the `:PerFile` sync point turns `PrePassExaminesEachLiveWALOnce` red (`fires.size()` is 0).
- Carried over from the previous revision and NOT re-run here: forcing classification under `kNone` turns `KNoneOpensEachWALOnceDuringRecovery` red (two opens); lowering the undecidable message to INFO turns `DamagedUnindexedHeadLogsWarning` red; removing the merge's unindexed-member rejection makes `MergeBackstopRejectsUnindexedWALAfterClassification` lose the required WAL-specific invariant error.
- Not covered by any neuter: the `HeadIntact()` substitution and the `OpenWALForRecovery` / `NewWALIndexRecoveryMember` consolidation are refactors with no behavior delta to invert. They are covered only by the suite staying green, which is weaker evidence than the items above.
- The `db_crashtest.py` blackbox run reported on the previous revision was not re-run for this revision.

Formatting and lint: `clang-format <file> | diff - <file>` is empty for all three changed files, using the repo-pinned `tools/third-party/clang-format/clang-format`. `arc lint -a` on the same three files reports no issues.

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

Reviewers: taopeng, anand76, #rocksdb, kinbertchou, dyao, rbanerjee2, xbw, rajivharlalka, jkangs, mszeszko, jewoongh, generatedunixname1816288208882371

Subscribers: jewoongh, rbanerjee2

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_wal_test: 2053 pass.

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

Tags: sentinelized
fbsource-commit: d2a53bb7fe6b
Summary:
First diff of the Partitioned WAL series. Adds the `wal_partitions` option and
its plumbing only -- no behavior change, and values > 1 are rejected at Open().

Motivation: a single WAL file admits only one append in flight at a time,
because durability granularity is per file descriptor. On storage where append
latency is high relative to bandwidth, that single outstanding I/O bounds write
throughput regardless of device bandwidth. Spreading writes across N WAL files
allows N concurrent appends. Recovery merges the partitions back into one
sequence-ordered stream, so the logical log is unchanged.

This diff lands the option so that later diffs -- routing, N write threads, the
durability watermark, multi-WAL recovery -- each have a configuration point to
hook into and can be reviewed independently.

Plumbing follows the existing `max_write_batch_group_size_bytes` pattern:
- `DBOptions::wal_partitions` (uint32_t, default 1)
- `ImmutableDBOptions` copy; not settable via SetOptions()
- OptionTypeInfo entry, so it round-trips through the OPTIONS file
- Dump() line
- BuildDBOptions()

Validation in `DBImpl::ValidateOptions`:
- 0 -> InvalidArgument
- > 1 -> NotSupported. The partitioned write path and multi-WAL recovery do not
  exist yet, so accepting the value would silently do nothing. Rejecting is
  removed in the diff that first makes N > 1 functional.

With the default of 1 the WAL is byte-for-byte identical to before.

M1 (owner-accepted): generated C API for
`experimental_allow_wal_partitions_for_testing` (+44, via
`make check-c-api-gen`), alongside the opt-in plumbing this diff holds.

M2 fold (2026-10-22, `M2-FoldTasks.md` + `M2-Amendment.md`): Absorbs GC06 Q1/Q6/Q7 (M2): `kMaxWalPartitions` and the bound check, kNone permanent rejection, CF blob/inplace checks, M1.4 table comment (doc-ahead, AMB-M2-3), `options.h` sentence; GC11 Q3/Q8: read-only/secondary `ValidateOptions`, db_bench tracking at N>1.

Test Plan:
Added `DBOptionsTest.WalPartitionsValidation` and
`DBOptionsTest.WalPartitionsRoundTrip` covering the default, 0, > 1, the
ImmutableDBOptions round trip, and parsing from the options string.

  buck2 test fbcode//internal_repo_rocksdb/repo:db_options_test \
             fbcode//internal_repo_rocksdb/repo:options_settable_test \
             fbcode//internal_repo_rocksdb/repo:options_test

  Tests finished: Pass 122. Fail 0.  (120 before this diff + 2 new)

`options_settable_test` is the one that would catch a missed plumbing site --
it fills DBOptions with a sentinel byte pattern and asserts every field is
reachable from the options string.

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

M2 fold: new or moved tests here: (none; checks covered by the D123079329 tests). B.1 at this diff (format check, `rocksdb_lib`, touched test targets): PASS; db_options_test + db_wal_test + options_settable_test 2113 pass; db_secondary_test + db_basic_test + db_readonly_with_timestamp_test 448 pass.

Reviewers: #rocksdb, rbanerjee2, anand76

Subscribers: jewoongh, rbanerjee2, anand76

M3 fold: Absorbs GC12 Q8 (a read-only open applies the wal_partitions checks ahead of CompactedDBImpl::Open) and GC14a Q4 (wal_partitions doc: manual_wal_flush is supported but not recommended above one partition).

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 + options_settable_test: 2120 pass.

M4 fold: Absorbs
- GC20 Q9: WalPartitionsValidation asserts the DBOptions() default of 1 (the "with indexing it opens" leg needs the lifted gate and is in the flip commit, exception X6).
- GC26 Q4: the recovery-modes paragraph of the wal_partitions doc (exception X23: the option's doc first exists here, above the D-10 code).
- 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, options_settable_test, db_stress, db_bench); 2123 tests, 0 failed.

Differential Revision: https://phabricator.intern.facebook.com/D117251769
fbsource-commit: ab5b582fe6d2
Summary:
Second diff of the Partitioned WAL series. Pure cleanup, no behavior change.

The WAL write path recorded which WAL a write landed in by reading the global
`cur_wal_number_`, even though every one of those call sites already has the
`WalFileNumberSize` of the WAL it is actually writing to. `WriteToWAL` even
asserted the two were equal:

    *wal_used = cur_wal_number_;
    assert(*wal_used == wal_file_number_size.number);

so the substitution is provably equivalent -- the assert becomes tautological
and is dropped with the read it was guarding.

Three sites:
- `WriteToWAL`: `wal_file_number_size` is already a parameter.
- `WriteGroupToWAL`: same, also a parameter.
- `ConcurrentWriteGroupToWAL`: hoists the `logs_.back()` / `alive_wal_files_
  .back()` selection above the `wal_used` assignment so the number has one
  source. Both were already inside the same `wal_write_mutex_` critical
  section, and the function already asserted
  `log_writer->get_log_number() == wal_file_number_size.number`, so the move
  changes nothing observable.

Why this is worth its own diff: `cur_wal_number_` is a single global, so it is
only meaningful while there is exactly one active WAL. Sourcing the number from
the WAL being written removes that dependency from the write path ahead of the
partitioning work, and it is reviewable on its own as a simplification -- it
deletes more than it adds.

Test Plan:
  buck2 test fbcode//internal_repo_rocksdb/repo:db_wal_test \
             fbcode//internal_repo_rocksdb/repo:db_write_test \
             fbcode//internal_repo_rocksdb/repo:write_callback_test \
             fbcode//internal_repo_rocksdb/repo:write_batch_test \
             fbcode//internal_repo_rocksdb/repo:db_basic_test

  Tests finished: Pass 2493. Fail 0.

`ConcurrentWriteGroupToWAL` is the two_write_queues / unordered_write path, so
it is covered separately by the transaction suites:

  buck2 test fbcode//internal_repo_rocksdb/repo:write_prepared_transaction_test \
             fbcode//internal_repo_rocksdb/repo:write_unprepared_transaction_test \
             fbcode//internal_repo_rocksdb/repo:transaction_test

  Tests finished: Pass 4062. Fail 0.

No new tests: this diff removes a redundant read and adds no branch. The
existing `wal_used` assertions in db_wal_test cover the value being correct.

M3 B.1 at this diff (clang-format 21.1.2 on its changed lines, make check-sources, debug librocksdb build; no test file touched): PASS.

Differential Revision: https://phabricator.intern.facebook.com/D117251770
fbsource-commit: 9e381b55bbac
Summary:
Third diff of the Partitioned WAL series. Pure refactor, no behavior change.

`WalContext` (db_impl.h) already bundles everything the WAL write path needs
about the WAL it is writing to:

    struct WalContext {
      bool need_wal_sync, need_wal_dir_sync;
      log::Writer* writer;
      WalFileNumberSize* wal_file_number_size;
      uint64_t prev_size;
    };

but `WriteImpl` unpacked four of those fields and passed them individually, so
the struct stopped existing one frame below the caller:

    WriteGroupToWAL(write_group, wal_context.writer, wal_used,
                    wal_context.need_wal_sync, wal_context.need_wal_dir_sync,
                    last_sequence + 1, *wal_context.wal_file_number_size);

Pass the context instead. Parameter counts drop from 7 to 4 for
`WriteGroupToWAL` and 7 to 6 for `WriteToWAL`, and the two functions now say in
their signature what they had to be told in four pieces.

`ConcurrentWriteGroupToWAL` and the recovery-time dummy write in
`db_impl_open.cc` were open-coding the same pair of fields from
`logs_.back()` / `alive_wal_files_.back()`; both now build a `WalContext`, so
every caller of `WriteToWAL` names its WAL the same way.

Why this is worth its own diff: `WalContext` is the natural per-WAL handle.
There is one today because there is one WAL, selected by `.back()` in
`PreprocessWrite`. Keeping it intact down the call chain is a prerequisite for
having more than one, and it means the follow-up diffs that add a partition id
and a WAL-record index to the context cost no further signature churn. On its
own it is a readability win, which is why it lands ahead of any partitioning.

Test Plan:
  buck2 test fbcode//internal_repo_rocksdb/repo:db_wal_test \
             fbcode//internal_repo_rocksdb/repo:db_write_test \
             fbcode//internal_repo_rocksdb/repo:write_callback_test \
             fbcode//internal_repo_rocksdb/repo:write_batch_test \
             fbcode//internal_repo_rocksdb/repo:db_basic_test \
             fbcode//internal_repo_rocksdb/repo:write_prepared_transaction_test \
             fbcode//internal_repo_rocksdb/repo:write_unprepared_transaction_test \
             fbcode//internal_repo_rocksdb/repo:transaction_test

  Tests finished: Pass 6555. Fail 0.

Covers all three call paths that changed: WriteImpl, PipelinedWriteImpl, and
ConcurrentWriteGroupToWAL (the two_write_queues / unordered_write path, via the
transaction suites). No new tests -- the signatures moved, the behavior did not,
and the compiler checks the call sites.

Reviewers: #rocksdb, rbanerjee2, anand76

Subscribers: jewoongh, rbanerjee2, anand76

M3 B.1 at this diff (clang-format 21.1.2 on its changed lines, make check-sources, debug librocksdb build; no test file touched): PASS.

Differential Revision: https://phabricator.intern.facebook.com/D117251771
fbsource-commit: c3b946b5d177
Summary:
Fourth diff of the Partitioned WAL series. No behavior change.

Three places independently open-coded the same selection of the WAL to append
to, each pairing two `.back()` calls with the same consistency assertion:

    wal_context.writer = logs_.back().writer;
    wal_context.wal_file_number_size = std::addressof(alive_wal_files_.back());
    assert(wal_context.writer->get_log_number() ==
           wal_context.wal_file_number_size->number);

in `PreprocessWrite`, in `ConcurrentWriteGroupToWAL`, and in the recovery-time
dummy write in `DBImpl::Open`. Replace all three with `SelectWalForWrite()`,
which does exactly that and carries the assertion once.

`logs_` and `alive_wal_files_` are always the same length and are always
`.back()`-ed together, so the pairing is an invariant, not a coincidence. The
assertion that was duplicated at two of the three sites is now unconditional at
all three.

Why a named function rather than leaving three two-line blocks: this is the one
point in the write path where "which WAL" is decided. Today the answer is
always "the newest", because there is one. Making that a seam is what lets the
answer become a routing decision later without touching the callers, and it
gives the locking requirement -- wal_write_mutex_ held, or Open() before the DB
is visible -- a single place to be documented instead of three.

Note the three sites only became textually identical in the previous diff of
this series, which is what makes the collapse mechanical rather than a
behavioral merge.

Test Plan:
  buck2 test fbcode//internal_repo_rocksdb/repo:db_wal_test \
             fbcode//internal_repo_rocksdb/repo:db_write_test \
             fbcode//internal_repo_rocksdb/repo:write_callback_test \
             fbcode//internal_repo_rocksdb/repo:write_batch_test \
             fbcode//internal_repo_rocksdb/repo:db_basic_test \
             fbcode//internal_repo_rocksdb/repo:write_prepared_transaction_test \
             fbcode//internal_repo_rocksdb/repo:write_unprepared_transaction_test \
             fbcode//internal_repo_rocksdb/repo:transaction_test \
             fbcode//internal_repo_rocksdb/repo:db_options_test

  Tests finished: Pass 6599. Fail 0.

Covers all three call sites: the normal write path, the two_write_queues /
unordered_write path, and DB::Open recovery. No new tests -- three copies of a
two-line block became one call, and the compiler checks the callers.

Reviewers: #rocksdb, anand76, rbanerjee2, generatedunixname1864816080879669

Subscribers: jewoongh, rbanerjee2, anand76

M3 B.1 at this diff (clang-format 21.1.2 on its changed lines, make check-sources, debug librocksdb build; no test file touched): PASS.

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

Tags: skip_dr_passed
fbsource-commit: 79a3c1763229
Summary:
Fifth diff of the Partitioned WAL series. Mechanical, no behavior change.

`logs_.back()` appeared at 13 call sites across four files, each one meaning
"the WAL currently being appended to" and each one carrying an unstated locking
requirement. Replace with a named accessor:

    LogWriterNumber& CurrentWal() {
      assert(!logs_.empty());
      return logs_.back();
    }

The `assert(!logs_.empty())` was previously present at only one of the 13 sites.

The declaration for `logs_` carries 15 numbered synchronization cases; the
accessor gives "the current WAL" one place to state its requirement
(wal_write_mutex_ held) instead of leaving it implicit at each use. It also
notes the subtlety already recorded on the member -- back() is not safe to call
unsynchronized, because implementations may touch other deque members.

Test Plan:
  buck2 test fbcode//internal_repo_rocksdb/repo:db_wal_test \
             fbcode//internal_repo_rocksdb/repo:db_write_test \
             fbcode//internal_repo_rocksdb/repo:write_callback_test \
             fbcode//internal_repo_rocksdb/repo:write_batch_test \
             fbcode//internal_repo_rocksdb/repo:db_basic_test \
             fbcode//internal_repo_rocksdb/repo:write_prepared_transaction_test \
             fbcode//internal_repo_rocksdb/repo:write_unprepared_transaction_test \
             fbcode//internal_repo_rocksdb/repo:transaction_test \
             fbcode//internal_repo_rocksdb/repo:db_options_test

  Tests finished: Pass 6599. Fail 0.

No new tests: a member access became a function call returning the same
reference, and the compiler checks every site.

M3 B.1 at this diff (clang-format 21.1.2 on its changed lines, make check-sources, debug librocksdb build; no test file touched): PASS.

Differential Revision: https://phabricator.intern.facebook.com/D117280372
fbsource-commit: 081f75633ebd
Summary:
The diff works to provide container of the WAL files handler to replace existing one wal file.

Stack: this diff sits on D117280372 with the write-path prep stack on D119751506 (per author direction; the prep content is unchanged from the D120171238-based version, and the base delta is read-path/test/comment-only, see Test Plan).

`DBImpl::logs_` and `DBImpl::alive_wal_files_` become one deque per WAL partition: `std::vector<std::deque<...>>`, sized 1 at construction. `wal_partitions > 1` is still rejected at Open, `SelectWalForWrite()` remains the only WAL-selection seam, and no public header, option, or on-disk format changes. Write-path point accesses bind partition 0; walks (obsolete-file selection, sync bookkeeping, size accounting, close) loop partitions in ascending index order under the same locks as before.

Locking documentation: the numbered cases are unchanged in content but reframed from "the deque" to "partition p's deque" under an explicit two-level split (the vectors are sized at construction and never resized, so they need no lock; every deque access holds the same global mutexes as before, since mutex splitting is out of scope). The back()/getting_synced observations are scoped to one partition's deque. Enforcement is mechanical where it can be: all access goes through the `WalLogs(p)` / `AliveWalFiles(p)` / `NumWalPartitions()` chokepoint with bounds and equal-length asserts, replacing direct member uses; the container abstraction itself still lands later once real N-partition usage is known.

Lifetime: each partition's deque keeps independent per-entry bookkeeping and removal stays per-entry (pop/erase), so a future reference-driven scheme can replace per-entry removal without reshaping; element addresses stay stable (deque elements never move, vectors never resized), which is what `CurrentWal()` references and `WalContext::wal_file_number_size` pointers rely on.

This diff also carries a one-word rebase-merge correction that belongs to the D117251771 rebase (`ConcurrentWriteGroupToWAL`'s cover call referenced `log_writer`, which the WalContext refactor removed; it now passes `wal_context.writer` like the two sibling sites). It lands here instead of in that diff per the no-touch rule for existing diffs; the rebased intermediate does not compile without it.

Behaviour preservation: the change is semantics-preserving by construction (same deque objects, same lock holds, loops run once), so most hunks have no neuter check available. Neutered instead: forcing `NumWalPartitions()` to 0 fails 8 `db_wal_test` tests (sync and WAL-lifecycle coverage incl. the new test below), proving the loops are load-bearing. No existing test caught a mistake during the change itself: the first full-matrix run passed, and the one real defect found (the `log_writer` merge breakage above) was caught by the compiler. New coverage is one pinning test, `DBWALTest.SingleWalPartition`, asserting exactly one partition across open, write, WAL roll, flush, and reopen; all existing tests pass unmodified.

Test Plan: `buck2 test fbcode//internal_repo_rocksdb/repo:db_wal_test fbcode//internal_repo_rocksdb/repo:db_write_test fbcode//internal_repo_rocksdb/repo:db_basic_test fbcode//internal_repo_rocksdb/repo:db_flush_test fbcode//internal_repo_rocksdb/repo:db_options_test fbcode//internal_repo_rocksdb/repo:repair_test fbcode//internal_repo_rocksdb/repo:log_test` - Pass 2888, Fail 0 on the submitted base. Targeted locking-route runs: `DBWALTest.SingleWalPartition`, `DBWALTest.WALWriteErrorNoRecovery`, `DBWALIndexTest.TwoWriteQueuesIsRejected`, `DBBasicTest.EmptyFlush` (all option configs incl. two_write_queues on), `DBBasicTest.DBCloseFlushError`, `DBBasicTest.ReadOnlyDBFlushWAL`, `DBWriteTestUnparameterized.PipelinedWriteRace` - all pass. Neuter (`NumWalPartitions()` forced to 0): 8 `db_wal_test` failures, reverted with byte-identical diff. R5 WAL byte comparison: fixed `db_bench fillseq` workload (num=20000, seed=12345) run against parent and new binaries - WAL bytes identical for `partition_wal_usage=none` and `record_ordering_single_file` (self-consistency verified first), identical Open rejection for `partition_by_column_family`; evidence gathered on D120171238-based binaries, and the move to D119751506 only drops a read-path/test/comment-only delta (reader validation, `log_test` cases, comment-only `log_writer.h`) touching none of this diff's files nor the write path, so the conclusion transfers - happy to re-run on request. 180s blackbox crash test with `--partition_wal_usage=record_ordering_single_file` on `db_stress` rebuilt from this commit: passed. `arc lint -a`: clean. `clang-format --dry-run --Werror` (v21.1.2, repo `.clang-format`): clean on all touched lines (two remaining violations are pre-existing rebase lines outside this diff).

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_wal_test: 2059 pass.

Differential Revision: https://phabricator.intern.facebook.com/D121858039
fbsource-commit: 91b7f3adfd8e
Summary:
Reviewer question: does every write-group path own scratch storage whose lifetime and exclusivity cover the synchronous WAL append?

WriteGroupToWAL previously flattened multi-writer groups into one DB-wide WriteBatch. Future partition leaders would merge, borrow a Slice from, append, and clear the same backing storage concurrently, allowing silent WAL corruption under load.

Give each WAL partition one reusable merge buffer, selected through the same bounds-checked partition accessor convention as its WAL deques. WalContext carries the selected partition from SelectWalForWrite to WriteGroupToWAL, and the buffer is cleared only after WriteToWAL returns. This retains allocation capacity across groups without introducing the larger deferred WalPartition ownership refactor.

ConcurrentWriteGroupToWAL keeps its existing invocation-local scratch because that path can already execute concurrently. The single-writer fast path still passes the leader batch directly and never touches the partition buffer. At one partition, WAL payload bytes, public APIs, options, and formats are unchanged; enabling multiple partition leaders remains out of scope.

Test Plan:
- `buck2 test fbcode//internal_repo_rocksdb/repo:db_write_test fbcode//internal_repo_rocksdb/repo:db_wal_test fbcode//internal_repo_rocksdb/repo:write_batch_test fbcode//internal_repo_rocksdb/repo:log_test`: 2,417 passed, 0 failed.
- `buck2 run fbcode//internal_repo_rocksdb/repo:db_write_test -- --gtest_filter=DBWriteTestUnparameterized.PartitionMergeBufferLifecycle --gtest_repeat=100`: 100/100 passed (each run covers both `two_write_queues` modes).
- `buck2 test @mode/dev-tsan fbcode//internal_repo_rocksdb/repo:db_write_test -- DBWriteTestUnparameterized.PartitionMergeBufferLifecycle`: passed under TSan.
- `DBWriteTestInstance/DBWriteTest.IOErrorOnWALWritePropagateToWriteThreadFollower/1` (kConcurrentWALWrites/two_write_queues) passes as part of the `db_write_test` run above.
- `PartitionMergeBufferLifecycle` runs once with `two_write_queues=false` and once with `two_write_queues=true`, reopening a fresh DB for each. In each mode it forces a two-writer group, proves the single-writer path does not borrow the merge buffer, verifies the exact merged payload bytes against an independently constructed WriteBatch, verifies the partition buffer is empty afterwards, and reopens with `avoid_flush_during_shutdown` to confirm all three values recover from the WAL. With `two_write_queues=false` the grouped WAL Slice must borrow the selected partition buffer (pointer identity); with `two_write_queues=true` it must not, because `ConcurrentWriteGroupToWAL` merges into invocation-local scratch and never reaches the member.
- Neuter 1 (per-partition ownership): replacing the selected partition buffer with an invocation-local `WriteBatch` fails `PartitionMergeBufferLifecycle` at `db_write_test.cc:444` (`group_borrowed_merge_buffer` false with `two_write_queues=0`).
- Neuter 2 (borrow outlives the append): moving `merge_buffer.Clear()` to before the `WriteToWAL` call fails `PartitionMergeBufferLifecycle` at `db_write_test.cc:451`; the payload captured at `DBImpl::WriteToWAL:log_entry` is an empty 12-byte header instead of `expected_group`. Restoring the implementation passes.
- A live N-partition race test is not possible in this diff because Open still rejects wal_partitions > 1 and enabling multiple leaders is explicitly deferred. R1 is additionally established by ownership: one fixed buffer per serialized partition leader, while the already-concurrent two-write-queues path retains one buffer per invocation.
- Built db_bench on the pinned parent and this change, ran the same one-thread 10,000-entry fillseq workload with seed 20260928 in fresh databases, and compared 000004.log with cmp: byte-identical, SHA-256 6d1351117a289a2784449a68d5421b1aa385ab0b383273c2c5918befa9181b09.
- Parent-versus-change on-disk comparison with a multi-writer db_bench workload: not used because repeated runs of the unchanged binary produced different WAL ordering and sizes. The deterministic forced-group payload comparison above covers the changed multi-writer merge path instead.
- `/usr/local/bin/clang-format --dry-run --Werror`: `db_write_test.cc` passes. `db_impl.h:2859` and `db_impl_write.cc:2419` report pre-existing violations on the base-owned `WriteToWAL` signature (94 columns, introduced by D117251771); deliberately left untouched to keep this diff minimal. No line this diff adds or changes is flagged.
- `arc f` and `arc lint -a` on all three changed files: no lint issues.
- `make check-sources`: not run successfully because the upstream script invokes git and this is a Sapling checkout (`fatal: not a git repository`).
- `AUTO_CLEAN=1 make check`: completed compilation and test execution but failed four repository checks unrelated to this change: Git-only check-format/check-sources, missing Ruby for check-workflow-yaml, and stale wal_partitions C API generation. The last reproduces with `make check-c-api-gen` on the parent alone; `DBOptions::wal_partitions` was added by D117251769 without regenerating `include/rocksdb/c.h`, `db/c.cc` and `c_api_gen/*.inc`.
- `AUTO_CLEAN=1 ASSERT_STATUS_CHECKED=1 make check`: not run because the ordinary full check is blocked by the same parent/environment failures above.

Subscribers: jewoongh, rbanerjee2, jkangs, #sentinel

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

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

Tags: sentinelized
fbsource-commit: 35a843aff22c
Summary:
Reviewer question: for every access to partition p's WAL state, is WalWriteMutex(p) held -- and does every multi-partition acquisition go through LockWalWriteMutexes(), in index order, with no Wait() under it?

PreprocessWrite takes the global wal_write_mutex_ unconditionally on every write purely to bind a writer to a WAL. At N partitions that serializes the resolve step on the hot path, so the feature would measure flat no matter what else is built. This diff splits the mutex before N leaders exist to contend on it.

New lock-ordering rule: mutex_ comes before every WAL write mutex; WAL write mutexes are taken in ascending partition-index order; sequence_wal_index_mutex_ is a leaf below them. A write binds to and appends to exactly one partition, so resolve (SelectWalForWrite), append (WriteToWAL), and the memtable-insert-failure truncate mark in WriteImpl hold exactly that partition's mutex and never a second, and all three read that partition's WAL (WalLogs(p).back(), via wal_context.wal_partition) rather than CurrentWal(). Operations spanning partitions (sync, obsolete-file cleanup, close, the manual-flush API surface) hold all N via the single guard LockWalWriteMutexes()/AllWalWriteMutexesLock -- the only multi-take implementation. Debug builds enforce the order rather than relying on that convention: every WalWriteMutex(p).Lock() asserts the calling thread holds no WAL write mutex of the same DB at an equal or higher index, and the partition mutex privately inherits InstrumentedMutex so the unchecked InstrumentedMutexLock path does not compile against it (single-partition takes use WalWriteMutexLock). A Wait() on WalSyncCV(p) holds WalWriteMutex(p) and no other partition mutex.

What changed: wal_write_mutex_ becomes one InstrumentedMutex per partition (with one bound condvar each), wal_empty_ becomes per-partition bytes, and the deferred-free list becomes per-partition; all live in the partition-vector convention from the containers diff with bounds-checked accessors. SelectWalForWrite binds the partition WalPartitionForWrite() selects (0 today; routing owns the future), and callers take that mutex before binding, so single-acquisition is structural.

Three structural points a reviewer should check. First, waits are sequential per partition because waiting while holding several partition mutexes deadlocks: pthread_cond_wait releases only the bound mutex, so a waiter holding others would sleep while a sync completion holding all N blocks on them. Second, PreprocessWrite claims the selected partition last so its claim and bind are atomic under one hold; a rotation landing between them would append an unmarked WAL the completion's MarkLogsSynced would trip on. Third, FlushWAL/WALBufferIsEmpty span all partitions (the manual-flush surface keeps meaning "all buffered WAL data"), while WriteToWAL's manual-flush exclusion takes exactly the written partition's mutex.

CurrentWal() stays a partition-0-only accessor (inherited from D117280372). Its remaining callers are rotation in SwitchMemtable, Open, the post-error reset_seen_error() in WALIOStatusCheck, and MaybeWriteWalMarkersToManifestOnClose(); they target partition 0 by construction and none is on the per-write path. The diff that makes a second partition reachable must parameterize them.

The owned WalPartition type stays deferred, with a trigger: it lands in the first diff that makes a second partition reachable (Open accepting wal_partitions > 1, or WalPartitionForWrite() returning non-zero), or before an eighth per-partition vector is added, whichever comes first. Until then the seven parallel vectors are held aligned only by the equal-length asserts in NumWalPartitions().

Instrumentation gap (for M1.3): wal_write_mutexes_ are default-constructed, so their InstrumentedMutex stats_/clock_/stats_code_ are null and they report no wait time -- as the global wal_write_mutex_ did, so not a regression. Per-partition WAL-write-mutex contention needs WalWriteMutexType to forward a (stats_, immutable_db_options_.clock, <ticker>) constructor, as mutex_ does with DB_MUTEX_WAIT_MICROS.

Deliberately preserved: the WriteToWAL early return without unlock on timestamp-record failure (pre-existing, out of scope); the two base-owned WriteToWAL signature clang-format violations. No public header, option, or format change. At one partition the mutex takes are the same single mutex, so behavior and WAL bytes are unchanged.

M1: M1 §6 item 1: `-Wshadow` fix — `wal_partition` local renamed to `bound_partition` in the `WriteImpl` error path (this diff introduced it). No behavior change.
M2 fix pass (2026-10-22): after the stack was rebased onto fbcode/stable `063e2f73a689`, upstream's slow mutex hold logging (`InstrumentedMutex::ConfigureSlowHoldLogging`, called for `wal_write_mutex_` in the `DBImpl` constructor) no longer compiled here, since this diff replaces that member with one mutex per partition. The constructor now configures it on every `WalWriteMutexType` in `wal_write_mutexes_` (name `DBImpl::wal_write_mutexes_`), and `WalWriteMutexType` re-exports `ConfigureSlowHoldLogging` alongside `AssertHeld`. Lock order checks are unchanged. At one partition this is the same single mutex as upstream.

Test Plan:
- `buck2 test fbcode//internal_repo_rocksdb/repo:db_wal_test fbcode//internal_repo_rocksdb/repo:db_write_test fbcode//internal_repo_rocksdb/repo:db_basic_test fbcode//internal_repo_rocksdb/repo:log_test`: 2737 passed, 0 failed.
- `buck2 test @mode/dev-tsan fbcode//internal_repo_rocksdb/repo:db_wal_test fbcode//internal_repo_rocksdb/repo:db_write_test`: 2052 passed, 0 failed.
- `buck2 build @mode/opt fbcode//internal_repo_rocksdb/repo:rocksdb_lib fbcode//internal_repo_rocksdb/repo:db_bench`: builds (covers the `NDEBUG` path of the lock-order check).
- New `DBWALTest.SplitWalMutexConcurrentManualFlush` (manual_wal_flush x two_write_queues off/on; writers hammer while main thread runs FlushWAL/WALBufferIsEmpty/Flush/LockWAL/UnlockWAL): passes normally and under TSan.
- New `DBWriteTestUnparameterized.WalWriteMutexConfigurationMatrix` (ported verbatim from D122438434): all four `two_write_queues` x `manual_wal_flush` configurations check `WALBufferIsEmpty()` before and under `LockWAL()`, a concurrent `no_slowdown` writer gets `Incomplete` while locked, and writes resume after `UnlockWAL()`. Passes normally and under TSan.
- New `DBWALTest.MemtableInsertFailureTruncatesBoundWal` covers the memtable-insert-failure path in WriteImpl, which no existing test reached: a batch naming a nonexistent column family appends to the WAL (size grows) and then fails the memtable insert with `InvalidArgument`; after `Close()` the WAL is truncated back to its pre-append size, and a reopen recovers the earlier write. Neuter N5 (drop the `SetAttemptTruncateSize` call): fails at `db_wal_test.cc:4284` (WAL size after close != pre-append size). At one partition the test cannot distinguish partition 0 from the bound partition; that choice is structural (the mutex and WAL both come from `wal_context.wal_partition`, set by SelectWalForWrite from WalPartitionForWrite()).
- Neuter N1 (WriteToWAL needs_locking forced false): new test Fatal under TSan with a data race in AlignedBuffer::CurrentSize (AddRecord vs FlushWAL). Reverted with matching checksum.
- Neuter N2 (PreprocessWrite resolve locks dropped): new test Fatal under TSan with a data race between SelectWalForWrite and FindObsoleteFiles. Reverted with matching checksum.
- N1 and N2 re-run on the final code under TSan: both still Fatal with the same races (N1: `AlignedBuffer::CurrentSize` in `WritableFileWriter::Flush` vs `AlignedBuffer::Append`; N2: `SelectWalForWrite` vs `FindObsoleteFiles` `pop_front`). Reverted with matching checksum.
- Neuter N3 (lock order, runtime): taking `AllWalWriteMutexesLock` inside the `SyncWalImpl` claim loop's single-partition hold (a second multi-take written outside the guard) makes `SplitWalMutexConcurrentManualFlush` abort in `WalWriteMutexType::AssertLockOrder()` instead of deadlocking. At one partition an out-of-order take can only be a re-take of partition 0, so this is the N=1 form of the violation; reversing the guard's loop is not a neuter at N=1 because it iterates one mutex. Reverted.
- Neuter N4 (lock order, compile time): changing one site back to `InstrumentedMutexLock wal_lock(&WalWriteMutex(p))` fails to build with "cannot cast 'WalWriteMutexType' to its private base class 'InstrumentedMutex'". Reverted.
- Byte-identical WAL comparison: one-thread 10,000-entry `db_bench fillseq` with seed 20260928 in fresh DBs, `@mode/opt` binaries built from the parent and from this change (binary SHA-256 prefixes 6596daddc8b1d917 vs 88cf0e6145a6002a; re-run after the final amend): `000004.log` byte-identical (`cmp` returned 0) for `partition_wal_usage=none` (1,380,286 bytes, SHA-256 6d1351117a289a2784449a68d5421b1aa385ab0b383273c2c5918befa9181b09, matching the base diff's reported hash) and for `record_ordering_single_file` (1,460,277 bytes, SHA-256 9a69a3fc66777fadce05e8a999479a5f57364aca27cd6d22aa00e4631adfc796, matching D122438434's reported hash for the same workload).
- `tools/db_crashtest.py blackbox --stress_cmd=<dev db_stress built from this commit> --duration=180 --interval=10 --partition_wal_usage=record_ordering_single_file --disable_wal=0 --two_write_queues=0 --manual_wal_flush_one_in=1000`: 16 kill/recover iterations, exit 0, "Crash-recovery verification passed". Run on the previous revision of this diff (before the failure-path/resolve partition fix and `MemtableInsertFailureTruncatesBoundWal`); not re-run after the final amend.
- `AUTO_CLEAN=1 make check`: 4,967 jobs; exit 2. Environment/base failures: Git-only `check-format`/`check-sources`, missing Ruby for `check-workflow-yaml`, and stale generated `wal_partitions` C API output inherited from D117251769. One unit-test failure, `RateLimiterTest.Rate` (29.6s timing assertion under the 192-way parallel run; `util/`, untouched here); it passes when re-run alone (`buck2 test fbcode//internal_repo_rocksdb/repo:rate_limiter_test -- RateLimiterTest.Rate`) and passed in the run below. Run on the previous revision of this diff (before the failure-path/resolve partition fix and `MemtableInsertFailureTruncatesBoundWal`); not re-run after the final amend.
- `AUTO_CLEAN=1 ASSERT_STATUS_CHECKED=1 make check`: 4,944 jobs, no unit-test failures; exit 2 for the same Git-only and missing-Ruby checks. Its `check-c-api-gen` passed only because the previous run's generator rewrote the checked-in C API files in place; those were reverted afterwards and are not part of this diff. Run on the previous revision of this diff (before the failure-path/resolve partition fix and `MemtableInsertFailureTruncatesBoundWal`); not re-run after the final amend.
- `make check-sources`: not runnable (upstream script requires git; this is a Sapling checkout).
- `arc f` (no configured linters) and `arc lint -a` on all changed files: clean. `clang-format --dry-run --Werror` (v21.1.2) on every changed C++ file: clean on all touched lines; the two remaining violations are the pre-existing base-owned `WriteToWAL` signature lines.

M1: `rocksdb_lib` builds at amend. Tip suites 7870/0.
M1 re-verification (2026-10-20, after rebasing the stack onto master f0c3a35689fc and clang-formatting): per-diff gate at this diff passed (CI format check, `rocksdb_lib` build, touched test targets); tip suites 8126/0; N=1 byte identity equals T0.
M2 fix pass (2026-10-22, stack rebased onto fbcode/stable 063e2f73a689): per-diff gate at this diff (CI format check, `rocksdb_lib`, db_wal_test + db_write_test) 2118/0. Tip: 27 suites 8667 pass / 0 fail (one timeout in the upstream `DBWriteBufferManagerTest.WaitForCompactDrainsReservedWBMFlushHandoff`; 140 reruns at the tip pass), N=1 byte identity unchanged (kNone 6d1351117a28…, indexed 9a69a3fc6677…), TSan `DBWritePartitionTest` 170/0 with 0 warnings, `arc lint -a` clean.

Reviewers: xbw, #rocksdb, peterd, rbanerjee2, anand76

Subscribers: jewoongh, rbanerjee2, anand76

M3 fold: Absorbs GC08 Q4 (FlushWAL attributes a failed flush to the WAL that failed; exception X5: hand-ported here as failed_wal_number = WalLogs(p).back().number, which D123971668's accessor rewrite turns into current_wal->number) and GC17 Q4 (cache-line padding: WalWriteMutexType is ALIGN_AS(CACHE_LINE_SIZE) with static_asserts, wal_empties_ holds CacheAlignedWrapper<uint8_t>, util/mutexlock.h included).

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_wal_test + db_write_test: 2118 pass.

M4 fold: Absorbs
- GC20 Q4: CoverBurnedWALIndex takes the partition WAL mutex whenever WriteToWAL would (wal_partition, wal_mutex_held), and its call sites pass the partition (exception X5: needs NumWalPartitions and WalWriteMutex(p), first here; the round's map said D119751506, AMB-M4-15).
- 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_wal_test, db_write_test); 2121 tests, 0 failed.

Differential Revision: https://phabricator.intern.facebook.com/D122412677
fbsource-commit: 9b0a332027c8
Summary:
Reviewer question: do these three histograms capture the deferred write-path decisions' signals — writers per group, group-cap-hit rate, and time blocked in `JoinBatchGroup` — as distributions, with no behavior change and no cost when statistics are off; and does `WRITE_GROUP_CAP_EXCLUDED` count only size-cap exclusions rather than every exclusion?

Signals, no policy: nothing here reads a metric and acts on it. This diff emits the data for M0.8 (route-then-group vs group-then-route, needed before diff 06) and M1.3 (load-aware vs fixed routing), both measurable now at one partition because grouping, the cap, and `JoinBatchGroup` queueing all happen pre-partitioning today.

Three new histograms, no tickers: `rocksdb.writers.per.write.group` (writers per WAL-side write group, one sample per group from the leader, at all three group-formation sites — `WriteImpl`, `PipelinedWriteImpl`, `WriteImplWALOnly`); `rocksdb.write.group.cap.excluded` (writers per group excluded by `max_write_batch_group_size_bytes` while otherwise compatible, so the cap-hit rate is the fraction of groups with a non-zero sample); `rocksdb.join.batch.group.wait.micros` (microseconds blocked in `JoinBatchGroup` per write, via a scoped `StopWatch` at all three call sites, in the same unit as the future watermark waits so the R3 comparison reads directly).

Sample output (`db_bench` fillrandom, 16 threads x 200k writes, 1KB values, `--statistics`):
```
rocksdb.writers.per.write.group P50 : 7.736952 P95 : 9.962466 P99 : 13.849150 P100 : 16.000000 COUNT : 403697 SUM : 3200000
rocksdb.write.group.cap.excluded P50 : 0.000000 P95 : 0.000000 P99 : 0.000000 P100 : 0.000000 COUNT : 403697 SUM : 0
rocksdb.join.batch.group.wait.micros P50 : 27.612568 P95 : 43.873479 P99 : 50.960688 P100 : 36857.000000 COUNT : 3200000 SUM : 93706872
```
Cross-checks hold exactly: writers SUM == join-wait COUNT == #writes (3.2M); #groups == `WRITE_DONE_BY_SELF` == `BYTES_PER_WRITE` COUNT (403,697). The cap metric moves when the cap binds (32 threads, 100KB values): groups collapse to ~2 writers with cap-excluded P50 28/group; the attribution handles the small-leader effective cap (leader + max/8).

Decisions. Buckets: RocksDB histograms share one fixed 1.5x geometric mapper — per-histogram buckets do not exist, and adding them would touch shared monitoring code; the runs above spread across buckets (P50 != P95 != P99), so the shared mapper resolves both the small-int distributions and the microsecond tails. WAL write mutexes: not wired — `InstrumentedMutex` only reports a cumulative kAll-gated ticker, which R2 rules out and which cannot attribute per-partition (the split M1.3 turns on); at one partition the wait is ~0 by construction (single group leader; followers never take the mutex), so it would ship unverifiable, while the relievable contention is visible now in the join-wait distribution; wiring it as a histogram belongs to diff 06, when N write threads make it non-zero. Per-partition: nothing is per-partition here — at one partition global and per-partition(0) are indistinguishable in output, and queueing plus group formation both happen pre-binding today, so the aggregate is the baseline M0.8/M1.3 need; per-partition restatement rides with diff 07, hence no new parallel vector and no `WalPartitionForWrite` use. Off-cost: `StopWatch` reads no clock when `stats_` is null and `RecordInHistogram` is one null branch, the same footing as the existing `DB_WRITE`/`BYTES_PER_WRITE` recordings; the factored exclusion test in `EnterAsBatchGroupLeader` evaluates identical clauses in identical order (single-copy bodies preserved), and counting is a rare-path increment.

Cap-exclusion attribution is tested directly. `DBWriteTestUnparameterized.WriteGroupCapExcludedAttribution` forces one cap exclusion and one compatibility exclusion in the same group formation and asserts only the former is counted. The leader is a non-sync write whose batch alone exceeds `max_write_batch_group_size_bytes` (1024); behind it queue a sync write (incompatible with a non-sync leader) and a compatible small non-sync write that cannot fit under the cap. Sync mismatch is the non-cap exclusion because it is the simplest to force -- one `WriteOptions` flag, no helper class -- and it exercises the first `incompatible` clause. Followers spawn sequentially: the `Wait` sync point fires after `LinkOne` (`write_thread.cc:405` links, `:413` callbacks), so a counted follower is already queued, and waiting for each before starting the next fixes the queue order deterministically. Group 1 is the leader alone (cap sample 1); group 2 is the sync follower leading with the small compatible follower joining under the small-leader effective cap (cap sample 0). Without this test the attribution is unverified: both other tests pass unchanged if `num_cap_excluded` were incremented on every exclusion, since one has no exclusions at all and the other has exactly one, which happens to be a cap exclusion.

Neuters, all verified live by mutation and reverted. Attribution: changing `if (over_cap)` to count every exclusion fails `WriteGroupCapExcludedAttribution` with `cap_excluded.sum` 2 vs expected 1 (and max 2 vs 1), while the other two tests still pass under the same mutation. Recordings: removing the `WRITERS_PER_WRITE_GROUP` recordings fails `WriteGroupHistograms` (count 0 vs 1); removing the `WRITE_GROUP_CAP_EXCLUDED` recordings fails `WriteGroupCapExcludedAttribution` (count 0 vs 2); removing the `JOIN_BATCH_GROUP_WAIT_MICROS` StopWatches fails `WriteGroupHistograms` (join count 0 vs 3); removing only the pipelined-site writers recording fails `WriteGroupHistograms` in that mode, so the per-mode fresh statistics cover each of the three sites individually. No neuter exists for the `EnterAsBatchGroupLeader` disjunction restructure itself, by design: `incompatible || over_cap || ingest_wbwi` evaluating identical clauses in identical order is an equivalence argument from inspection, including the short-circuit that keeps `ByteSize(w->batch)` off a null batch (`w->batch == nullptr` sits inside `incompatible`, which gates the cap test).

What this answers now: M0.8's batching baseline (group-size distribution, whether the cap binds) and M1.3's queueing baseline (blocked-time distribution including the tail). Still waiting on diff 07 (R4, not stubbed here): the sync-barrier fan-out (`|{p : pending_low_synced[p] < my_sequence}|` at each sync=true write), its induced latency, and per-partition completion latency — all require the watermark.

M1: Absorbs GC13 Q3: histogram enum/docs/name map/Java, WAL-mutex recording, `WalPartition*` helpers (mutex recording sits here, not D122412677, per W13).

Test Plan:
- `buck2 test fbcode//internal_repo_rocksdb/repo:db_write_test` — Pass 57/57, including 3 new tests (`WriteGroupHistograms` over default/pipelined/unordered modes, `WriteGroupCapExcludedHistogram`, `WriteGroupCapExcludedAttribution`); all pre-existing tests unmodified and passing.
- `WriteGroupCapExcludedAttribution` repeated 200 iterations (two `--gtest_repeat=100` runs of the built binary) — 200 passed, 0 failed.
- Neuter runs (temporary mutations, each reverted and the tree re-confirmed afterwards): attribution neuter and all recording-removal neuters red as specified in the Summary.
- `buck2 test fbcode//internal_repo_rocksdb/repo:statistics_test` — Pass 3/3, including `SanityHistograms` covering the new name-map entries.
- `buck2 test fbcode//internal_repo_rocksdb/repo:db_basic_test` — Pass 346/346.
- `buck2 test fbcode//internal_repo_rocksdb/repo:write_callback_test` — Pass 129/129 (adjacent grouping-callback coverage for the restructured exclusion test).
- Production-shaped `db_bench` (fillrandom, 16 threads x 200k, 1KB values, `--statistics`): histograms spread as quoted in the Summary with exact cross-checks. Full log: `/tmp/m10_fillrandom.log`.
- Cap-binds `db_bench` (fillrandom, 32 threads, 100KB values): groups ~2 writers, cap-excluded P50 28/group — the metric moves. Full log: `/tmp/m10_bigvalue.log`.
- Byte-identical WAL at one partition (fillseq, 1 thread, 10k entries, seed 20260928): SHA-256 `6d1351117a289a2784449a68d5421b1aa385ab0b383273c2c5918befa9181b09`, matching the published hash from the two diffs below; base-vs-patched A/B run also byte-identical.
- Disabled-statistics cost: 15 alternating base-vs-patched `db_bench` pairs without `--statistics` (final 6 pairs write-path-only: no flush/compaction); patched faster in about half the clean pairs, all within shared-box noise; medians within 3%. No measurable write-path cost.
- Formatting: repo-pinned clang-format-21 clean on all touched files except the pre-existing base-owned 94-col `WriteToWAL` signature line (in `db_impl_write.cc`, from D117251771), deliberately left untouched like the diffs below.
- `arc lint -a`: no issues. (`arc f` reports no applicable formatters in this environment; formatting verified directly with the pinned clang-format.)
- Java: `HistogramType.java` compiles standalone with `javac`; `statisticsjni.cc` (covers the new `portal.h` cases) compiles with `g++ -fsyntax-only`. Java unit tests: not run — no Java test targets exist in the repo BUCK file.

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

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

Subscribers: jewoongh, rbanerjee2

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

Differential Revision: https://phabricator.intern.facebook.com/D122660502
fbsource-commit: 40fbfc66af88
Summary:
Reviewer question: are these the right three routing rules -- stable hash of the smallest column-family id by default, smallest CF id as the multi-CF tie-break, and stable hash of the smallest XID for CF-less transaction markers, with partition 0 only when no XID exists?

The base measurement found zero group-cap exclusions across 403,697 groups, while join waits ranged from a 27.6 us median to a 36.8 ms maximum. This therefore does not use cap pressure to justify routing. It chooses deterministic CF hashing because the long queueing tail is real but the later watermark-wait measurement is still needed to show whether another partition could absorb it; this policy improves isolation across CFs without claiming relief for a single-CF workload.

Resolve the route exactly once before all three group-formation paths, carry it on the writer, and prevent a WAL record from grouping writers with different routes. SelectWalForWrite remains the only WAL-binding seam. Hashing XIDs prevents ordinary 2PC commit markers from creating a fixed-partition straggler, while sequence numbers, keys, values, and caller threads are excluded from routing.

The one-partition neuters are the early return of partition 0 before batch iteration or hashing and the always-false writer partition mismatch. A fixed db_bench workload produced byte-identical WAL output against the parent. No semantic behavior lacks a neuter; the partition field plumbing and comparison still execute because they carry and enforce the already-resolved decision, but they cannot change selection or grouping while every route is 0.

**Folded in from round 12 (D124911745) and round 12.1 (D125113461)**
- Cross-partition group exclusion has a direct `WriteThread` test: `WriteThreadPartitionTest.DifferentPartitionsFormSeparateGroups`. The DB can't reach this case because per-partition write threads never meet. Three writers routed {0,0,1} form groups {A,B} then {C}. Neuter: drop the partition-mismatch clause -> one group of 3 -> fail.
- The P=1 early return in the router is a performance shortcut, not a neuter: `hash % 1 == 0` either way. This replaces the neuter claim above.
- Routing inputs: `TEST_WalPartitionForWrite` takes deferred CF ids. `RoutesDeferredPutEntitiesByColumnFamily`: the deferred route equals the direct route, and a deferred CF joins the minimum. `HashesPrepareAndTimestampedCommitXids`: the same XID routes the same way through either marker. Neuters: drop the deferred loop, or drop either marker's `AddXid` -> route 0 -> fail.
- `WalRoutingTest.OnePartitionIsNeutered` keeps its original name and body (12.1 reverted round 12's rename).

Test Plan:
- Pinned-base gate: passed; HEAD was b7ccb4b44b0c, status was clean, and only(., public()) matched all 24 dispatched subjects in order.
- buck2 test fbcode//internal_repo_rocksdb/repo:db_write_test: passed, 60 tests after final formatting.
- buck2 test fbcode//internal_repo_rocksdb/repo:db_wal_test: passed in the combined required suite.
- buck2 test fbcode//internal_repo_rocksdb/repo:transaction_test: passed in the combined required suite.
- buck2 test fbcode//internal_repo_rocksdb/repo:db_basic_test: passed in the combined required suite.
- Combined required suite: passed, 5,543 tests with zero failures, timeouts, fatals, skips, omissions, infra failures, or build failures.
- Direct routing coverage at four partitions: passed for a CF id reaching every partition, multi-CF order-independent smallest-id selection, sequence/key/value independence, XID distribution, smallest-XID selection, XID-less fallback, and the one-partition neuter.
- One-partition WAL comparison: passed; cmp found byte-identical 1,000-write fillseq WALs and both SHA-256 hashes were bac3d8a3e81835780bd50f6df0275127eefd81d8c4e132977fd20c2fd715a1b7.
- Repo-pinned clang-format --dry-run --Werror on every changed range: passed.
- arc lint -a: passed with no lint issues.
- Write-group instrumentation benchmark: not rerun; policy selection uses the supplied D122660502 results above, and the fixed workload rerun was reserved for byte identity.

**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 137, Fail 0 (https://www.internalfb.com/intern/testinfra/testrun/17169973791598798).
- 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.

Reviewers: generatedunixname1816288208882371

Subscribers: jewoongh, rbanerjee2, jkangs

M3 fold: Absorbs GC17 Q3: the router scans record headers and never fails (WalPartitionForWrite returns the partition; WalRoutingCollector and the routing error returns are gone; TEST_WalPartitionForWrite keeps its signature), the Open post-recovery marker call hand-applied to this diff's context, and the tests HeaderScanMatchesIteratingRouter and MalformedBatchRoutesDeterministically with their includes.

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

Differential Revision: https://phabricator.intern.facebook.com/D122869562
fbsource-commit: bccb2ca10a98
Summary:
Reviewer question: is the memtable-switch gate sufficient to exclude every other partition's leader from a memtable/WAL switch -- a leader enters it in PreprocessWrite() before binding a WAL and leaves it only when its group exits (including the parallel-follower and unordered_write exits), and a leader that must switch closes it from PreprocessWrite() before entering, so no leader ever waits on itself?

**Blocked decisions**

1. M0.8, route-then-group: already decided and implemented by D122869562; not reopened. Each writer carries the route resolved once in WriteImpl and joins the queue of that partition. Reversing it (group-then-route) would need WriteThread to release leadership between WAL selection and the append.
2. Memtable fork: **A, allow_concurrent_memtable_write.** N leaders insert into the same memtables, and A needs no new lock or lock ordering. It keeps unordered_write working (which requires A), and B's serialization cost does not need measuring because nothing is serialized. Its cost: wal_partitions > 1 requires a SkipList memtable, and enable_blob_direct_write cannot be combined with it (ColumnFamilyData::ValidateOptions already rejects blob direct write with concurrent memtable writes). Enforced at Open: wal_partitions > 1 with allow_concurrent_memtable_write=false is now NotSupported, and this check runs before the general wal_partitions > 1 rejection, so it is reachable and tested. Reversing to B: drop that Open check, give each leader a memtable-insert lock around its insert at N > 1 (and let single-writer groups insert serially again), and reject unordered_write at N > 1 instead.

**Why**

Routing (D122869562) decides which WAL a write binds to, but every writer still joins the one write_thread_, so writers to different partitions are still serialized behind one leader. D122660502's 36.8 ms join-wait tail is unrelieved. This diff makes N > 1 mean N concurrent leaders, each appending to its own WAL.

**Previous behavior**

One WriteThread write_thread_ and one nonmem_write_thread_. The per-partition containers were always sized 1: Open created partition 0's WAL only, and SwitchMemtable rotated partition 0 only. At N > 1 the default write path also read LastSequence() as its allocation, published with SetLastSequence() (which asserts monotonicity), and inserted single-writer groups with concurrent_memtable_writes=false -- all of which assume one leader.

**New behavior (only at N > 1, still unreachable outside tests)**

- One WriteThread and one nonmem WriteThread per partition (write_threads_/nonmem_write_threads_, sized with the other partition containers in the constructor). A writer joins its routed partition's queue, so each partition has its own newest_writer_ and leader. There is no cross-partition election.
- One log::Writer per partition: Open creates N WALs and SwitchMemtable rotates all N together, under all N WAL write mutexes. Partition 0 keeps the lowest number of each generation, so cur_wal_number_, memtable NextLogNumber and obsolescence keep their meaning.
- Sequence allocation stays inside each partition's leader critical section. The default (!two_write_queues) path allocates through AllocateSequenceAndWALIndex, the counter the WAL-index path and both two_write_queues queues already use, so sequences and wal_index stay unique across partitions and queues. The two-queue path still allocates under WalWriteMutex(p), which both queues of a partition share.
- Every leader inserts in concurrent mode (forced parallel path), because other partitions insert into the same memtables.
- Memtable-switch gate: PreprocessWrite()'s SwitchWAL / HandleWriteBufferManagerFlush / ScheduleFlushes close the gate and wait for leaders past it. Callers outside the write path (flush, SetOptions, CF create/drop, ingestion, LockWAL, ResumeImpl, ...) enter every partition's queue unbatched in ascending order (AllPartitionsWriter).
- Publication: PublishLastSequence() skips a publish a higher one already overtook (CAS-max), so LastSequence() never moves backwards. Publication order is not established here (see limitations).
- Stalls and delays act on the leader's own partition queue; UnlockWAL and WaitForPendingWrites cover every queue.

**Neuter checks at one partition (R5)**

NumWalPartitions() == 1 returns from all four gate functions immediately; `parallel` keeps `write_group.size > 1`; the allocator condition reduces to WALIndexEnabled; PublishLastSequence calls SetLastSequence; stats keep `concurrent = two_write_queues_`; the constructor's resize, Open's extra-WAL loop, SwitchMemtable's extra-WAL loops and its any-partition-non-empty loop are all empty; AllWalWriteMutexesLock in SwitchMemtable takes exactly WalWriteMutex(0); AllPartitionsWriter uses an inline writer for partition 0, with no allocation, i.e. the same single EnterUnbatched as before. The R2 assertion and its per-file tracker are debug-only.

Changes without a neuter: last_batch_group_size_ is now RelaxedAtomic (relaxed load/store); IsMainWriteThread replaces `&write_thread == &write_thread_` with one comparison at N=1; UnlockWAL keeps its stall counts in two size-1 vectors (a cold path); WriteToWAL/WriteGroupToWAL take a sequence_count used only by the debug assertion. None of these changes control flow or WAL bytes at N=1.

**Safety, compatibility, limitations**

- wal_partitions > 1 remains rejected at Open. Tests reach N > 1 only through the debug sync point DBImpl::ValidateOptions:AllowWalPartitions. Read-only and secondary instances always size to one partition. No public header changes.
- Deferred to follow-up diffs, as agreed, and unsafe at N > 1 until then: publication order (a reader can see sequence S before a lower sequence from another partition is inserted, much like unordered_write's visibility); enable_pipelined_write (per-WriteThread last_sequence_ allocation, ordered SetLastSequence); sync=true writes (one leader syncs every partition's files while other partitions append); WBWI ingestion (switches memtables inside a gated leader); Merge batches (still inserted non-concurrently because of max_successive_merges); cached_recoverable_state_ without two_write_queues; timed write delays now run per partition in parallel; WALIOStatusCheck resets partition 0's writer on non-paranoid errors. None of these configurations is rejected: the coordination they need belongs to the follow-ups.
- Durability watermark (07), completion gate (08) and multi-WAL recovery are out of scope. A crash at N > 1 can leave holes, and reopening an N > 1 DB is not supported.
- Adaptive yield is unchanged: WriteThread's AdaptationContexts are file-scope statics shared by every instance, so they already adapt to aggregate traffic rather than to one queue's 1/N share.

**Folded in from round 12 (D124911745)**
Merge batches and WBWI ingestion are no longer deferred; this replaces those two items under limitations. Every N>1 memtable insert is now concurrent-safe:
- Merge batches stay on the parallel insert path at N>1 (`assert(parallel || N==1)`). Rejecting `max_successive_merges>0` covers the only part of Merge that isn't concurrent-safe.
- `IngestWriteBatchWithIndex` is rejected at runtime in `WriteImpl` at N>1 (`assert(N==1)` in `IngestWBWIAsMemtable`).
- At N>1, Open rejects `max_successive_merges>0` and non-SkipList memtables. VectorRep passes the generic concurrent check, so only this new guard rejects it.
- Tests: `MergeBatchesInsertConcurrentlyAcrossPartitions`, `IngestWriteBatchWithIndexRejectedAtNPartitions`, `ConcurrentUnsafeConfigsRejectedAtOpen` (4 rejects + control), `N1ConcurrentUnsafeOptionsStillAccepted`.
- Neuters: revert the Merge guard -> the `parallel || N==1` assert aborts. Revert the WBWI check -> the `N==1` assert aborts. Revert the CF guards -> the vector_rep and merges cases open -> fail.

M1: Absorbs 14 entries: GC13 Q1 gate opt-in + `WalPartitionsTestingOptIn`, Q3 ingestion stall + test, Q4 asserts; GC15 Q6 import stall + test, Q7 asserts (AMB-10 comment line lives in D123701876; SilentAtN1 lives in D123551605).

M2 fold (2026-10-22, `M2-FoldTasks.md` + `M2-Amendment.md`): Absorbs (M2) GC06 Q2-Q5/Q8: option rejections, `WriteWithCallback` and OCC rejections, fixture, `UnindexedWalPartitionsAlwaysRejected`, `WalPartitionsUpperBound`, `ValidatePolicyAtNPartitions`, bypasses; GC10 Q1-Q4: recoverable-state cache, per-partition group size, WBM stall, `DelayWrite` arg, `WritePrepared` fixture and tests; GC11: a1 rejection (N>1 requires `track_and_verify_wals_in_manifest`), fixture tracking, `ReadOnlyAndSecondaryApplyPartitionChecks`; GC07 Q5/Q6: version_set assertions, `WriteRecoverableState` bump, `PublishAboveAllocatedAsserts`, `ConcurrentRecoverableStateCaching` rewrite. Exception X11 (GC11 tracking line in GC06's OCC test lands here).

Test Plan:
- Pinned-base gate: passed with one recorded discrepancy. HEAD was exactly 4b70127fb45f, `sl status` was clean, and `only(., public())` listed the 25 dispatched commits in the dispatched order. The base's own subject still carries `[Codex]` (prefix not stripped locally); the requester confirmed proceeding on the pinned hash. This diff is a new commit on top; nothing below it was amended.
- Required suites, default dev mode (ASan/UBSan): `buck2 test` of db_write_test, db_wal_test, write_batch_test, transaction_test, db_basic_test, plus db_options_test (validation changed): passed, 5,631 tests, 0 failures/timeouts/build failures. No existing test was modified.
- TSan (`@fbcode//mode/dev-tsan`), the five required suites: passed, 5,580 tests, 0 failures, no ThreadSanitizer reports. This includes the eight new N > 1 tests.
- R1, appends overlap: `DBWritePartitionTest.PartitionLeadersAppendConcurrently` (16 partitions; two_write_queues off and on, and with two queues also through the nonmem queue): every write holds its WAL append open until all of them are inside one, and all 16 of 16 appends were in flight at once. Neuter verified: routing every writer to partition 0's queue makes the maximum 1 and the test fails.
- R2, sequence order equals byte order per file: debug assertion `sequence > log_writer->last_sequence_consumed()` in WriteToWAL. `DBWritePartitionTest.SequenceOrderHoldsUnderConcurrentSwitches` runs 16 partitions with 16 writer threads x 200 writes (a quarter WAL-only with two queues), plus a thread issuing Flush(). db_write_buffer_size and max_total_wal_size are small, so leaders keep switching memtables and rotating all 16 WALs. The assertion held and every write reads back. Neuter verified: moving the two-queue sequence allocation outside WalWriteMutex(p) trips the assertion.
- Switch gate: `DBWritePartitionTest.SwitchWaitsForOtherPartitionsLeaders` holds one partition's append open and has another partition's leader schedule and run a memtable switch; the switch starts only after the open append completes. Neuter verified: with CloseMemTableSwitchGate() a no-op, the switch runs while the append is open and the test fails.
- R3: `DBWritePartitionTest.MemtableDecisionEnforcedAtOpen`: wal_partitions=4 with allow_concurrent_memtable_write=false is NotSupported naming that option, even with the test bypass of the general N > 1 rejection; with it true, Open sizes 4 partitions. The existing db_options_test still sees "wal_partitions > 1 is not supported yet" without the bypass.
- R5, byte-identical WAL at one partition: opt-mode db_bench built from 4b70127fb45f and from this diff; fillseq + fillrandom, 5,000 ops each, one thread, compression off, avoid_flush_during_shutdown. Run on the default path, enable_pipelined_write, and two_write_queues (via an options file; the OPTIONS files confirmed each setting). Base and new WALs were byte-identical in all three, `cmp` clean, sha256 913a88100f64e31e5faa17c0c5101fb0c838e6777096afa6845a210fbb22ffbb, 690,143 bytes.
- Blackbox crash test, dbg-mode db_stress rebuilt from this diff (asserts on), 600 s with a 60 s interval:
  - two_write_queues=0: 11 kill/reopen iterations, and the final verification and DB cleanup ran (the success path). The exit status was not captured because I killed its wrapper shell while restarting the other run; no error, assertion or traceback appears in the log.
  - two_write_queues=1 (with enable_blob_direct_write=0 and file_scope_wal_write_faults=0, because the crash script's sanitizer otherwise forces two queues off): 11 iterations, every one with --two_write_queues=1, exit 0.
- Formatting: the repo-pinned clang-format (/usr/local/bin/clang-format 21.1.2) via clang-format-diff.py over every changed range of the submitted state leaves no changes. `arc f` reports "No linters to run" for this subtree.
- `arc lint -a` on all nine files: no lint issues.
- Not run: whitebox crash test (not required). The comparison against D122660502's join-wait histogram: wal_partitions > 1 cannot be opened outside tests until the completion gate exists, so no db_bench configuration exercises N > 1. Crash/recovery at N > 1: unsupported until 08 and multi-WAL recovery. CMake/Make, macOS and Windows builds.

**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 154, Fail 0 (https://www.internalfb.com/intern/testinfra/testrun/32088147390513887).
- 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 gate at fold: `db_write_test` 88/0, options matrix 55/0. Tip suites 7870/0.
M1 re-verification (2026-10-20, after rebasing the stack onto master f0c3a35689fc and clang-formatting): per-diff gate at this diff passed (CI format check, `rocksdb_lib` build, touched test targets); tip suites 8126/0; N=1 byte identity equals T0.

M2 fold: new or moved tests here: UnindexedWalPartitionsAlwaysRejected, WalPartitionsUpperBound, ReadOnlyAndSecondaryApplyPartitionChecks, PublishAboveAllocatedAsserts, ValidatePolicyAtNPartitions, WritePreparedPartitionedWalTest.*. B.1 at this diff (format check, `rocksdb_lib`, touched test targets): PASS; db_write_test + optimistic_transaction_test + write_prepared_transaction_test 1019 pass.

Reviewers: #rocksdb, anand76, jewoongh, rbanerjee2

Subscribers: jewoongh, rbanerjee2

M3 fold: Absorbs
- GC12 Q1: GetCurrentWalFile refuses at N>1 (and the db.h doc); the checkpoint WAL inclusion bound is the newest current WAL over every partition (NewestAliveWalNumber); checkpoint quiesces every write queue until the open WAL sizes are read. GC12 Q8: ReadOnlyCompactedOpenAppliesPartitionChecks (AMB-M3-12). GC12: PreparedHeap::push/erase keep the heap sorted under out-of-order prepares, with PreparedHeap.BasicsTest (exception X4, AMB-M3-1: here rather than D123476301, because WritePrepared already runs at N>1 in this diff).
- GC14b Q2: ConcurrentPreparesAcrossPartitions enabled; fixture comment.
- GC08 Q4: WalContext::sync_failed_wal_number, the first WALIOStatusCheck argument in WriteImpl, SwitchMemtable failure attribution, TEST_WalRecoveryCutoff (exception X5: the leadership-sync attribution is hand-ported into this diff's inline sync loop; D123971668 re-extracts it). GC08 Q5 reset-and-continue assert, Q8 ConcurrentRecoverableStateCaching with 20 releases, Q9 AssertLastSequenceCoversAllocated, Q10 CreateMutex before the parallel memtable writers.
- GC14a Q6: checkpoint pins a LockWAL count when another thread holds LockWAL, and unlocks after the size read.
- GC17 Q4 constructor line (wal_empties_), Q6 (snapshots_version_ atomic, UpdateSnapshots never stores an older list, OlderSnapshotListNeverWins), Q3 MalformedBatchFailsAsAtN1.
Exceptions recorded: X1 (GC12's Q1 copy tests sit at D123928339), X4, X5.

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

Differential Revision: https://phabricator.intern.facebook.com/D123079329
fbsource-commit: 50fc07822290
Summary:
Does every N>1 completion advance the safe point only after its write() is durable, and can any scan miss an outstanding registration? If both hold, holes become suffixes.

With one WAL, "what is durable" is a single point and a torn tail is always a suffix. With N files failing independently, naive recovery replays everything present and a missing middle is invisible: the replica reports its high-water mark and is silently missing sequences forever. This diff builds the tracking and the watermark that convert holes into suffixes: per-partition outstanding ranges registered at allocation, a global frontier W = min(pending_low) with safe point W - 1 recomputed on the I/O-completion path at sync=false, exposed through a single `DBImpl::WalDurabilitySafePoint()` accessor. Nothing gates on it yet; the next diff consumes it.

The watermark lives in the tracker's own atomic, never in `last_published_sequence_`: ingestion and recovery legitimately jump the published sequence forward, while the watermark is a lower bound whose worth is that it cannot be overstated. No N>1 writer touches `last_published_sequence_`, `last_seq_same_as_publish_seq_` is unwidened, and the published ≤ allocated relationship is preserved. The design is a header-only `WalDurabilityTracker` with per-partition FIFOs (reserved up front, no hot-path allocation at typical depth 1-4), contiguous atomic `pending_low`/`durable_upto` arrays, and its own safe-point atomic. An idle partition contributes a sentinel infinity so the rescan is one min over one array with a single all-idle check falling back to max durable; tracking the minimum's owner lets a different partition's advance skip the rescan. Registration runs inside `AllocateSequenceAndWALIndex` under `sequence_wal_index_mutex_` (plus a small bracket on the no-index `ConcurrentWriteGroupToWAL` path), completion runs after `WriteToWAL` returns OK under the same mutex, and every registration is therefore ordered before any later scan. That mutex edge, not atomic orderings alone, closes the stale-registration window in which a scan misses an outstanding range and overstates durability with no symptom; the frontier arrays additionally use release stores on the completing writer and acquire loads on the scanner so observing an advanced frontier observes the WAL append that advanced it. Duplicate lows from WAL-only markers stamped without consuming are stored as separate entries, so the minimum does not advance past the shared value until every entry carrying it completes. Failed appends stay pinned per the burned-index rule (cover-sync popping and stalled partitions are later diffs). The N=1 default path registers nothing, so behavior, WAL bytes, and hot-path cost are unchanged at one partition.

R8 rejects `wal_partitions > 1 && seq_per_batch && two_write_queues` with `NotSupported` at `Open`. The gating expression was confirmed against `db_impl.cc` (`last_seq_same_as_publish_seq_ = !(seq_per_batch && two_write_queues)`) and `pessimistic_transaction_db.cc` (`use_seq_per_batch` covers both WritePrepared and WriteUnprepared): only the diverging combination is rejected, and WritePrepared without two queues keeps working through the `SetLastSequenceAtLeast` path the base already handles. A CAS-max cannot repair the N-queue publish case because `last_published_sequence_` is a contiguous settled prefix, not a high-water mark.

R5 contract audit (production callers of `SetLastPublishedSequence` at the base; readers unchanged and out of scope):
| file | disposition | sites |
| db/db_impl/db_impl.cc | adapted (tracker sizing only) | :533 WAL-error recovery, :7606 ingestion, :8389 Open pre-population: all mutex-held or Open-time, allocated-first, max-gated; none assumes finishing-writer |
| db/db_impl/db_impl.h | adapted (tracker member, accessor, Allocate signature) | `GetLastPublishedSequence` read boundary unchanged; no setter widening |
| db/db_impl/db_impl_open.cc | adapted (R8 rejection, recovery Allocate flag) | :2579 recovery catch-up, allocated-first, single-threaded |
| db/db_impl/db_impl_secondary.cc | unaffected | :553 secondary catch-up, allocated-first |
| db/db_impl/db_impl_write.cc | adapted (Register/Complete hooks, Allocate calls) | :3002 recoverable-state drain unchanged, holds all WAL mutexes, allocated-first |
| db/import_column_family_job.cc | unaffected | :237 ingestion jumps published forward allocated-first; the reason the watermark must not share the field |
| db/repair.cc | unaffected | :685 repair sets all three to max, single-threaded |
| db/version_set.h | unaffected | setter definition and published ≤ allocated assert untouched |
| utilities/transactions/write_prepared_txn_db.cc | unaffected | :73 recovery-time set, allocated-first |
| utilities/transactions/write_prepared_txn_db.h | unaffected | [F] :1043 MarkCommit, :1109 rollback callbacks assume single queue; guarded by two_write_queues and R8 rejects N>1 there, so the premise holds where they run |
| utilities/transactions/write_unprepared_txn_db.cc | unaffected | :191 rollback-recovery publish under two_write_queues (R8-gated at N>1), :332 recovery-time set |
| utilities/transactions/write_unprepared_txn_db.h | unaffected | [F] :86 commit callback, same single-queue premise and R8 gating as WritePrepared |
| outside the twelve | no extra writers | version_set.cc, version_edit_handler.cc, db_impl_compaction_flush.cc, db_impl_sync_and_async.h, write_prepared_txn.h, pessimistic_transaction_db.cc, write_unprepared_txn.{h,cc}, memtable.h, db_impl_debug.cc hold only reads, asserts, comments, or docs; no additional finishing-writer publish site |

**Folded in from round 12 (D124911745) and round 12.1 (D125113461)**
No N=1 write path touches the durability tracker (this used to cover only the default path):
- `Register`/`Complete` run only at N>1; at N=1 nothing reads the tracker. Test: `N1IndexedSkipsDurabilityTracker`: the safe point stays 0 while sequences advance. Neuter: revert the guards -> the safe point advances -> fail.
- `PipelinedWriteImpl` computes `track_durability = wal_index_enabled && NumWalPartitions() > 1` and passes it to both registration and completion. Before, pipelined writes with WAL indexing at N=1 registered with the tracker. New test accessors: `TEST_WalDurabilityPendingLow(p)` and `TEST_WalDurabilityDurableUpto(p)`.
- Test: `N1PipelinedAndTwoQueueWritesSkipTracker` (`/0` pipelined with indexing, `/1` two queues). Neuters: revert registration only -> all 11 appends see a pending range -> fail. Revert completion only -> the tracker's unpaired-completion assert aborts (debug builds only).

M1: Absorbs GC13 Q3 completion latency at `Complete` + GC15 Q4 tracker hook.

M2 fold (2026-10-22, `M2-FoldTasks.md` + `M2-Amendment.md`): Absorbs (M2) GC07 Q1/Q2: `applied_tracker_`, `WriteGroup::first_sequence`, `PublishLastSequence(range)`, `PublishAppliedPrefix` (without the waiter signal: X6); GC10's five stall/throttle tests and GC07's rate-test rewrite (exception X4: they call `IndexedWalOptions`), GC06 bypasses, GC11 tracking; GC07a (D127011765) Q2: a group whose WAL append succeeded but a later step failed before any insert (recording the sync in the MANIFEST) marks its range applied, so higher ranges and their completion gates cannot wait on it forever; GC07a Q4: the safe-point test hook applies only to the durability tracker. Exception X12: `IngestionThenWritesKeepLastSequenceMonotone` moved to D123551605.

Test Plan:
```
buck2 test fbcode//internal_repo_rocksdb/repo:db_write_test
```
https://www.internalfb.com/intern/testinfra/testrun/12103424203804062
Pass 79, Fail 0. Includes 7 new `WalDurabilityTrackerTest` unit tests (worked example reproducing safe point 1 exactly, all-idle max, out-of-order pinning, duplicates in both orders, cost, threaded) and 2 new `DBWritePartitionTest` end-to-end tests (watermark advance, R8 rejection) × 2 `two_write_queues` params. No existing test modified.
```
buck2 test fbcode//internal_repo_rocksdb/repo:db_wal_test
```
https://www.internalfb.com/intern/testinfra/testrun/25051272981484013
Pass 2031, Fail 0.
```
buck2 test fbcode//internal_repo_rocksdb/repo:transaction_test
```
https://www.internalfb.com/intern/testinfra/testrun/9851624390400585
Pass 3106, Fail 0.
```
buck2 test fbcode//internal_repo_rocksdb/repo:write_prepared_transaction_test
```
https://www.internalfb.com/intern/testinfra/testrun/33495522269942844
Pass 842, Fail 0.
```
buck2 test fbcode//internal_repo_rocksdb/repo:write_unprepared_transaction_test
```
https://www.internalfb.com/intern/testinfra/testrun/31806672409670672
Pass 176, Fail 0.
```
buck2 test fbcode//internal_repo_rocksdb/repo:db_basic_test
```
https://www.internalfb.com/intern/testinfra/testrun/30962247479537411
Pass 346, Fail 0.
```
buck2 test fbcode//internal_repo_rocksdb/repo:db_write_test -m tsan -- 'WalDurabilityTrackerTest'
```
https://www.internalfb.com/intern/testinfra/testrun/5629499933573750
Pass 7, Fail 0. Threaded test exercises the R2 release/acquire pairing across partitions with no mutex; TSan validates the pairing, while the stale-registration window is closed by the sequence-mutex edge argued in the Summary (TSan cannot catch a missed registration since it is not a data race).
```
buck2 test fbcode//internal_repo_rocksdb/repo:db_write_test -m tsan -- 'DBWritePartitionTest'
```
https://www.internalfb.com/intern/testinfra/testrun/34621422176778942
Pass 12, Fail 0.
```
buck2 test fbcode//internal_repo_rocksdb/repo:db_options_test -- 'WalPartitions'
```
https://www.internalfb.com/intern/testinfra/testrun/30680772502824677
Pass 2, Fail 0. Confirms `wal_partitions > 1` remains rejected at `Open` without the sync-point bypass.
Recompute cost at 16 partitions, measured with a -O2 standalone harness over the real header (g++ -O2, 500k `ForceRecalculate` iterations, 3 runs): 35.1, 30.5, 25.4 ns/op, all under the 100 ns budget. The in-repo `RecomputeCostAt16Partitions` check (5000 ns bound under dev+asan) is neuter: it guards against algorithmic regressions only, and the -O2 number above is the real evidence. All other new checks are non-neuter.
Formatting: repo-pinned clang-format `--dry-run --Werror` clean on all six touched files after `-i` (only new lines reformatted; base files were clean). `arc lint -a` on all six files: ok, no lint issues. `arc f`: no linters to run for this subtree (formatting covered by clang-format directly). Zero hunks under `include/rocksdb`: no public header changed.
Checks not run: none. Every required check above ran and passed.

**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 169, Fail 0 (https://www.internalfb.com/intern/testinfra/testrun/7036874807246014).
- 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 gate at fold: `rocksdb_lib` builds. Tip suites 7870/0.
M1 re-verification (2026-10-20, after rebasing the stack onto master f0c3a35689fc and clang-formatting): per-diff gate at this diff passed (CI format check, `rocksdb_lib` build, touched test targets); tip suites 8126/0; N=1 byte identity equals T0.

M2 fold: new or moved tests here: StallBegunOnOnePartitionHoldsOnAll, DelayChargesOwnPartitionsGroup, DelayedWriteRateHoldsAcrossPartitions, WriteBufferManagerStallWakesEveryLeader, WriteBufferManagerStallsEveryLeaderTogether. B.1 at this diff (format check, `rocksdb_lib`, touched test targets): PASS; db_write_test 119 pass.

Reviewers: #rocksdb, xbw, anand76, rbanerjee2

Subscribers: jewoongh, rbanerjee2, anand76

M3 fold: Absorbs GC12 Q3 (ingestion fails cleanly over a pinned failed append; a debug assertion that every partition is idle before the sequence jump) and IngestionFailsCleanlyOverPinnedFailedAppend with GC08's S2 edit (AMB-M3-11); GC08 Q6 WalDurabilityTracker::Release; GC14a Q5 RejectsSeqPerBatchTwoQueues as a TEST_F; GC17 Q4 per-partition tracker state padded to one cache line per partition. Exception X2 places GC12's other two ingestion tests at D123551605 and D123928339.

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

M4 fold: Absorbs
- GC20 Q3: a record that consumes no sequence registers and completes an empty range in both trackers; PublishAppliedPrefix completes [first, last] and the clamp becomes an assert (exception X4: hand-ported into PublishAppliedPrefix; D123701876 extracts PublishAppliedFrontierLocked, AMB-M4-11); tracker comments; tests ZeroCountEntryStaysBelowItsLow and CoverAppendSerializedWithFlushWAL (exception X7: uses IndexedWalOptions).
- GC25 Q1 (trackers): the AllocateSequenceAndWALIndex overload with leading_sequence_count, which registers a block's leading run as its own applied range (AMB-M4-20); every caller here passes 0, the sync group passes its async run from D123551605.
- 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_write_test); 129 tests, 0 failed.

Differential Revision: https://phabricator.intern.facebook.com/D123476301
fbsource-commit: 5b84a87a7fbb
…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.

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.

Reviewers: jkangs, rbanerjee2, jewoongh, #rocksdb

Subscribers: jewoongh, rbanerjee2

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).

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.

Differential Revision: https://phabricator.intern.facebook.com/D123551605
fbsource-commit: 00aba4703b34
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).

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 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.

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.

Differential Revision: https://phabricator.intern.facebook.com/D123701876
fbsource-commit: f0e61e43f769
…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).

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 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).

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.

Differential Revision: https://phabricator.intern.facebook.com/D123928339
fbsource-commit: f1ab84fee284
Summary:
**Question for the reviewer:** does each accessor grant exactly the operation its caller needs -- no mutable deque, no wider capability, no second selection path?

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

M1: re-extraction carries GC03/GC13 claim/filter/fan-out changes fused
during restack (verified T0-identical: SyncWalImpl, Claim*, MarkLogs*,
call sites, gate, fan-out); GC15 `note_synced` fused (recorded
placement, AMB-8). Absorbs GC15 `NonLeadershipSyncsAdvanceSyncedSize`
+ GC16 Q4 `SyncWalAdvancesOtherPartitionsSyncedSize`. Test-block order
adjusted to T0 (`LiveWalReads` + `WriteThread` block after the N>1 cut
tests). Gate: `db_write_test` 195/0 (4 new).
M1 re-verification (2026-10-20, after rebasing the stack onto master f0c3a35689fc and clang-formatting): per-diff gate at this diff passed (CI format check, `rocksdb_lib` build, touched test targets); tip suites 8126/0; N=1 byte identity equals T0.

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

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

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

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

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

Differential Revision: https://phabricator.intern.facebook.com/D123971668
fbsource-commit: bd008d210e82
…oracle

Summary:
M1 standalone S-C (S-GC15), carved from GC15 Q1-Q4 + Q8 plus GC16 Q5/Q6
(see those round summaries for question evidence):
- `utilities/latency_injection_fs.{h,cc}` + `latency_injection_fs_test.cc`
  and BUCK/CMake/Makefile/src.mk entries.
- `db_bench` latency flags, install block and counter print.
- `db/db_wal_oracle_test.cc` prefix oracle + self-tests, with the Q6 drop
  count and failure.
- `LeadershipSyncExcludesCoupledRotation` (needs the FS) and the GC03
  `SyncWAL`-horizon regression test `SyncWalClaimTimeHorizonExcludesCoupled-
  Rotation`, with the `latency_injection_fs.h` include.

Placed directly above D123971668 (depends on GC13's testing opt-in and
GC03's `TEST_WalSyncMarks` below).

M2 fold (2026-10-22, `M2-FoldTasks.md` + `M2-Amendment.md`): Absorbs (M2) GC11 Q1/Q3: oracle strict lower bound on by default, comments, tracking on (and in `latency_injection_fs_test`); GC10's `PostOpenManualFlushSyncsEveryPartition` (exception X5: needs the latency FS); GC07a (D127011765) Q3: each oracle cycle has a 300 s watchdog that aborts with the cycle's configuration instead of hanging.
M2 fix pass (2026-10-22): both neuter self-tests (`CatchesSafePointOffByOne`, `CatchesMergeStopOffByOne`) share a 400-cycle budget (`kSelfTestMaxCycles`, was 100 each). They stop at the first violation, so the budget only costs time when the oracle has gone blind. The merge-stop self-test missed once at 100 cycles at the M2 tip (thread interleaving is not controlled); its catches ranged over cycles 8 to 73.

Test Plan:
gate at placement: `db_wal_oracle_test` +
`latency_injection_fs_test` 13/0; new `db_write_test` tests 4/4;
`db_bench` builds. Tip suites pass.

M2 fold: new or moved tests here: PostOpenManualFlushSyncsEveryPartition. B.1 at this diff (format check, `rocksdb_lib`, touched test targets): PASS; db_wal_oracle_test + db_write_test + latency_injection_fs_test 267 pass.
M2 fix pass (2026-10-22): per-diff gate at this diff (format check, `rocksdb_lib`, db_wal_oracle_test + db_write_test + latency_injection_fs_test) 267/0. With the 400-cycle budget, `CatchesMergeStopOffByOne` caught the injection in 12/12 runs (cycles 8–65) and `CatchesSafePointOffByOne` in 4/4 (cycles 1–4). At the tip: oracle 1000 cycles strict PASS and with `ROCKSDB_WAL_ORACLE_CHECK_PUBLISHED=1` PASS (0 lower-bound holes, 0 published-but-lost).

M3 fold: Absorbs GC12 Q7: the oracle drops kStrictLowerBound and its lower-bound exclusion counting; the self-test CatchesLowerBoundWithoutSpans (it uses D123928339's StartWALFile:WriteSpan sync point).

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_wal_oracle_test + db_write_test + latency_injection_fs_test: 323 pass.

M4 fold: Absorbs
- GC18 Q10: GateSyncToleratesCoupledRotation replaces LeadershipSyncExcludesCoupledRotation (exception X1: uses latency_fs), as GC25 rewrote it; Q11: the oracle trigger kLeadershipSync becomes kGateSync.
- GC24 Q1: CatchesMergeStopOffByOne and CatchesLowerBoundWithoutSpans turn head floors off.
- 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_wal_oracle_test, db_write_test, latency_injection_fs_test, db_bench); 361 tests, 0 failed.

Differential Revision: https://phabricator.intern.facebook.com/D126533193
fbsource-commit: 302d9fdce382
Summary:
M1 standalone S-B (S-GC13), carved from GC13 Q2 (see that round summary
for question evidence):
- `db_crashtest.py`: N sweep over {1,2,8,16} plus both sanitize stages
  (N>1 admits indexed WALs only).
- `db_stress --sync_write_one_in` (flag and use) and `SetOptions`
  `max_successive_merges` at N>1.

Placed above S-C (no dependency; order follows the M1 plan).

M2 fold (2026-10-22, `M2-FoldTasks.md` + `M2-Amendment.md`): Absorbs (M2) GC06's and GC11's N=1 crashtest fallbacks (`track_and_verify_wals`, OCC serial validation, `file_scope_wal_write_faults`).

Test Plan:
`db_stress` builds at placement. Tip suites pass.

M2 fold: new or moved tests here: (none). B.1 at this diff (format check, `rocksdb_lib`, touched test targets): PASS; no test targets; `db_crashtest.py` compiles.

Reviewers: generatedunixname1864816080879669

M3 B.1 at this diff (clang-format 21.1.2 on its changed lines, make check-sources, debug librocksdb build; no test file touched): PASS.

M4 fold: Absorbs
- GC26 Q5(e): db_crashtest.py runs no secondary and no continuous verification at N>1 (code only; no crash test was run).
- 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_stress; no test binary touched).

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

Tags: skip_dr_passed
fbsource-commit: 776f516e542c
M1 standalone S-D (from GC16 Q1-Q3): reproducible WAL partition sweep
harness (`tools/partition_wal_sweep.py`) plus `db_bench --sync_write_one_in`
and `--wal_slow_partition`.

At-M1...

Summary:
M1 standalone S-D (from GC16 Q1-Q3): reproducible WAL partition sweep harness (`tools/partition_wal_sweep.py`) plus `db_bench --sync_write_one_in` and `--wal_slow_partition`. Carved from GC16 D126232422, which is abandoned at M1.

At-M1 corrections to the GC16 summary below (applied inline): (1) reproducibility: the second `--quick` run's medians moved up to -8.3% (write p99) and -21% (gate p99) from the first, not "~2% on every median"; (2) the N=1 to N=16 async gain at 50us for 1024B values is +92% (47075 to 90571 ops/s); +77% is the 100B row; (3) join p99 at N=16/mix reaches 350ms; the 192ms figure was N=8/5000us/mix/1024B.

[GC] GC16: the N sweep and the abandon trigger, measured reproducibly (G-53). Benchmark tooling only: a checked-in sweep script plus two new `db_bench` flags, with the Tasks:975 abandon trigger evaluated under D-G53 (A). Also closes the GC15 carry-over: G-50 evidence for the multi-partition `synced_size` advance (Q4), a regression test for GC03's claim-time `SyncWAL` horizon (Q5), proof that the oracle's crashes lose data (G-54, Q6), and the `CrashMidRotationUnderSkewRecoversPrefix` drop fix (N-7-4, Q7). Q4's test idea, Q5's test, Q6's drop check and the Q7 finding are ported from D126193958 (MuseCode) as the requirement allows; its oracle, hooks, `SyncWalImpl` advance, latency FileSystem, per-WAL flag and Q8 labelling are not.

Reviewer question: Can anyone rerun this sweep and get the same picture, and does the watermark wait trip the abandon trigger at N=8? Anyone can: one command reproduces the 435-run matrix below (plus `--quick` in ~100s), and a second `--quick` run matches the first within −8.3% write p99 / −21% gate p99 at worst (see header). The trigger does not fire: 0.0012 at the designated N=8 profile, 50x below the 0.10 threshold on every sync-containing cell.

Q1: `tools/partition_wal_sweep.py` takes a `db_bench` binary and an output directory and runs the Q2 matrix with 3 reps per cell, emitting `results.json` (one row per rep: config, rep index, seed, throughput, p50/p99/p99.9 write latency, every Q2 histogram, FS counters; plus median/min-max aggregates), `results.md` (human table), per-cell command lines and raw logs, and the environment (host, CPUs, storage, opt build mode, commit hash, FS wait mode and concurrency cap). Injected and uninjected cells render in separate tables and the trigger refuses uninjected input. Reproducibility: two `--quick` runs from this commit (18 runs each, tables below) agree within −8.3% write p99 / −21% gate p99 at worst; strict min-max containment fails narrowly on 7 of 18 checked medians (worst -2.2%) because 3-rep spreads are extremely tight, and with n=3 a fresh median lands outside the previous min-max half the time by chance alone, so the small relative deviation, not strict containment, is the reproducibility evidence.

First `--quick` table (medians; commit 9c7f9a9b5188, opt, 166x AMD EPYC-Genoa):

## Injected cells (median across reps)
       N    usage append_us     sync     size     slow    ops/s    us/op   wr_p50   wr_p99 wr_p99.9 gate_p50 gate_p99 join_p50 join_p99 fsync/wr  cap_med fanout_med
       1    knone      500      mix      100       -1     9213     1707     1660     4309     6014    0.000    0.000     1291     4254    0.024    0.000    0.000
       1    knone      500     none      100       -1    13884     1118     1321     1895     2886    0.000    0.000    989.5     1874    0.000    0.000    0.000
       1      idx      500      mix      100       -1     9126     1713     1644     4300     6172    0.000    0.000     1292     4250    0.024    0.000    0.000
       1      idx      500     none      100       -1    13908     1114     1318     1890     3625    0.000    0.000    987.3     1869    0.000    0.000    0.000
       8      idx      500      mix      100       -1     2024     7721    867.9    49064    74742    0.553     43.9    269.3    44354    0.267    0.000     8.00
       8      idx      500     none      100       -1    18247    866.2    820.4     1415     2716    0.558     41.8    597.6     1271    0.000    0.000    0.000

Second --quick table (medians):

## Injected cells (median across reps)
       N    usage append_us     sync     size     slow    ops/s    us/op   wr_p50   wr_p99 wr_p99.9 gate_p50 gate_p99 join_p50 join_p99 fsync/wr  cap_med fanout_med
       1    knone      500      mix      100       -1     9013     1729     1670     4323     6485    0.000    0.000     1306     4270    0.025    0.000    0.000
       1    knone      500     none      100       -1    13746     1118     1314     1890     2770    0.000    0.000    994.9     1868    0.000    0.000    0.000
       1      idx      500      mix      100       -1     8815     1796     1675     4393     8014    0.000    0.000     1333     4335    0.025    0.000    0.000
       1      idx      500     none      100       -1    13938     1120     1322     1891     2668    0.000    0.000    993.4     1871    0.000    0.000    0.000
       8      idx      500      mix      100       -1     2013     7755    867.4    49739    77800    0.554     44.0    309.6    44902    0.265    0.000     8.00
       8      idx      500     none      100       -1    17845    864.9    818.0     1298     1882    0.555     33.0    588.7     1267    0.000    0.000    0.000

Q2: matrix is N in {1 kNone, 1 indexed, 2, 4, 8, 16} x append latency {50, 200, 1000, 5000}us (sync = append, jitter = append/10, seeded per rep) x sync {none, mix 1-in-20 via `--sync_write_one_in`, all} x value sizes {100, 1024} x 3 reps, 32k writes per cell on 64 CFs fixed across N (per-WAL counters verify every partition is covered in every N>1 cell; 8 CFs covered only 6/8 partitions in a pilot, hence 64), plus the N=8 one-slow-partition cell (`--wal_slow_partition=7`, 10x, mirroring the trigger profile). Steady state is inherent (WAL append cost is constant; the benchmark loop excludes open/CF setup) and confirmed by tight 3-rep spreads (e.g., trigger cell ops/s 1385-1417). New code only: the two flags live next to GC15's latency flags; no D118371518 line is touched. Cells use default write buffers (single generation; the slow override's rotation re-apply is validated in a separate small-buffer pilot where a stability check keeps mid-rotation tails from being misread as generations). Readings, one per bullet: baseline: N=1 indexed is within ~5% of kNone on every cell (e.g., 1000/mix/1024: 5376 vs 5658 ops/s) and byte-identical per the check below, so the stack costs ~nothing at N=1 (pre-stack-base comparison at 217951834332: not run, needs a second opt build; covered by byte-identity plus indexed-vs-kNone instead). N/BDP sweep: partitioning helps async writes at every latency (none/1024B N=1 to N=16: +92% at 50us (1024B: 47075 to 90571 ops/s; +77% is the 100B row), +40% at 1000us, +34% at 5000us) and hurts sync-containing ones (mix/1024B at 1000us: 5658 to 905 ops/s, -84%; all: 2874 to 582, -80%), driven by sync fan-out, not the gate. Cap-hit rate at N=8: `cap_excluded` sum is 0 in every cell over 10k-20k groups each, so the group cap never binds at N>1 here (M0.4: no). Join-wait vs watermark-wait: join p99 exceeds gate p99 by 7x (none) to 650x (mix) at N=8 (mix/1000/1024: 61ms vs 0.09ms); queueing dwarfs the watermark wait in every cell. Sync barrier: fan-out median is exactly N; barrier p50/p99 at N=8/1000/1024 is 21/49ms (all) and 36/102ms (mix); fsyncs/write is 0.33 (all) and 0.27 (mix), rising to 0.48/0.44 at N=16. One slow partition: throughput -53% (1399 to 661 ops/s), write p99 +126% (74 to 167ms), gate p99 x108 (91us to 9868us); the straggler cost lands almost entirely in the gate wait. Contention at N=8: the single-partition WAL mutex is uncontended (p99 1us); the all-partition mutex is taken per sync write (21k takes at all, p99 4.3ms; 2.8k takes at mix, p99 21.6ms) while async barely takes it (9 takes), so cross-partition serialization is the sync path's lock cost. Highlight (1000us, mix, 1024B medians): N=1 kNone 5658 ops/s wr_p99 6497us; N=1 idx 5376/6570; N=2 3615/17241; N=4 2275/34590; N=8 1399/73761 gate_p99 90.9us; N=8 slow 661/166813 gate_p99 9868us; N=16 905/157617. Full 145-row table (medians; commit 9c7f9a9b5188, opt, 166x AMD EPYC-Genoa):

## Injected cells (median across reps)
       N    usage append_us     sync     size     slow    ops/s    us/op   wr_p50   wr_p99 wr_p99.9 gate_p50 gate_p99 join_p50 join_p99 fsync/wr  cap_med fanout_med
       1    knone       50      all      100       -1     6955     2144     1837     4392     9100    0.000    0.000     1768     4346    0.092    0.000    0.000
       1    knone       50      all     1024       -1     6764     2246     1870     4384     8360    0.000    0.000     1803     4364    0.094    0.000    0.000
       1    knone       50      mix      100       -1    19060    827.4    369.9     2867     4317    0.000    0.000    331.3     2710    0.025    0.000    0.000
       1    knone       50      mix     1024       -1    18416    851.3    467.6     2749     4569    0.000    0.000    340.8     2623    0.025    0.000    0.000
       1    knone       50     none      100       -1    52029    298.1    289.4    547.9    784.1    0.000    0.000    278.6    378.5    0.000    0.000    0.000
       1    knone       50     none     1024       -1    47075    328.7    304.2    799.5     2900    0.000    0.000    276.9    532.3    0.000    0.000    0.000
       1    knone      200      all      100       -1     5864     2555     2127     5104    11634    0.000    0.000     1842     4392    0.095    0.000    0.000
       1    knone      200      all     1024       -1     5186     2936     2819     6054    11152    0.000    0.000     2396     5488    0.099    0.000    0.000
       1    knone      200      mix      100       -1    13826     1133    783.6     2895     5909    0.000    0.000    751.0     2865    0.025    0.000    0.000
       1    knone      200      mix     1024       -1    13194     1195    793.7     3448     7385    0.000    0.000    752.8     2879    0.025    0.000    0.000
       1    knone      200     none      100       -1    26404    578.7    660.0    868.5     1621    0.000    0.000    638.1    865.8    0.000    0.000    0.000
       1    knone      200     none     1024       -1    25858    598.2    655.7    970.0     1732    0.000    0.000    634.7    866.4    0.000    0.000    0.000
       1    knone     1000      all      100       -1     2954     5049     4184     9834    12417    0.000    0.000     4060     9817    0.094    0.000    0.000
       1    knone     1000      all     1024       -1     2874     5215     4239     9844    13632    0.000    0.000     4110     9831    0.095    0.000    0.000
       1    knone     1000      mix      100       -1     5633     2723     2565     6513     9417    0.000    0.000     2453     6414    0.025    0.000    0.000
       1    knone     1000      mix     1024       -1     5658     2760     2569     6497     9424    0.000    0.000     2459     6410    0.025    0.000    0.000
       1    knone     1000     none      100       -1     7702     1997     2146     2887     3828    0.000    0.000     2079     2884    0.000    0.000    0.000
       1    knone     1000     none     1024       -1     7588     2026     2139     2887     3511    0.000    0.000     2070     2883    0.000    0.000    0.000
       1    knone     5000      all      100       -1      857    17711    13717    32780    45952    0.000    0.000    13352    32746    0.096    0.000    0.000
       1    knone     5000      all     1024       -1      843    17630    13599    32787    44333    0.000    0.000    13243    32759    0.097    0.000    0.000
       1    knone     5000      mix      100       -1     1441    10811    11403    27626    34000    0.000    0.000    11105    21824    0.026    0.000    0.000
       1    knone     5000      mix     1024       -1     1393    11108    11556    28820    48827    0.000    0.000    11254    21991    0.027    0.000    0.000
       1    knone     5000     none      100       -1     1636     9191    11013    13943    13996    0.000    0.000    10747    13166    0.000    0.000    0.000
       1    knone     5000     none     1024       -1     1646     9117    10908    13941    13996    0.000    0.000    10626    12602    0.000    0.000    0.000
       1      idx       50      all      100       -1     7064     2168     1846     4374     7920    0.000    0.000     1782     4350    0.092    0.000    0.000
       1      idx       50      all     1024       -1     6825     2220     1869     4366     6578    0.000    0.000     1804     4344    0.094    0.000    0.000
       1      idx       50      mix      100       -1    19277    816.4    373.6     2656     4279    0.000    0.000    336.5     2514    0.026    0.000    0.000
       1      idx       50      mix     1024       -1    18639    843.4    484.9     2757     4203    0.000    0.000    344.4     2595    0.025    0.000    0.000
       1      idx       50     none      100       -1    51514    301.2    291.4    566.0    937.9    0.000    0.000    277.6    379.2    0.000    0.000    0.000
       1      idx       50     none     1024       -1    49359    316.1    301.8    574.3     1231    0.000    0.000    275.8    490.9    0.000    0.000    0.000
       1      idx      200      all      100       -1     5825     2596     2343     4840     8014    0.000    0.000     1870     4387    0.095    0.000    0.000
       1      idx      200      all     1024       -1     5410     2795     2747     6311     8910    0.000    0.000     2441     6185    0.097    0.000    0.000
       1      idx      200      mix      100       -1    13807     1135    780.7     2881     4569    0.000    0.000    754.3     2862    0.025    0.000    0.000
       1      idx      200      mix     1024       -1    13350     1182    784.4     3069     5700    0.000    0.000    755.6     2874    0.025    0.000    0.000
       1      idx      200     none      100       -1    26815    582.8    659.9    968.4     2900    0.000    0.000    637.3    866.9    0.000    0.000    0.000
       1      idx      200     none     1024       -1    24464    637.1    667.5     1686     3922    0.000    0.000    638.3    869.8    0.000    0.000    0.000
       1      idx     1000      all      100       -1     2799     5308     4213    11187    20780    0.000    0.000     4079    10327    0.095    0.000    0.000
       1      idx     1000      all     1024       -1     2767     5391     4326     9893    13819    0.000    0.000     4175     9867    0.097    0.000    0.000
       1      idx     1000      mix      100       -1     5465     2811     2571     6542     9845    0.000    0.000     2439     6451    0.026    0.000    0.000
       1      idx     1000      mix     1024       -1     5376     2804     2564     6570    11266    0.000    0.000     2430     6459    0.026    0.000    0.000
       1      idx     1000     none      100       -1     7531     2009     2141     2890     4266    0.000    0.000     2070     2884    0.000    0.000    0.000
       1      idx     1000     none     1024       -1     7275     2080     2175     3272     6355    0.000    0.000     2106     2889    0.000    0.000    0.000
       1      idx     5000      all      100       -1      835    18449    22425    32826    45265    0.000    0.000    13761    32778    0.099    0.000    0.000
       1      idx     5000      all     1024       -1      849    17924    13812    32804    42208    0.000    0.000    13421    32778    0.097    0.000    0.000
       1      idx     5000      mix      100       -1     1474    10462    11192    25826    32667    0.000    0.000    10899    21554    0.025    0.000    0.000
       1      idx     5000      mix     1024       -1     1470    10612    11227    26240    32679    0.000    0.000    10926    21628    0.026    0.000    0.000
       1      idx     5000     none      100       -1     1713     8883    10730    13938    13996    0.000    0.000    10421    13000    0.000    0.000    0.000
       1      idx     5000     none     1024       -1     1685     9065    10878    13943    13999    0.000    0.000    10594    13533    0.000    0.000    0.000
       2      idx       50      all      100       -1     3173     5010     4817    10548    18717    0.500    0.990     4146     9837    0.157    0.000     2.00
       2      idx       50      all     1024       -1     3253     4881     4584     9844    13883    0.500    0.991     3990     9737    0.157    0.000     2.00
       2      idx       50      mix      100       -1     9613     1632    530.9     6555     9705    0.501    0.992    326.0     6348    0.072    0.000     2.00
       2      idx       50      mix     1024       -1     7238     2182    535.5    10814    13913    0.501    0.993    332.4     9763    0.072    0.000     2.00
       2      idx       50     none      100       -1    73703    212.3    196.4    378.1     1054    0.501    0.992    152.7    372.7    0.000    0.000    0.000
       2      idx       50     none     1024       -1    58770    233.9    219.8    759.8     2900    0.505    0.999    160.3    455.9    0.000    0.000    0.000
       2      idx      200      all      100       -1     3007     5295     5069    11021    15756    0.500    0.991     4350     9876    0.157    0.000     2.00
       2      idx      200      all     1024       -1     3507     4537     4482     8705    13672    0.500    0.991     3980     7920    0.157    0.000     2.00
       2      idx      200      mix      100       -1     5592     2831    856.8    13065    20918    0.501    0.993    708.3    11987    0.071    0.000     2.00
       2      idx      200      mix     1024       -1     5360     2944    863.0    13563    28000    0.501    0.993    720.6    12924    0.071    0.000     2.00
       2      idx      200     none      100       -1    36498    435.4    371.1    860.0     1660    0.501    0.991    335.0    842.5    0.000    0.000    0.000
       2      idx      200     none     1024       -1    35377    448.3    385.8    859.5     1900    0.501    0.991    339.0    845.5    0.000    0.000    0.000
       2      idx     1000      all      100       -1     1823     8740     9873    13967    21764    0.500    0.991     8830    13928    0.157    0.000     2.00
       2      idx     1000      all     1024       -1     1749     9091     9913    13974    21810    0.500    0.991     8879    13929    0.157    0.000     2.00
       2      idx     1000      mix      100       -1     3677     4298     2723    16638    21509    0.504    0.998     2381    13766    0.071    0.000     2.00
       2      idx     1000      mix     1024       -1     3615     4350     2742    17241    21887    0.506     5.06     2389    13746    0.071    0.000     2.00
       2      idx     1000     none      100       -1    10378     1528     1285     2862     3136    0.502    0.995     1169     2837    0.000    0.000    0.000
       2      idx     1000     none     1024       -1    10328     1538     1281     2865     3542    0.502    0.994     1168     2843    0.000    0.000    0.000
       2      idx     5000      all      100       -1      527    30190    33019    49746    68939    0.500    0.991    29637    49610    0.157    0.000     2.00
       2      idx     5000      all     1024       -1      524    30321    32999    49710    69078    0.500    0.991    29615    49566    0.157    0.000     2.00
       2      idx     5000      mix      100       -1      985    16047    12484    55452    73373    0.541    296.0    11359    48332    0.072    0.000     2.00
       2      idx     5000      mix     1024       -1      977    16107    12512    53021    73347    0.538    262.4    11407    48122    0.072    0.000     2.00
       2      idx     5000     none      100       -1     2271     6987     6264    13715    13983    0.508     46.0     5811    12824    0.000    0.000    0.000
       2      idx     5000     none     1024       -1     2236     7095     6344    13721    13989    0.508     53.5     5852    13541    0.000    0.000    0.000
       4      idx       50      all      100       -1     3132     5052     4757     9900    19523    0.501    0.991     3436     9757    0.220    0.000     4.00
       4      idx       50      all     1024       -1     2981     5328     5059    12450    19304    0.500    0.990     3752    10256    0.220    0.000     4.00
       4      idx       50      mix      100       -1     5206     2994    362.7    16734    21957    0.513     15.5    209.2    13481    0.146    0.000     4.00
       4      idx       50      mix     1024       -1     5116     3089    417.6    17175    21767    0.519     93.9    225.1    13734    0.147    0.000     4.00
       4      idx       50     none      100       -1    75704    206.7    197.1    375.7    531.4    0.503    0.995    145.0    363.1    0.000    0.000    0.000
       4      idx       50     none     1024       -1    72385    214.7    205.4    376.7     1335    0.504    0.997    147.2    366.4    0.000    0.000    0.000
       4      idx      200      all      100       -1     2557     6199     6379    13396    21463    0.500    0.991     4657    12400    0.219    0.000     4.00
       4      idx      200      all     1024       -1     2469     6413     6528    13829    21784    0.500    0.990     4721    12782    0.220    0.000     4.00
       4      idx      200      mix      100       -1     4487     3493    781.0    19880    26685    0.515     14.2    371.2    17212    0.145    0.000     4.00
       4      idx      200      mix     1024       -1     4341     3612    827.3    19957    26529    0.517     22.2    389.9    17764    0.145    0.000     4.00
       4      idx      200     none      100       -1    35151    449.1    416.6    864.5     1796    0.505    0.999    323.2    815.6    0.000    0.000    0.000
       4      idx      200     none     1024       -1    34343    461.6    431.4    866.4     3650    0.504    0.999    326.9    840.0    0.000    0.000    0.000
       4      idx     1000      all      100       -1     1297    12186    12349    25183    33000    0.500    0.991    10115    21877    0.219    0.000     4.00
       4      idx     1000      all     1024       -1     1264    12488    13023    25700    41225    0.500    0.990    10220    21925    0.219    0.000     4.00
       4      idx     1000      mix      100       -1     2255     6946     2644    34819    49792    0.540     65.4     1266    30316    0.149    0.000     4.00
       4      idx     1000      mix     1024       -1     2275     6908     2613    34590    55952    0.538     67.8     1270    30184    0.147    0.000     4.00
       4      idx     1000     none      100       -1     9766     1627     1516     2875     3800    0.522     35.1     1138     2839    0.000    0.000    0.000
       4      idx     1000     none     1024       -1     9644     1648     1559     2885     5866    0.523     66.5     1145     2851    0.000    0.000    0.000
       4      idx     5000      all      100       -1      378    41788    40944    75336   107477    0.500    0.991    33643    73855    0.218    0.000     4.00
       4      idx     5000      all     1024       -1      375    42333    41105    78277   108731    0.500    0.991    33890    74077    0.218    0.000     4.00
       4      idx     5000      mix      100       -1      631    24937    12239   136600   197826    0.590    373.8     6387   102624    0.151    0.000     4.00
       4      idx     5000      mix     1024       -1      626    24990    12237   129052   187297    0.584    369.4     6385   101482    0.152    0.000     4.00
       4      idx     5000     none      100       -1     2085     7609     6598    13854    13990    0.550    292.9     5628    12498    0.000    0.000    0.000
       4      idx     5000     none     1024       -1     2071     7654     6698    13858    13991    0.550    306.8     5648    12430    0.000    0.000    0.000
       8      idx       50      all      100       -1     2129     7442     7339    21040    41904    0.500    0.990     3655    18016    0.329    0.000     8.00
       8      idx       50      all     1024       -1     1991     7965     7726    20817    31412    0.500    0.990     3943    18174    0.330    0.000     8.00
       8      idx       50      mix      100       -1     3202     4871    225.7    31709    47000    0.531     21.8     69.8    29138    0.260    0.000     8.00
       8      idx       50      mix     1024       -1     3108     5067    233.7    32225    47820    0.531     27.8     74.5    30062    0.256    0.000     8.00
       8      idx       50     none      100       -1    82431    188.7    178.4    372.4    501.7    0.512     5.47    116.1    327.5    0.000    0.000    0.000
       8      idx       50     none     1024       -1    80988    195.0    185.6    374.4    568.9    0.513     6.83    117.6    343.0    0.000    0.000    0.000
       8      idx      200      all      100       -1     1729     9168     9338    21970    32715    0.500    0.991     5025    20367    0.330    0.000     8.00
       8      idx      200      all     1024       -1     1652     9603     9627    25015    34888    0.500    0.991     5143    20962    0.331    0.000     8.00
       8      idx      200      mix      100       -1     2694     5791    445.2    39174    53125    0.534     26.0    151.0    31635    0.259    0.000     8.00
       8      idx      200      mix     1024       -1     2614     5992    471.6    40379    49928    0.536     51.4    177.5    32085    0.256    0.000     8.00
       8      idx      200     none      100       -1    37460    422.0    379.5    851.2     1062    0.523     13.5    272.6    728.2    0.000    0.000    0.000
       8      idx      200     none     1024       -1    36931    426.4    393.3    851.3    869.3    0.522     12.4    271.5    741.5    0.000    0.000    0.000
       8      idx     1000      all      100       -1      857    18445    17511    47477    73571    0.500    0.990    10538    42973    0.330    0.000     8.00
       8      idx     1000      all     1024       -1      845    18738    17946    47829    72670    0.500    0.991    10756    42949    0.329    0.000     8.00
       8      idx     1000      mix      100       -1     1402    11165     1741    74393   108959    0.585     93.4    312.5    60059    0.276    0.000     8.00
       8      idx     1000      mix     1024       -1     1399    11114     1802    73761   109023    0.578     90.9    880.4    60966    0.270    0.000     8.00
       8      idx     1000      mix     1024        7      661    23760    11139   166812   244581    0.732     9867    870.7   108682    0.295    0.000     8.00
       8      idx     1000     none      100       -1     9843     1609     1451     2875     3650    0.598     98.5    994.0     2806    0.000    0.000    0.000
       8      idx     1000     none     1024       -1     9552     1655     1523     3025     5377    0.603    414.8    991.9     2828    0.000    0.000    0.000
       8      idx     5000      all      100       -1      250    63159    58084   159190   222173    0.500    0.990    35234   140991    0.330    0.000     8.00
       8      idx     5000      all     1024       -1      247    63715    58555   161949   232028    0.500    0.991    35455   144577    0.331    0.000     8.00
       8      idx     5000      mix      100       -1      410    38438     6810   289671   378652    0.643    494.2    889.1   197712    0.283    0.000     8.00
       8      idx     5000      mix     1024       -1      412    38123     7160   254511   372618    0.641    486.1     1900   191509    0.282    0.000     8.00
       8      idx     5000     none      100       -1     2075     7651     6478    13876    13991    0.658    395.1     4996    13349    0.000    0.000    0.000
       8      idx     5000     none     1024       -1     2074     7648     6445    13878    13991    0.658    408.6     5002    11790    0.000    0.000    0.000
      16      idx       50      all      100       -1     1491    10629    10610    31645    49569    0.500    0.990     1960    24014    0.484    0.000     16.0
      16      idx       50      all     1024       -1     1437    11010    10980    31891    48539    0.500    0.991     1993    25956    0.484    0.000     16.0
      16      idx       50      mix      100       -1     2130     7392    162.9    62961    78181    0.541     27.9    0.782    48548    0.405    0.000     16.0
      16      idx       50      mix     1024       -1     2007     7818    164.6    65696    98068    0.540     32.0    0.780    49673    0.404    0.000     16.0
      16      idx       50     none      100       -1    92287    169.7    159.3    366.9    379.8    0.527     11.3     44.4    249.1    0.000    0.000    0.000
      16      idx       50     none     1024       -1    90571    173.0    160.6    368.9    379.7    0.530     12.1     45.3    285.3    0.000    0.000    0.000
      16      idx      200      all      100       -1     1181    13431    13356    38860    63571    0.500    0.990     2991    30479    0.484    0.000     16.0
      16      idx      200      all     1024       -1      949    16720    15013    72363   118108    0.500    0.990     3108    48272    0.486    0.000     16.0
      16      idx      200      mix      100       -1     1778     8789    355.4    71340   105314    0.546     44.1    0.782    61541    0.409    0.000     16.0
      16      idx      200      mix     1024       -1     1727     9101    356.4    72268   104615    0.544     39.9    0.787    65150    0.407    0.000     16.0
      16      idx      200     none      100       -1    40927    385.7    353.6    837.2    869.8    0.551     19.1     85.8    573.0    0.000    0.000    0.000
      16      idx      200     none     1024       -1    40675    389.0    355.3    840.6    870.0    0.545     15.7     88.9    578.4    0.000    0.000    0.000
      16      idx     1000      all      100       -1      589    26867    26163    74241   108472    0.500    0.991     6078    64161    0.483    0.000     16.0
      16      idx     1000      all     1024       -1      582    27175    26211    74011   131818    0.500    0.991     6756    63614    0.481    0.000     16.0
      16      idx     1000      mix      100       -1      954    16309     1212   149831   231600    0.604     84.9    0.773   104478    0.439    0.000     16.0
      16      idx     1000      mix     1024       -1      905    17307     1216   157617   238930    0.603     90.3    0.776   108960    0.438    0.000     16.0
      16      idx     1000     none      100       -1    10625     1490     1224     2868     2900    0.693     78.3    170.1     2725    0.000    0.000    0.000
      16      idx     1000     none     1024       -1    10610     1491     1226     2866     2898    0.689     75.0    166.4     2724    0.000    0.000    0.000
      16      idx     5000      all      100       -1      171    92232    88833   246299   368560    0.500    0.990    22354   210692    0.482    0.000     16.0
      16      idx     5000      all     1024       -1      169    93424    89851   246061   368288    0.500    0.990    22052   212761    0.485    0.000     16.0
      16      idx     5000      mix      100       -1      278    55903     6118   533996   815050    0.660    517.5    0.751   348988    0.471    0.000     16.0
      16      idx     5000      mix     1024       -1      279    55956     6123   533486   817263    0.655    508.0    0.757   350460    0.468    0.000     16.0
      16      idx     5000     none      100       -1     2223     7125     6114    13834    13986    0.752    487.9    787.9    11836    0.000    0.000    0.000
      16      idx     5000     none     1024       -1     2205     7131     6109    13839    13986    0.754    485.5    743.3    11352    0.000    0.000    0.000

Q3: D-G53 = (A) share of the tail (Recommended; the choice cell is blank). Metric is p99(`rocksdb.wal.durability.wait.micros`) / p99(write) at N=8 per (latency, sync) cell; the designated profile is append=1000us, mix, 1024B (mid-range networked-WAL latency, realistic sync ratio, KB-scale values, per the doc's own example). Number: 0.0012. Verdict: DOES NOT FIRE. The verdict is robust: every sync-containing cell at N=8 is at most 0.0019 (5000us mix), 50x below threshold, and all-sync cells round to 0.0000 (writes serialize through the barrier, so the gate never waits). The highest ratio anywhere is 0.1371 at (1000us, none, 1024B), a no-sync extreme where the denominator has no barrier (write p99 3.0ms) while the gate tail reaches 415us consistently across reps (281/415/531us); the 100B sibling is 0.034. That cell is reported, not the verdict: the trigger refers to the realistic sync mix, but the none-mode tail's value-size sensitivity is flagged for GC17.

## Abandon trigger (D-G53 (A)) at N=8
append_us sync size gate_p99_us write_p99_us ratio
50 all 100 0.990 21040 0.0000
50 all 1024 0.990 20817 0.0000
50 mix 100 21.8 31709 0.0007
50 mix 1024 27.8 32225 0.0009
50 none 100 5.47 372.4 0.0147
50 none 1024 6.83 374.4 0.0183
200 all 100 0.991 21970 0.0000
200 all 1024 0.991 25015 0.0000
200 mix 100 26.0 39174 0.0007
200 mix 1024 51.4 40379 0.0013
200 none 100 13.5 851.2 0.0159
200 none 1024 12.4 851.3 0.0146
1000 all 100 0.990 47477 0.0000
1000 all 1024 0.991 47829 0.0000
1000 mix 100 93.4 74393 0.0013
1000 mix 1024 90.9 73761 0.0012
1000 none 100 98.5 2875 0.0343
1000 none 1024 414.8 3025 0.1371
5000 all 100 0.990 159190 0.0000
5000 all 1024 0.991 161949 0.0000
5000 mix 100 494.2 289671 0.0017
5000 mix 1024 486.1 254511 0.0019
5000 none 100 395.1 13876 0.0285
5000 none 1024 408.6 13878 0.0294

TRIGGER: ratio 0.0012 at N=8 append=1000us sync=mix size=1024B does not fire (threshold 0.10)

Q4: `SyncWalAdvancesOtherPartitionsSyncedSize` syncs both partitions, writes nothing more, then a sync write on partition 0 must record sum 0 on `WAL_SYNC_UNSYNCED_PARTITIONS`. Neuter (drop the `note_synced` in the `wal.number > up_to` branch; dropping the whole branch would still advance via the active-WAL path): fails with sum 1. Existing `NonLeadershipSyncsAdvanceSyncedSize` passes unmodified.

Q5: `SyncWalClaimTimeHorizonExcludesCoupledRotation` holds a manual `SyncWAL` in its fsync loop with 100ms slow syncs, lands a coupled rotation inside (counter-observed, order proven by `DBImpl::SyncWAL:Begin` < switch < `DBImpl::SyncWAL:BeforeMarkLogsSynced:1`), writes into the rotated-in WALs, and requires a later sync write to count all 4 partitions unsynced, with marks clear and deques consistent. Neuter (finish-time horizon): aborts on `assert(wal.IsSyncing())` on the unmarked rotated-in WAL.

Q6: the oracle records per power-loss cycle whether an acknowledged write is absent after recovery, prints the count in the summary line, and `RecoveredStateIsPrefixOfHistory` fails when power-loss cycles ran but none lost a write (runs with zero power-loss cycles, i.e. single-cycle reruns of process-crash seeds, are exempt: nothing to prove). 1000-cycle run from this commit: pass, 313 of 528 power-loss cycles lost a write. Neuter (crash keeps unsynced data): 40-cycle run fails with "power loss lost an acknowledged write in 0".

Q7: `CrashMidRotationUnderSkewRecoversPrefix` now sets `SetInjectUnsyncedDataLoss(true)` before the open (files capture the flag at creation) and requires `missing_seen` past the last sync. Neuter (flag off again): fails on "the crash dropped no acknowledged write". Listed under Invariant 4 as the one modified test.

GC17 pointers (numbers only, no decisions): D-G11: mean unsynced partitions under the mix is 1.3-2.3 of 8 (well below N) and the barrier dominates sync-write p99 (barrier p99 102ms over 1321 sync groups vs write p99 74ms over 32k mixed writes at N=8/1000/mix/1024; different populations, noted). G-19a: writers/group p50 is 1-2.4 while join p99 reaches 350ms at N=16/mix (191.5ms is N=8/5000us/mix/1024B); the index-allocation mutex has no dedicated histogram, so the harness bounds group-formation queueing but does not isolate the allocator. muse #22: per-partition mutex waits are ~0 at all N (p99 1us); no contention signature that padding would relieve in these workloads. N-2-6: 0.27-0.48 fsyncs/write sit on the write path at N=8-16 sync workloads; a background fsync's prize is bounded by the barrier numbers above minus the all-mutex claim, which stays.

Fold-back split: Q1-Q3 (script + `--sync_write_one_in` + `--wal_slow_partition` in `tools/db_bench_tool.cc`) stays a standalone diff (new code; no D118371518 line touched; no D-G53 (B) bypass). Q4 test folds with GC15's `NonLeadershipSyncsAdvanceSyncedSize` (D123971668, or D123551605). Q5 test to GC15's standalone diff (needs the latency FS). Q6 (oracle drop count + failure) to GC15's standalone diff. Q7 (test change) to D123928339. No hunk is unplaceable at its target.

Assumptions: D-G53 blank, so Recommended (A) per AB section 4 rule 2. Trigger profile (1000us append, mix 1-in-20, 1024B) chosen per rule 5 (mid-range networked-WAL latency, realistic sync ratio, KB-scale values; every cell tabulated so the choice is auditable). Sync latency = append latency and jitter = append/10 per rule 5 (one profile knob; seeded jitter keeps reps reproducible). 64 fixed CFs per rule 5 (isolates N; coverage verified from per-WAL counters). Cells use default write buffers (single generation; rotation re-apply validated in a separate small-buffer pilot) per rule 5 (cleanest numbers). Q4 neuter removes the `note_synced` call rather than the whole branch per rule 5 (the literal branch drop still advances via the active path and would not fail). Q6 exempts runs with zero power-loss cycles per rule 5 (single-cycle reruns must stay green). Cap-hit rate is reported as mean excluded/group plus P99 (ToString exposes no non-zero fraction) per rule 5.

Not done: (empty).

M2 fold (2026-10-22, `M2-FoldTasks.md` + `M2-Amendment.md`): Absorbs (M2) GC10 Q8/Q9: `SlowWalPartitionFileSystem`, sweep comparisons, steady state, `--compare_to`, trigger table; GC07 Q9: sweep dedup and N=1 baselines. This diff now edits S-C's db_bench lines: it moves S-C's latency-FS install block below its own slow-partition validation.

Test Plan:
- `buck2 test fbcode//internal_repo_rocksdb/repo:db_write_test fbcode//internal_repo_rocksdb/repo:latency_injection_fs_test`: 199 pass, 0 fail.
- `buck2 test fbcode//internal_repo_rocksdb/repo:db_wal_oracle_test` (40 cycles): 3 pass; drop count 13/17 power-loss cycles.
- 1000-cycle oracle run from this commit (`ROCKSDB_WAL_ORACLE_CYCLES=1000`): pass; 313 of 528 power-loss cycles lost a write; 2 known lower-bound holes (non-strict, expected). A pre-format run gave 310/528; the committed run above is the evidence.
- Q5+Q7 x100 repeats (`--gtest_repeat=100`): 100/100 iterations pass, 0 failures.
- Q5+Q7 under `@fbcode//mode/dev-tsan`: 4 pass, no TSan warnings.
- Q4 neuter (no `note_synced` past the horizon): `SyncWalAdvancesOtherPartitionsSyncedSize` fails with sum 1 (expected). Q5 neuter (finish-time horizon): aborts on `assert(wal.IsSyncing())` (expected). Q6 neuter (crash keeps unsynced data): 40-cycle run fails "no power-loss cycle lost an acknowledged write" with count 0 (expected). Q7 neuter (flag off): fails "the crash dropped no acknowledged write" (expected). All neuters reverted; `db_impl.cc` clean.
- Full matrix: 435/435 runs ok from this commit (opt `db_bench`); trigger verdict DOES NOT FIRE (0.0012 at N=8/1000us/mix/1024B; max 0.0019 on any sync-containing cell).
- Two `--quick` runs from this commit: 18/18 each; second run's medians within −8.3% write p99 / −21% gate p99 of the first at worst (7 of 18 narrowly outside the tight 3-rep min-max; worst -2.2%); tables in summary.
- N=1 byte-identity check (base vs this commit, `none` and `partition_by_column_family`): pass; hashes equal the documented values (`6d135111...` off, `9a69a3fc...` on).
- 180s `db_stress` blackbox crash test at N=1 with `partition_wal_usage` on: first run failed early (checkpoint "WAL index merge: WAL 3 unreadable" under injected read faults), retry passed ("Crash-recovery verification passed"). Engine code is untouched by this diff (benchmark tooling + tests only), so the intermittent failure is a pre-existing base finding, reported, not fixed.
- Pre-stack-base N=1 comparison at 217951834332: not run (needs a second opt build; covered by byte-identity plus N=1 indexed-vs-kNone instead).
- Repo-pinned clang-format clean on all touched C++ files; `arc lint -a` and the script's lint clean.

(M1 standalone carved from GC16 D126232422; that round diff is abandoned at M1.)

M1 re-verification (2026-10-20, after rebasing the stack onto master f0c3a35689fc and clang-formatting D117251769, D117251771, D123079329, D123551605):
- Per-diff gate, all 35 commits bottom-up: CI format check, `rocksdb_lib` build, every touched test target: all pass, 0 failures.
- Tip suites (23 targets): 8126 pass, 0 fail.
- N=1 byte identity at the tip: `6d135111...` (off) and `9a69a3fc...` (on), equal to T0.
- 180s blackbox crash test at N=1 with `partition_wal_usage=partition_by_column_family`: pass.
- Trigger rerun, opt `db_bench`, N=8/1000us/1024B, this harness: sync mix 0.0014 / 0.0013 / 0.0011 at 8 / 16 / 32 threads; all-async 0.026 / 0.025 / 0.018. Does not fire in either profile (the earlier 0.137 and dev-mode 0.108 readings do not reproduce in opt).

M2 fold: new or moved tests here: (none). B.1 at this diff (format check, `rocksdb_lib`, touched test targets): PASS; no test targets; `db_bench` and `db_stress` build; `partition_wal_sweep.py` compiles.

M3 B.1 at this diff (clang-format 21.1.2 on its changed lines, make check-sources, debug librocksdb build; no test file touched): PASS.

Differential Revision: https://phabricator.intern.facebook.com/D126533195
fbsource-commit: 496c3dc34993
Summary:
Every WAL consumer outside recovery either reads the partitioned WALs correctly or refuses them before reading or changing anything (README "Final stack layout" row 33). This is what remains of GC12 after M3: GC12's other answers folded into the diffs that own the code they change.

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

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

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

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

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

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

Differential Revision: https://phabricator.intern.facebook.com/D127093323
fbsource-commit: 01ebc084d2ed
Summary:
Runs every WAL consumer and transaction suite at N=8 as well as N=1 (README "Final stack layout" row 37). Tests only.

- test::SetWalPartitions and test::WalPartitionsForCurrentTest (test_util/testharness.{h,cc}) with one-line fixture hooks; DBTestBase skips, at N>1 only, the option configurations Open rejects there.
- WalPartitions8 instantiations (or N in {1,8} conversions) for the secondary, repair, external SST (both suites), WalManager, ldb, backup, checkpoint, transaction, optimistic, WritePrepared and WriteUnprepared suites. N=1 instances assert what they asserted before.
- Shared helpers in db/db_test_util.{h,cc}: ColumnFamilyIdsCoveringWalPartitions, ColumnFamilyNamesThrough, PartitionWriters, AssertKeyPrefixesInEveryRecoveryMode, RunWithin.
- GC14b's Q3, Q4 and Q5 tests: the PreparedHeap top moving backwards, WriteUnprepared crash-image recovery across partitions, checkpoint and backup alongside LockWAL.

GC14b's Q2 edits (enabling ConcurrentPreparesAcrossPartitions) folded into D123079329 at M3.

M3 fold: Absorbs GC14a Q6/Q7 (re-enables CheckpointRacingLockWAL at N=8 and removes both G-14 skips; GC14a's checkpoint fix and GC08's Release and recovery fixes now sit below) and GC17 Q6 (re-enables CommitOfDelayedPrepared at N=8, over GC17's snapshots_version_ fix in D123079329).

M3 B.1 at this diff (clang-format 21.1.2 on its changed lines, make check-sources, debug build, touched test binaries): PASS; backup_engine_test + checkpoint_test + db_secondary_test + external_sst_file_basic_test + external_sst_file_test + ldb_cmd_test + optimistic_transaction_test + repair_test + transaction_test + wal_manager_test + write_prepared_transaction_test + write_unprepared_transaction_test: 5533 pass.

M4 fold: Absorbs
- GC18 Q6 (TwoPhaseCommitSpanningPartitionsRecoversAtomically and its write_prepared_txn_db.h friend line) and Q7 (BackupWithoutFlushRacingLockWAL); Q9's AsyncOnSyncingPartitionWaitsForItsFsync (exception X1: uses RunWithin, AMB-M4-10).
- GC20 Q5's test as GC25 rewrote it, FailedGateSyncFailsWritesAbove (exception X7).
- GC22: the M-b repro FU14CatchUpRefusesBeforeApplyingPartitionZero (exception X15: test::SetWalPartitions).
- GC23 Q9: GC23TimestampedSnapshotsSurviveFlushStress (with the test hook, exception X14).
- Net-zero pairs dropped (rule 2.7): 1: GC18 Q9's AsyncAboveSyncReturnsWhileSyncFsyncHeld cancels with GC25's removal.

M4 B.1: PASS (clang-format 21.1.2 on the changed lines, make check-sources, debug build of backup_engine_test, checkpoint_test, db_secondary_test, db_write_test, external_sst_file_basic_test, external_sst_file_test, ldb_cmd_test, optimistic_transaction_test, repair_test, transaction_test, wal_manager_test, write_prepared_transaction_test, write_unprepared_transaction_test, ldb); 5930 tests, 0 failed.

Differential Revision: https://phabricator.intern.facebook.com/D127275775
fbsource-commit: db6612fbcbee
Summary:
N>1 coverage for every recovery mode, partition-count changes, MANIFEST tracking, merge buffers and FlushWAL/LockWAL, plus a checked-in N=1 byte-identity vehicle (README "Final stack layout" row 36). Tests and a script only. This is what remains of GC14a after M3: its Q6 checkpoint fix folded into D123079329, its Q4 doc into D117251769, its Q5 test edits into D123476301 and D123928339, and its Q6/Q7 skip removals into D127275775.

- DBWalPartitionCoverageTest (derived from DBWritePartitionTest, two_write_queues=false), 10 tests: TornTailsInSeveralPartitionsPerMode, MissingMidChainWalPerMode, TwoPhaseCommitAcrossPartitionsRecoversWhole, DisableWalAndIngestionGapsDoNotTruncate, ReopenAtAnotherPartitionCountKeepsEveryKey, ReopenOneFourOneKeepsEveryKey, ManifestTracksEveryPartitionsWalsUnderSkew, ForcedGroupsOnEveryPartitionAreByteExact, FlushWalSyncsEveryPartitionsAckedWrites, LockWalHoldsEveryPartitionUnderWrites. Each crash-image cell either opens with exactly the expected prefix or fails with the status the stack implements, in every WALRecoveryMode.
- tools/check_wal_byte_identity.sh DB_BENCH_A DB_BENCH_B: compares the WAL bytes two db_bench builds write for a fixed single-threaded workload at partition_wal_usage=none, indexed with one partition, and four partitions; prints MATCH or MISMATCH per configuration.

Sits above D127275775 (it uses PartitionWriters and RunWithin) and D127093323 (CopyDBAsCrashImage).

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

M4 fold: Absorbs
- Every DBWalPartitionCoverageTest test and helper of GC19, GC23, GC24 and GC26 (exception X12): the H3-H6 repros; GC19's Q1/Q3/Q4 tests; GC23's CreateBrandNewPartitionedDb, CorruptImageRecord and floor and void tests; GC24's lost-current-WAL and skipped-hole tests; GC26's skip cells, DBWalPrepareAcrossChangeTest and its three tests, the D-10 skip tests and the ported GC24HistoryFloorScopeOnUpgrade.
- Exception X14: the tests written after GC18 that open N>1 here (GC19TornFirstRecordInBrandNewNTwoDbModes, CreateBrandNewPartitionedDb, GC23FloorOffForLaterGenerationHeads, GC24HistoryFloorScopeOnUpgrade) carry the test hook; the flip removes it.
- 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_write_test); 402 tests, 0 failed.
…n builds

The flip of the PartitionWAL stack (GC18 Q1-Q5). DB::Open accepts
wal_partitions > 1 with an indexing partition_wal_usage in release and
debug builds, with no sync point and no opt-in. kNone with N>1 and every
other M1.4 rejection still fail with their exact Status. The
wal_partitions doc and the release notes describe the shipped behaviour
and the rollout order (readers first).

Removes:
- the N>1 gate in DBImpl::ValidateOptions and its debug sync point
  DBImpl::ValidateOptions:AllowWalPartitions;
- the GC13 opt-in experimental_allow_wal_partitions_for_testing
  (D-G18k (i)): the option, its OPTIONS-map entry, Dump line, generated C
  accessors and allowlist entries; db_bench, db_stress and
  test::SetWalPartitions stop setting it;
- every use of the hook in tests and tools, including the hooks that
  tests folded below this commit carry at M4 (exception X14:
  FailedSyncPrepareLeavesNoStaleFence, GC23TimestampedSnapshotsSurviveFlushStress,
  GC19TornFirstRecordInBrandNewNTwoDbModes, CreateBrandNewPartitionedDb,
  GC23FloorOffForLaterGenerationHeads, GC24HistoryFloorScopeOnUpgrade) and
  the original hooks of SyncPrepareAfterSyncCommitSurvivesCrash,
  FU14SnapshotRace and FU14H6TornFirstRecordInBrandNewNTwoDb (GC26 Q5(d)).

Adds db_wal_partitions_open_test (GC18 Q1, with GC20 Q9's edits), GC20
Q9's "with indexing it opens" leg of WalPartitionsValidation (exception
X6), GC23 Q8's wal_partitions doc sentences (exception X6), and the
release notes unreleased_history/new_features/wal_partitions.md,
behavior_changes/partition_wal_sync_visibility.md (GC25) and
behavior_changes/partition_wal_recovery_modes.md (GC26) (exception X19:
they describe behaviour production builds reach only from this commit).

Recorded exception: this commit stays a standalone diff on top of the
stack and is never folded (GC18 round decision, design audit G3-C-2), so it
can be reviewed, landed and reverted alone, and N>1 never becomes legal
partway up the stack.

M4 B.1: PASS (clang-format 21.1.2 on the changed lines, make check-sources, debug build of db_options_test, db_wal_oracle_test, db_wal_partitions_open_test, db_write_test, latency_injection_fs_test, ldb_cmd_test, optimistic_transaction_test, options_settable_test, transaction_test, write_prepared_transaction_test, db_stress, db_bench, ldb); 4974 tests, 0 failed.
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
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 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 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