Skip to content

[GC] GC14b: Every WAL consumer and transaction suite runs at N in {1,8} - #2

Closed
JustinGaoF wants to merge 1 commit into
pwal/gc12from
pwal/gc14b
Closed

JustinGaoF wants to merge 1 commit into
pwal/gc12from
pwal/gc14b

Conversation

@JustinGaoF

Copy link
Copy Markdown
Owner

[GC] GC14b: Every WAL consumer and transaction suite runs at N in {1,8}

Summary:
[GC] GC14b

Reviewer question: Does every consumer and transaction suite now run at N=8, and does each N=8 assertion match what GC12 settled?

Closes G-56 and GC12's carry-over Q2-Q5. Tests only: no production file changes (sl diff -r 01ebc084d2ed --stat lists only *_test.cc, transaction_test.h, db_test_util.{h,cc} and test_util/testharness.{h,cc}).

Why

  • M3 ("N>1 production-testable") needs every WAL consumer and transaction suite to run at N>1. At the base, none of the twelve suites mentioned wal_partitions, so a regression in checkpoint, backup, ingestion or transactions at N>1 would land unseen.
  • GC12 left four weak spots untested: GC10's concurrent-prepares test was still disabled; PreparedHeap::top() moving backwards; WriteUnprepared across partitions; checkpoint/backup alongside LockWAL.

Previous behavior

  • Every one of the twelve suites ran at N=1 only. GC12's outcomes (secondary and repair refuse, GetUpdatesSince refuses, ldb dump_wal labels partitions, the checkpoint quiesce) were pinned only by GC12's own targeted tests.
  • WritePreparedPartitionedWalTest.DISABLED_ConcurrentPreparesAcrossPartitions was disabled, and its comment still said the heap defect was unfixed.

New behavior

  • Each suite has a WalPartitions8 instance (or an N in {1,8} test asserting GC12's refusal), driven by one helper. The N=1 instances are unchanged.
  • GC10's test is enabled. New tests pin Q3 (heap top moving backwards; prepare below max_evicted_seq), Q4 (WriteUnprepared crash-image recovery across partitions) and Q5 (checkpoint and backup alongside LockWAL).
  • Two N>1 bugs were found and not fixed (invariant 5): a G-30 residual (checkpoint racing UnlockWAL) and a new WritePrepared race. The G-14 hang (GC08) was also hit; it is not in this base.

Implementation

  • test_util/testharness.{h,cc}:
    • test::SetWalPartitions(options, n) sets wal_partitions plus what Open needs for n>1: indexing (kPartitionByColumnFamily if kNone), track_and_verify_wals_in_manifest, recycle_log_file_num=0, and experimental_allow_wal_partitions_for_testing. It uses no sync point, so it is the same open path an opt build takes. It does nothing for n=1.
    • test::WalPartitionsForCurrentTest() returns 8 when the running test belongs to an instantiation named WalPartitions8, else 1. Fixtures call it while being constructed, so no parameter tuple had to be widened.
  • One-line hooks: DBTestBase::GetOptions (secondary, repair, both external_sst suites, CommitBypassMemtableTest), TransactionTestBase (transaction, WritePrepared, WriteUnprepared), OptimisticTransactionTest, CheckpointTestBase::CurrentOptions, BackupEngineTestBase's constructor, WalManagerTest::RollTheLog (spreads its WAL files over partitions with markers).
  • Existing TEST_P suites got one INSTANTIATE_TEST_CASE_P(WalPartitions8, ...) each, restricted to the parameters N>1 accepts. TEST_F suites had their WAL-relevant tests turned into TEST_P on a parameterized fixture (CheckpointTest, BackupEngineTest, WalManagerTest) or a thin subclass (ExternalSSTFileTestN, ExternalSSTFileBasicTestN), instantiated as WalPartitions1 and WalPartitions8. N=1 instances assert exactly what they asserted before (their names gain the WalPartitions1/ prefix).
  • DBTestBase::ShouldSkipOptions skips, at N>1 only, the option configurations Open rejects there (hash-skiplist, hash-linklist and vector memtables, pipelined, two queues, unordered).
  • Shared test helpers in db_test_util.{h,cc}: ColumnFamilyIdsCoveringWalPartitions, ColumnFamilyNamesThrough, PartitionWriters (one writer per partition, acked counts), AssertKeyPrefixesInEveryRecoveryMode (opens a copy read-only in all four WALRecoveryModes and checks per-writer prefixes), and RunWithin (30 s bound; aborts on a hang).

This is better than widening parameter tuples (hundreds of std::get<> edits in the transaction suites) or adding test targets (BUCK is generated), and it keeps one mechanism for all twelve suites.

Answers

Q1 - the twelve suites at N in {1,8}. [G-56]

  • Property: every listed suite has an N=8 instance; each N=8 test passes or asserts GC12's (or the Open gate's) outcome; N=1 is unchanged.
  • Counts, from a full single-process-per-test pass of every test at the final tree (see Test Plan):
Suite N=1 pass / skip / disabled N>1 pass / skip / disabled N>1 skip reasons
checkpoint_test 60 / 0 / 0 50 / 1 / 0 G-30 residual
backup_engine_test 110 / 0 / 0 66 / 0 / 0
wal_manager_test 8 / 0 / 0 4 / 0 / 0
db_secondary_test 73 / 0 / 2 1 / 0 / 0 suite refused at N>1 (GC12)
repair_test 19 / 0 / 0 1 / 0 / 0 suite refused at N>1 (GC12)
ldb_cmd_test 20 / 0 / 0 1 / 0 / 0
external_sst_file_test 224 / 0 / 4 109 / 0 / 0
external_sst_file_basic_test 42 / 2 / 0 37 / 2 / 0 the same 2 upstream skips as N=1
transaction_test 2843 / 265 / 31 281 / 37 / 3 12 listed below; 25 policy bypasses that also fire at N=1
write_prepared_transaction_test 851 / 9 / 0 67 / 2 / 0 G-14; new snapshots_version_ race
write_unprepared_transaction_test 184 / 0 / 0 62 / 4 / 0 G-14
optimistic_transaction_test 72 / 0 / 0 35 / 0 / 0

N>1 counts the WalPartitions8 instances plus the N=4 partitioned fixtures (WritePreparedPartitionedWalTest, WriteUnpreparedPartitionedWalTest). Disabled tests are upstream DISABLED_ tests.

  • A temporary, env-gated trace in DBImpl::ValidateOptions (removed before commit) confirmed that every passing N=8 test opens its DBs at N>1 only. The exceptions are by design: Issue921Test and NoDoubleCopy_And_AutoGC (no DB; dummy DB), the four WalManager tests (no DB::Open), and SecondaryAtWalPartitions (opens at N=1, then N=8).
  • Suites whose mode GC12 refuses at N>1. Their existing tests stay at N=1, and a new N in {1,8} test asserts the refusal:
    • db_secondary_test: with the temporary conversion every secondary open or catch-up at N=8 hit NotSupported (GC12 Q2). New DBSecondaryWalPartitionsTest.SecondaryAtWalPartitions: catch-up after the primary reopens at N refuses and exposes no new key; a new OpenAsSecondary refuses; both succeed at N=1.
    • repair_test: every repair at N=8 refused (GC12 Q2). New RepairWalPartitionsTest.RepairAtWalPartitions: NotSupported naming wal_partitions > 1, every DB file byte-identical, DB still opens with every key; at N=1 it repairs a lost MANIFEST.
    • wal_manager_test: GetUpdatesSince refuses N>1-written WALs (D-G32 (a)). The archival tests run at N=8; new GetUpdatesSinceAtWalPartitions asserts the refusal (N=1 iterates 30 records).
    • ldb_cmd_test: new LdbCmdWalPartitionsTest.DumpWalAtWalPartitions (from D127115188's test): dump_wal on each partition's current WAL prints its records and WAL partition: p for p != 0, the files hold every write once, --only_print_seqno_gaps refuses p != 0. Finding: dump_live_files (which opens the DB) is refused at N=8, because ldb reopens from the OPTIONS file, which does not keep the testing opt-in (GC13's design); asserted.
  • Kept out of the N=8 run, each with its reason (comment at the test where the line is upstream):
    • Open rejects the mode at N>1 (asserted by GC06's DBWriteTestUnparameterized.WalPartitionsRejectionsNameTheirOptions): CheckpointWithLockWALRejectsBlobDirectWrite, BackupWithoutFlushRejectsBlobDirectWrite, TransactionTest.DirectWriteCommitPath (bypass extended to wal_partitions > 1), ExternalSSTFileTest.WithUnorderedWrite (D-G05), the max_successive_merges leg of TransactionTest.DuplicateKeys, TransactionTest's two-queue, unordered and stackable instantiations (D-G03), and OptimisticTransactionTest with serial validation (D-N51; ValidatePolicyAtNPartitions covers it).
    • IngestFilesTriggerFlushingWithTwoWriteQueue shares its instantiation, so its N=8 instance asserts the NotSupported itself.
    • CommitBypassMemtableTest (13 tests): WBWI ingestion is refused at N>1 (DBWritePartitionTest.IngestWriteBatchWithIndexRejectedAtNPartitions).
    • Test artifacts of GC12's quiesce: CheckpointTest.SubsetOptionsAndManifestUseSameMembershipSnapshot and BackupEngineTest.FlushCompactDuringBackupCheckpoint run DB operations from the CheckpointImpl::CreateCustomCheckpoint:AfterGetLive1/2 sync points, which at N>1 sit inside the window where the checkpoint holds every write queue, so they deadlock by construction. Production never waits on a write queue inside that window. Listed as a hazard below.
    • Single-WAL assumptions: GarbageCollectionBeforeBackup (first SST file number), TransactionTest.TwoPhaseLogRollingTest/2 (prepares land in the one current WAL), TransactionTest.DoubleCrashInRecovery (corrupts partition 0's WAL at a fixed offset; the N>1 corruption matrix is GC14a's).
    • Fold rule: CheckpointCopiesIndexedWAL, BackupWithoutFlushCopiesIndexedWAL (D119600943), DumpWalPrintsIndexedRecords, CatchUpReadsIndexedWAL, UnflushedIndexedWAL (D119600943) are untouched; the new N in {1,8} tests cover their behaviour.
    • Not WAL-relevant (subset justification): backup rate-limiting suites; ExternalSSTFileWithTimestampTest, IngestDBGeneratedFileTest(2), ExternSSTFileLinkFailFallbackTest, ExternalSSTBlockChecksumTest (SST format/linking); five ExternalSSTFileBasicTest tests that build their own Options (SST sync, checksum readahead, atomic replace, bottommost check); the other 18 ldb tests (option parsing, SST/checksum tools); MySQLStyleTransactionTest, SnapshotConcurrentAccessTest, SeqAdvanceConcurrentTest (slow sharded brute-force; TransactionStressTest and Q3 cover the N>1 paths).
  • Skipped at N>1 because they exposed a bug (invariant 5, details below): WritePreparedTransactionTest.RollbackPreparedAfterCommitWriteFailure and its WriteUnprepared copy (G-14), CheckpointTest.CheckpointRacingLockWAL (G-30 residual), and WritePreparedTransactionTest.CommitOfDelayedPrepared (new). The 12 transaction_test N=8 skips are DoubleCrashInRecovery, TwoPhaseLogRollingTest, TwoPhaseLogRollingTest2 and DirectWriteCommitPath, 3 instances each (reasons above).
  • Adapted at N>1 without changing N=1: CurrentFileModifiedWhileCheckpointing2PC (WAL count bound 3 * N), BackupUsingDirectIO (subtract one WAL per partition), WriteUnpreparedTransactionTest.MarkLogWithPrepSection (compares with the newest current WAL across partitions).
  • Ported from D127115188 (credit), adapted to the base's quiesce so every copy opens in every recovery mode: CheckpointTest.CheckpointIncludesEveryPartitionCurrentWal, CheckpointTest.CheckpointConcurrentWritesArePrefix, BackupEngineTest.BackupIncludesEveryPartitionCurrentWal, ExternalSSTFileTestN.IngestionConcurrentWritesAtWalPartitions, and the ldb case above. Its disableWAL and failed-append ingestion cases are already pinned by GC12's IngestionAfterDisableWalWriteFindsRangesIdle and IngestionFailsCleanlyOverPinnedFailedAppend (Assumption 6).
  • Neuters: make SetWalPartitions a no-op: RepairAtWalPartitions fails (no refusal), and CheckpointIncludesEveryPartitionCurrentWal aborts on partition < wal_write_mutexes_.size(). Drop the WalManager::GetUpdatesSince peek: GetUpdatesSinceAtWalPartitions is not NotSupported.

Bug found (invariant 5): G-14 at N>1. WritePreparedTransactionTest.RollbackPreparedAfterCommitWriteFailure (and the WriteUnprepared copy) hang forever at N=8: the rollback after a failed commit append plus Resume() parks in DBImpl::WaitForWalDurability (stack: RunCompletionGate <- ExitAsBatchGroupLeader <- WritePreparedTxn::RollbackInternal). Steps: WritePrepared, max_bgerror_resume_count=0, prepare; inject a retryable write error on the commit; Resume(); roll back. Deterministic (no seed); 5 of 5 N=8 instances. This is G-14 ("Writes hang after a successful Resume()"), closed by GC08 (D127088253, Lane B), which is not in this base. The N>1 cases are skipped with ROCKSDB_GTEST_SKIP("G-14: ..."); N=1 is unchanged.

Bug found (invariant 5): G-30 (new residual) - a checkpoint racing another thread's UnlockWAL at N>1 can cut a hole. CheckpointImpl::CreateCustomCheckpoint skips the quiesce when lock_wal_owner_thread_id_counts_ is non-empty (db/db_filesnapshot.cc:586), then reads the WAL sizes later (GetOpenWalSizes, :629). If the LockWAL holder is another thread and it calls UnlockWAL in between, writes resume on every partition and the sizes are no longer one cut of the sequence order. The copy then fails to open: "Corruption: WAL index merge: unexplained hole at wal_index 1152 with records above it; cannot bound" (and wal_index 368 in a second run). Steps: CheckpointTest.CheckpointRacingLockWAL at N=8, with one writer per partition, a thread looping LockWAL/yield/UnlockWAL, and 5 checkpoints; open each copy read-only. There is no seed, because it is timing-dependent. Rate: 1 in 100 iterations under heavy load, and 1 in about 200 isolated iterations. The N>1 instance is skipped with ROCKSDB_GTEST_SKIP("G-30: ..."); the N=1 instance runs. The owner is GC12's quiesce hunk (D123079329). A fix must hold the queues across the UnlockWAL window (for example, re-check under mutex_ or wait for UnlockWAL before reading sizes); this diff does not attempt one.

Bug found (invariant 5): new - WritePrepared snapshots_version_ race between partition leaders. TSan flags WalPartitions8/WritePreparedTransactionTest.CommitOfDelayedPrepared/0 (an upstream test that now runs at N=8): AdvanceMaxEvictedSeq reads snapshots_version_ without snapshots_mutex_ (utilities/transactions/write_prepared_txn_db.cc:736), while another leader's UpdateSnapshots writes it under the lock (:930). At N>1 every partition leader runs AddCommitted -> AdvanceMaxEvictedSeq concurrently. Beyond the race itself: two leaders can both pass the unlocked check, and if the one with the smaller new_max takes the lock second, UpdateSnapshots writes the older version and the shorter snapshot list over the newer one. Snapshots between the two maxes then leave the list while max_evicted_seq_ is already past them. That is a snapshot-visibility risk, inferred from the code but not shown by a test. Reproduction: dev-tsan, --gtest_filter=WalPartitions8/WritePreparedTransactionTest.CommitOfDelayedPrepared/0 --gtest_repeat=5 gave 4 reports per 5 iterations in each of 3 runs, all the same pair of lines. All 9 N=1 instances, including the 6 two-queue ones, gave 0 reports in 3x5 iterations each. The lines are upstream (2018); none of the existing IDs covers them. The closest is G-18, shared state written by concurrent leaders, which belongs to GC10's owner. The N>1 instance is skipped with ROCKSDB_GTEST_SKIP("new: ..."), and the N=1 instances run. NonAtomicCommitOfDelayedPrepared and Q3's PrepareBelowMaxEvictedAtNPartitions still cover the delayed-prepared path at N>1 and are TSan clean.

Q2 - GC10's concurrent-prepares test is enabled. [G-56]

  • WritePreparedPartitionedWalTest.ConcurrentPreparesAcrossPartitions (N=4, 4x100 concurrent prepare+commit) loses its DISABLED_ prefix and its stale comment; the fixture's stale "which it does not support" comment is corrected. Passes; 100 of 100 repeats; TSan clean.
  • Neuter: restore GC12's original push (push_back with assert(heap_top_ < v)): aborts on that assertion.

Q3 - snapshots stay correct when PreparedHeap::top() moves backwards. [N-5-4]

  • WritePreparedPartitionedWalTest.SnapshotBelowHeapTopMovingBackwards (N=4): A's prepare on partition 0 is held at AddPreparedCallback::AddPrepared::begin:pause (after allocation, before the push); B's prepare on partition 1 allocates above it and is pushed first, then parks in its gate; a snapshot is taken; A is released, so A's push moves the top backwards. The held snapshot never sees A, before or after A commits; a snapshot after the commit does.
  • Finding: two bounds protect it. GC07 keeps the snapshot sequence below A (held_seq < a), and SmallestUnCommittedSeq caps min_uncommitted at LastSequence()+1 <= a, so the snapshot is never paired with the higher top.
  • WritePreparedTransactionTest.PrepareBelowMaxEvictedAtNPartitions (N=8, commit_cache_bits=1): A is held as above while three commits on other partitions evict entries committed above A; A then reaches AddPrepared below future_max_evicted_seq_ and CheckPreparedAgainstMax moves it to delayed_prepared_. Before its commit A reads as uncommitted at old, current and new snapshots; after its commit only the later snapshot sees it.
  • Neuters: let PublishAppliedPrefix publish past the applied prefix (max(frontier, high)): the held snapshot reads A's uncommitted "va" and IsInSnapshot is true. Skip the delayed_prepared_ move in CheckPreparedAgainstMax: the eviction test reads the uncommitted "va" (and IsInSnapshot is true), which also shows the test reached the below-max path.

Q4 - WriteUnprepared recovers across partitions. [N-5-4]

  • WriteUnpreparedPartitionedWalTest.RecoversAcrossPartitions (N=4, indexed, one queue, write_batch_flush_threshold=1): each transaction writes two column families on different partitions (two unprepared batches) and its XID routes prepare/commit markers to a third. From a crash image (synced writes, files copied while open): committed recovered, rolled back gone, the two prepared ones recover as prepared, one commits and one rolls back, and a second reopen finds nothing prepared.
  • Neuters: route every write to partition 0 (WalPartitionForWrite): the spread precondition fails ("every column family routes to one partition"). Skip the recovered AddPrepared rebuild in WriteUnpreparedTxnDB::Initialize: the recovered prepared transactions' data reads as committed.

Q5 - checkpoint and backup alongside LockWAL; the quiesce never hangs. [G-30/G-31] Answer: partly. The holder's own checkpoint and the backup work at N=8, and no checkpoint hung. A checkpoint racing another thread's LockWAL/UnlockWAL loop completes but can produce a copy that does not open (G-30 residual above), so that property fails at N>1.

  • CheckpointTest.CheckpointByLockWALHolder: the LockWAL holder's checkpoint returns (within 30 s) and the copy holds every write acknowledged before LockWAL, on every partition, in every recovery mode.
  • CheckpointTest.CheckpointRacingLockWAL: five checkpoints race another thread's LockWAL/UnlockWAL loop while writers run on every partition. Each finishes within 30 s, and each copy should be a per-writer prefix holding every acked write, in every recovery mode. That holds at N=1. At N=8 every checkpoint finished in time, but 1 in about 100-200 iterations produced the unopenable copy. The N=8 instance is skipped (G-30).
  • BackupEngineTest.BackupWithoutFlushDuringWritesIsPrefix: CreateNewBackup(flush_before_backup=false) during writes restores to such a prefix, in every recovery mode.
  • All run at N=1 and N=8 and are TSan clean. The 100-repeat run had two RunWithin aborts (CheckpointByLockWALHolder and CheckpointConcurrentWritesArePrefix at N=8, each on its first iteration) while the host load average was about 2500 on 192 cores. Both then passed 200 of 200 isolated iterations, so they are counted as load, not hangs.
  • Neuter: remove the quiesce (db_filesnapshot.cc): copies fail to open with "WAL index merge: unexplained hole at wal_index N", in 20 test iterations of the two concurrent checkpoint tests and 8 of 20 backup iterations.

Fold-back split

Q1, Q3, Q4 and Q5 stay in this standalone diff (README row 37). Every hunk was mapped with sl annotate -r 01ebc084d2ed; all modified lines are upstream except the Q2 hunks.

  • Q1 (standalone): test_util/testharness.{h,cc} (helper), db/db_test_util.{h,cc} (hook, option skip, shared helpers), and the hooks, instantiations, TEST_F->TEST_P conversions, adaptations and new tests in all twelve suites. Pure insertions next to D119600943/GC12 lines (ldb_cmd_test.cc include and the new test after DumpWalOnPartitionedWals; backup_engine_test.cc new tests after BackupWithoutFlushCopiesIndexedWAL) modify none of them.
  • Q2 -> D123079329: write_prepared_transaction_test.cc hunk at the GC10 test (rename, comment) and the CommitWithState comment.
  • Q3 (standalone, needs D123476301 and GC07): SnapshotBelowHeapTopMovingBackwards (uses GC10's fixture from D123079329) and PrepareBelowMaxEvictedAtNPartitions, plus the db/snapshot_impl.h include.
  • Q4 (standalone, needs D123928339's crash-image reopen): RecoversAcrossPartitions and its includes.
  • Q5 (standalone, needs D123079329's quiesce): the three tests above, including the G-30 skip inside the new CheckpointRacingLockWAL.
  • The new-bug skip in CommitOfDelayedPrepared edits an upstream test, so it is Q1 (standalone).
  • Cannot live lower: every N=8 instance needs the opt-in (in base since M1) and the N>1 write path (D123079329); the ones that reopen N>1 copies need D123928339.

Assumptions (rule from AB-Implementation-Requirement.md section 4)

  1. "N in {1,8} with WAL indexing on": the N=1 instance keeps each suite's default options (kNone, as before), so its assertions are unchanged; the N=8 instance turns indexing on. Rule 5 (N=1 unchanged).
  2. SetWalPartitions also clears recycle_log_file_num at N>1: suites set it only to stress WAL reuse, and Open rejects it at N>1. Rule 5.
  3. Tests whose mode Open or GC12 rejects at N>1 stay out of the N=8 run, with the rejection asserted once by a new suite test (secondary, repair, wal_manager, ldb) or by GC06's existing rejection test. Where a test shares an instantiation it cannot leave, it bypasses at N>1, or asserts the rejection (two-queue ingestion). Rule 2 (Q1 text).
  4. The "opt build" requirement is met by the mechanism, not by an opt run: fbcode marks rocksdb_test_lib incompatible with @mode/opt, and a DEBUG_LEVEL=0 make of the test harness fails upstream (SyncPoint undeclared in db_test_util.cc). The helper uses only the opt-in, so the dev N=8 runs take the path opt builds take. Rule 5.
  5. The G-14 hang is GC08's (Lane B) and is not fixed here; the two N>1 cases are skipped naming G-14. Invariant 5.
  6. D127115188's disableWAL and failed-append ingestion cases are not re-added: GC12's tests pin the same behaviours. Rule 5 (least code).
  7. Q3's eviction test runs on WritePreparedTransactionTest at N=8 only (bypassed at N=1, where holding a prepare holds every write), because wp_commit_cache_bits is private to that fixture's friends. Rule 5.
  8. Notes were read from the JustinGaoNotesChanges commit exported to /tmp; nothing under the notes directory was touched. Rule 2.
  9. The racing-checkpoint hole is filed as a G-30 residual ("checkpoint and backup copy all N chains as a consistent set") rather than a new ID. Invariant 5 ("naming the checklist ID (or "new")").
  10. The 100-repeat requirement covers every N=8 instance whose test body uses SyncPoint or fault injection, plus every new test at both N: 193 test instances. The other N=8 instances ran once each in two full passes. A body is selected if it mentions SyncPoint, FaultInjection, fault_fs/fault_env or TEST_SYNC_POINT. Rule 5.

Not done

  • Fixing the snapshots_version_ race between leaders (new). Found here; GC10's owner.
  • Q5's racing property is not met at N>1 (G-30 residual). Finding it is done here; the fix belongs to GC12's owner (D123079329).
  • The opt-mode suite run (Assumption 4).

Safety boundaries and unsupported cases

  • Tests only. No production, public header, option or WAL-format change; db_bench output is byte-identical to the base (Test Plan).
  • N=1 instances run with each suite's original options and assertions. The only N=1-visible change is the WalPartitions1/ name prefix on the converted TEST_F tests.
  • Open hazards, not covered here:
    • The AfterGetLive1/2 sync points sit inside the N>1 quiesce: any future test that runs a write-queue operation from them deadlocks at N>1 (new; test-only).
    • G-14 (GC08) until Lane B is folded.
    • G-30 residual: checkpoint or backup racing another thread's UnlockWAL at N>1 (above).
    • New: WritePreparedTxnDB snapshot-list version race between partition leaders (above).
    • ldb commands that open the DB cannot open an N>1 DB (OPTIONS file drops the opt-in); tooling question for GC13/GC18.
    • G-55/N-3-5/muse [Muse][GC] GC23: Recovery and consumer carry-over after GC19 and GC22 #19/G-57/N-7-4 are GC14a's.

Test Plan:
All runs are on devvm dev builds of the final tree unless noted. "Final tree" is caeba6be1b7f plus the two invariant-5 skips (CheckpointRacingLockWAL, CommitOfDelayedPrepared), which add skips and change nothing else.

  1. buck2 test fbcode//internal_repo_rocksdb/repo:{checkpoint_test,backup_engine_test,wal_manager_test,db_secondary_test,repair_test,ldb_cmd_test,external_sst_file_test,external_sst_file_basic_test,transaction_test,write_prepared_transaction_test,write_unprepared_transaction_test,optimistic_transaction_test}:
    • final tree: Pass 5535, Fail 0, Timeout 0, Fatal 0, Skip 7 (5 G-14 skips, the G-30 skip and the new-race skip).
    • caeba6be1b7f: Pass 5537, Fail 0, Timeout 0, Fatal 0, Skip 5 (the 5 G-14 skips). Exit 64 is tpx's code for "passes and skips".
  2. Full pass, one process per test (every test in every suite, 24-way parallel): 0 failures and 0 timeouts. Per-suite N=1 and N>1 counts are in the Q1 table. checkpoint_test and write_prepared_transaction_test were re-run after the skips: 110 pass + 1 skip, and 918 pass + 11 skip.
  3. Which N each test opens at: a temporary GC14B_TRACE line in DBImpl::ValidateOptions logged every open during an earlier full pass. Every passing N=8 test opened at N>1 only, except the by-design cases in Q1. The trace was reverted with sl revert, and the commit does not contain it.
  4. TSan (@fbcode//mode/dev-tsan), on every WalPartitions* instance, both partitioned fixtures, and the edited N=1 tests (DoubleCrashInRecovery, TwoPhaseLogRollingTest*, DirectWriteCommitPath, DuplicateKeys, MarkLogWithPrepSection, RollbackPreparedAfterCommitWriteFailure). Results by suite:
    • checkpoint 95 pass + 1 skip (final);
    • backup 118;
    • wal_manager 8;
    • secondary 2;
    • repair 2;
    • ldb 2;
    • external_sst 154;
    • external_sst_basic 60 + 2 upstream skips;
    • optimistic 34;
    • write_unprepared 78 + 4 G-14 skips;
    • write_prepared 76 + 2 skips (final);
    • transaction 410 + 58 skips + 3 disabled.
      0 ThreadSanitizer reports. Before the skip, WalPartitions8/WritePreparedTransactionTest.CommitOfDelayedPrepared/0 reported the race above. Excluded: ExternalSSTFileBasicTestN.LargeSizeSstFileWriter, an upstream big-memory test (4 GiB key and value) that OOM-killed the TSan run twice. It is not WAL-related and passes in dev.
  5. --gtest_repeat=100 on 193 test instances: every N=8 instance whose body uses SyncPoint or fault injection, plus every new test at both N (Assumption 10). This includes Q2's ConcurrentPreparesAcrossPartitions and every Q3/Q4/Q5 test. All passed except:
    • WalPartitions8/CheckpointTest.CheckpointRacingLockWAL/0: 1 of 100 failed. Isolated, 1 of 200 failed. This is the G-30 residual; the test is now skipped.
    • CheckpointByLockWALHolder and CheckpointConcurrentWritesArePrefix at N=8: one RunWithin 30 s abort each, on the first iteration, during a load average of about 2500. Isolated, each passed 200 of 200.
    • WalPartitions8/ExternalSSTFileTestN.IngestFlushRequestNotLostBehindQueuedFlush/0 (upstream): 1 of 100 failed, on iteration 2, which took 335 s (the median is 1 s), in the same overload window, with the "Timed out waiting" hang guard. Isolated, it passed 300 of 300 at N=8 and 100 of 100 at N=1.
  6. Neuters (each change applied, the run observed, the change reverted):
    • Q2: restore the old PreparedHeap::push. The test aborts on heap_top_ < v.
    • Q3: publish past the applied prefix. The held snapshot reads uncommitted "va".
    • Q3: skip the delayed_prepared_ move. The eviction test reads uncommitted "va".
    • Q4: route every write to partition 0. The precondition fails.
    • Q4: skip the recovered AddPrepared rebuild. Recovered prepared data reads as committed.
    • Q5: drop the quiesce. Checkpoint copies fail with "unexplained hole" in 20 of 20 iterations; backup in 8 of 20.
    • WalManager: drop the peek. The N=8 call is not NotSupported.
    • Helper: make SetWalPartitions a no-op. The repair and checkpoint N=8 tests fail.
  7. N=1 byte identity: dev-mode db_bench --benchmarks=fillseq --num=10000 --seed=20260928 --threads=1 --disable_auto_compactions=1, no flush before close, built from this commit and from the base. Recorded value: the SHA-256 of the live WAL (000004.log):
    • partition_wal_usage=none: 6d1351117a289a2784449a68d5421b1aa385ab0b383273c2c5918befa9181b09
    • partition_by_column_family: 9a69a3fc66777fadce05e8a999479a5f57364aca27cd6d22aa00e4631adfc796
      Both match the base. No production file changed.
  8. Opt mode: not run, because it is impossible here (Assumption 4). fbcode marks rocksdb_test_lib incompatible with @mode/opt, and a DEBUG_LEVEL=0 make of the test harness fails upstream.
  9. Repo-pinned tools/third-party/clang-format/clang-format-diff.py (with tools/third-party/clang-format/clang-format) over sl diff -r 01ebc084d2ed: no changes. arc lint -a on every modified file: no issues. No non-ASCII characters.
    TBD

Differential Revision: https://phabricator.intern.facebook.com/D127275775
fbsource-commit: db6612fbcbee

Summary:
[GC] GC14b

**Reviewer question:** Does every consumer and transaction suite now run at N=8, and does each N=8 assertion match what GC12 settled?

Closes G-56 and GC12's carry-over Q2-Q5. Tests only: no production file changes (`sl diff -r 01ebc084d2ed --stat` lists only `*_test.cc`, `transaction_test.h`, `db_test_util.{h,cc}` and `test_util/testharness.{h,cc}`).

## Why
- M3 ("N>1 production-testable") needs every WAL consumer and transaction suite to run at N>1. At the base, none of the twelve suites mentioned `wal_partitions`, so a regression in checkpoint, backup, ingestion or transactions at N>1 would land unseen.
- GC12 left four weak spots untested: GC10's concurrent-prepares test was still disabled; `PreparedHeap::top()` moving backwards; WriteUnprepared across partitions; checkpoint/backup alongside `LockWAL`.

## Previous behavior
- Every one of the twelve suites ran at N=1 only. GC12's outcomes (secondary and repair refuse, `GetUpdatesSince` refuses, `ldb dump_wal` labels partitions, the checkpoint quiesce) were pinned only by GC12's own targeted tests.
- `WritePreparedPartitionedWalTest.DISABLED_ConcurrentPreparesAcrossPartitions` was disabled, and its comment still said the heap defect was unfixed.

## New behavior
- Each suite has a `WalPartitions8` instance (or an N in {1,8} test asserting GC12's refusal), driven by one helper. The N=1 instances are unchanged.
- GC10's test is enabled. New tests pin Q3 (heap top moving backwards; prepare below `max_evicted_seq`), Q4 (WriteUnprepared crash-image recovery across partitions) and Q5 (checkpoint and backup alongside `LockWAL`).
- Two N>1 bugs were found and not fixed (invariant 5): a G-30 residual (checkpoint racing `UnlockWAL`) and a new WritePrepared race. The G-14 hang (GC08) was also hit; it is not in this base.

## Implementation
- `test_util/testharness.{h,cc}`:
  - `test::SetWalPartitions(options, n)` sets `wal_partitions` plus what Open needs for n>1: indexing (`kPartitionByColumnFamily` if `kNone`), `track_and_verify_wals_in_manifest`, `recycle_log_file_num=0`, and `experimental_allow_wal_partitions_for_testing`. It uses no sync point, so it is the same open path an opt build takes. It does nothing for n=1.
  - `test::WalPartitionsForCurrentTest()` returns 8 when the running test belongs to an instantiation named `WalPartitions8`, else 1. Fixtures call it while being constructed, so no parameter tuple had to be widened.
- One-line hooks: `DBTestBase::GetOptions` (secondary, repair, both external_sst suites, `CommitBypassMemtableTest`), `TransactionTestBase` (transaction, WritePrepared, WriteUnprepared), `OptimisticTransactionTest`, `CheckpointTestBase::CurrentOptions`, `BackupEngineTestBase`'s constructor, `WalManagerTest::RollTheLog` (spreads its WAL files over partitions with markers).
- Existing TEST_P suites got one `INSTANTIATE_TEST_CASE_P(WalPartitions8, ...)` each, restricted to the parameters N>1 accepts. TEST_F suites had their WAL-relevant tests turned into TEST_P on a parameterized fixture (`CheckpointTest`, `BackupEngineTest`, `WalManagerTest`) or a thin subclass (`ExternalSSTFileTestN`, `ExternalSSTFileBasicTestN`), instantiated as `WalPartitions1` and `WalPartitions8`. N=1 instances assert exactly what they asserted before (their names gain the `WalPartitions1/` prefix).
- `DBTestBase::ShouldSkipOptions` skips, at N>1 only, the option configurations Open rejects there (hash-skiplist, hash-linklist and vector memtables, pipelined, two queues, unordered).
- Shared test helpers in `db_test_util.{h,cc}`: `ColumnFamilyIdsCoveringWalPartitions`, `ColumnFamilyNamesThrough`, `PartitionWriters` (one writer per partition, acked counts), `AssertKeyPrefixesInEveryRecoveryMode` (opens a copy read-only in all four `WALRecoveryMode`s and checks per-writer prefixes), and `RunWithin` (30 s bound; aborts on a hang).

This is better than widening parameter tuples (hundreds of `std::get<>` edits in the transaction suites) or adding test targets (BUCK is generated), and it keeps one mechanism for all twelve suites.

## Answers

**Q1 - the twelve suites at N in {1,8}.** [G-56]
- Property: every listed suite has an N=8 instance; each N=8 test passes or asserts GC12's (or the Open gate's) outcome; N=1 is unchanged.
- Counts, from a full single-process-per-test pass of every test at the final tree (see Test Plan):

| Suite | N=1 pass / skip / disabled | N>1 pass / skip / disabled | N>1 skip reasons |
|---|---|---|---|
| checkpoint_test | 60 / 0 / 0 | 50 / 1 / 0 | G-30 residual |
| backup_engine_test | 110 / 0 / 0 | 66 / 0 / 0 | |
| wal_manager_test | 8 / 0 / 0 | 4 / 0 / 0 | |
| db_secondary_test | 73 / 0 / 2 | 1 / 0 / 0 | suite refused at N>1 (GC12) |
| repair_test | 19 / 0 / 0 | 1 / 0 / 0 | suite refused at N>1 (GC12) |
| ldb_cmd_test | 20 / 0 / 0 | 1 / 0 / 0 | |
| external_sst_file_test | 224 / 0 / 4 | 109 / 0 / 0 | |
| external_sst_file_basic_test | 42 / 2 / 0 | 37 / 2 / 0 | the same 2 upstream skips as N=1 |
| transaction_test | 2843 / 265 / 31 | 281 / 37 / 3 | 12 listed below; 25 policy bypasses that also fire at N=1 |
| write_prepared_transaction_test | 851 / 9 / 0 | 67 / 2 / 0 | G-14; new `snapshots_version_` race |
| write_unprepared_transaction_test | 184 / 0 / 0 | 62 / 4 / 0 | G-14 |
| optimistic_transaction_test | 72 / 0 / 0 | 35 / 0 / 0 | |

N>1 counts the `WalPartitions8` instances plus the N=4 partitioned fixtures (`WritePreparedPartitionedWalTest`, `WriteUnpreparedPartitionedWalTest`). Disabled tests are upstream `DISABLED_` tests.

- A temporary, env-gated trace in `DBImpl::ValidateOptions` (removed before commit) confirmed that every passing N=8 test opens its DBs at N>1 only. The exceptions are by design: `Issue921Test` and `NoDoubleCopy_And_AutoGC` (no DB; dummy DB), the four WalManager tests (no DB::Open), and `SecondaryAtWalPartitions` (opens at N=1, then N=8).
- Suites whose mode GC12 refuses at N>1. Their existing tests stay at N=1, and a new N in {1,8} test asserts the refusal:
  - `db_secondary_test`: with the temporary conversion every secondary open or catch-up at N=8 hit `NotSupported` (GC12 Q2). New `DBSecondaryWalPartitionsTest.SecondaryAtWalPartitions`: catch-up after the primary reopens at N refuses and exposes no new key; a new `OpenAsSecondary` refuses; both succeed at N=1.
  - `repair_test`: every repair at N=8 refused (GC12 Q2). New `RepairWalPartitionsTest.RepairAtWalPartitions`: NotSupported naming `wal_partitions > 1`, every DB file byte-identical, DB still opens with every key; at N=1 it repairs a lost MANIFEST.
  - `wal_manager_test`: `GetUpdatesSince` refuses N>1-written WALs (D-G32 (a)). The archival tests run at N=8; new `GetUpdatesSinceAtWalPartitions` asserts the refusal (N=1 iterates 30 records).
  - `ldb_cmd_test`: new `LdbCmdWalPartitionsTest.DumpWalAtWalPartitions` (from D127115188's test): `dump_wal` on each partition's current WAL prints its records and `WAL partition: p` for p != 0, the files hold every write once, `--only_print_seqno_gaps` refuses p != 0. Finding: `dump_live_files` (which opens the DB) is refused at N=8, because ldb reopens from the OPTIONS file, which does not keep the testing opt-in (GC13's design); asserted.
- Kept out of the N=8 run, each with its reason (comment at the test where the line is upstream):
  - Open rejects the mode at N>1 (asserted by GC06's `DBWriteTestUnparameterized.WalPartitionsRejectionsNameTheirOptions`): `CheckpointWithLockWALRejectsBlobDirectWrite`, `BackupWithoutFlushRejectsBlobDirectWrite`, `TransactionTest.DirectWriteCommitPath` (bypass extended to `wal_partitions > 1`), `ExternalSSTFileTest.WithUnorderedWrite` (D-G05), the `max_successive_merges` leg of `TransactionTest.DuplicateKeys`, `TransactionTest`'s two-queue, unordered and stackable instantiations (D-G03), and `OptimisticTransactionTest` with serial validation (D-N51; `ValidatePolicyAtNPartitions` covers it).
  - `IngestFilesTriggerFlushingWithTwoWriteQueue` shares its instantiation, so its N=8 instance asserts the NotSupported itself.
  - `CommitBypassMemtableTest` (13 tests): WBWI ingestion is refused at N>1 (`DBWritePartitionTest.IngestWriteBatchWithIndexRejectedAtNPartitions`).
  - Test artifacts of GC12's quiesce: `CheckpointTest.SubsetOptionsAndManifestUseSameMembershipSnapshot` and `BackupEngineTest.FlushCompactDuringBackupCheckpoint` run DB operations from the `CheckpointImpl::CreateCustomCheckpoint:AfterGetLive1/2` sync points, which at N>1 sit inside the window where the checkpoint holds every write queue, so they deadlock by construction. Production never waits on a write queue inside that window. Listed as a hazard below.
  - Single-WAL assumptions: `GarbageCollectionBeforeBackup` (first SST file number), `TransactionTest.TwoPhaseLogRollingTest`/`2` (prepares land in the one current WAL), `TransactionTest.DoubleCrashInRecovery` (corrupts partition 0's WAL at a fixed offset; the N>1 corruption matrix is GC14a's).
  - Fold rule: `CheckpointCopiesIndexedWAL`, `BackupWithoutFlushCopiesIndexedWAL` (D119600943), `DumpWalPrintsIndexedRecords`, `CatchUpReadsIndexedWAL`, `UnflushedIndexedWAL` (D119600943) are untouched; the new N in {1,8} tests cover their behaviour.
  - Not WAL-relevant (subset justification): backup rate-limiting suites; `ExternalSSTFileWithTimestampTest`, `IngestDBGeneratedFileTest(2)`, `ExternSSTFileLinkFailFallbackTest`, `ExternalSSTBlockChecksumTest` (SST format/linking); five `ExternalSSTFileBasicTest` tests that build their own Options (SST sync, checksum readahead, atomic replace, bottommost check); the other 18 ldb tests (option parsing, SST/checksum tools); `MySQLStyleTransactionTest`, `SnapshotConcurrentAccessTest`, `SeqAdvanceConcurrentTest` (slow sharded brute-force; `TransactionStressTest` and Q3 cover the N>1 paths).
- Skipped at N>1 because they exposed a bug (invariant 5, details below): `WritePreparedTransactionTest.RollbackPreparedAfterCommitWriteFailure` and its WriteUnprepared copy (G-14), `CheckpointTest.CheckpointRacingLockWAL` (G-30 residual), and `WritePreparedTransactionTest.CommitOfDelayedPrepared` (new). The 12 transaction_test N=8 skips are `DoubleCrashInRecovery`, `TwoPhaseLogRollingTest`, `TwoPhaseLogRollingTest2` and `DirectWriteCommitPath`, 3 instances each (reasons above).
- Adapted at N>1 without changing N=1: `CurrentFileModifiedWhileCheckpointing2PC` (WAL count bound `3 * N`), `BackupUsingDirectIO` (subtract one WAL per partition), `WriteUnpreparedTransactionTest.MarkLogWithPrepSection` (compares with the newest current WAL across partitions).
- Ported from D127115188 (credit), adapted to the base's quiesce so every copy opens in every recovery mode: `CheckpointTest.CheckpointIncludesEveryPartitionCurrentWal`, `CheckpointTest.CheckpointConcurrentWritesArePrefix`, `BackupEngineTest.BackupIncludesEveryPartitionCurrentWal`, `ExternalSSTFileTestN.IngestionConcurrentWritesAtWalPartitions`, and the ldb case above. Its disableWAL and failed-append ingestion cases are already pinned by GC12's `IngestionAfterDisableWalWriteFindsRangesIdle` and `IngestionFailsCleanlyOverPinnedFailedAppend` (Assumption 6).
- Neuters: make `SetWalPartitions` a no-op: `RepairAtWalPartitions` fails (no refusal), and `CheckpointIncludesEveryPartitionCurrentWal` aborts on `partition < wal_write_mutexes_.size()`. Drop the `WalManager::GetUpdatesSince` peek: `GetUpdatesSinceAtWalPartitions` is not NotSupported.

**Bug found (invariant 5): G-14 at N>1.** `WritePreparedTransactionTest.RollbackPreparedAfterCommitWriteFailure` (and the WriteUnprepared copy) hang forever at N=8: the rollback after a failed commit append plus `Resume()` parks in `DBImpl::WaitForWalDurability` (stack: `RunCompletionGate` <- `ExitAsBatchGroupLeader` <- `WritePreparedTxn::RollbackInternal`). Steps: WritePrepared, `max_bgerror_resume_count=0`, prepare; inject a retryable write error on the commit; `Resume()`; roll back. Deterministic (no seed); 5 of 5 N=8 instances. This is G-14 ("Writes hang after a successful Resume()"), closed by GC08 (D127088253, Lane B), which is not in this base. The N>1 cases are skipped with `ROCKSDB_GTEST_SKIP("G-14: ...")`; N=1 is unchanged.

**Bug found (invariant 5): G-30 (new residual) - a checkpoint racing another thread's `UnlockWAL` at N>1 can cut a hole.** `CheckpointImpl::CreateCustomCheckpoint` skips the quiesce when `lock_wal_owner_thread_id_counts_` is non-empty (`db/db_filesnapshot.cc:586`), then reads the WAL sizes later (`GetOpenWalSizes`, `:629`). If the `LockWAL` holder is another thread and it calls `UnlockWAL` in between, writes resume on every partition and the sizes are no longer one cut of the sequence order. The copy then fails to open: "Corruption: WAL index merge: unexplained hole at wal_index 1152 with records above it; cannot bound" (and wal_index 368 in a second run). Steps: `CheckpointTest.CheckpointRacingLockWAL` at N=8, with one writer per partition, a thread looping `LockWAL`/`yield`/`UnlockWAL`, and 5 checkpoints; open each copy read-only. There is no seed, because it is timing-dependent. Rate: 1 in 100 iterations under heavy load, and 1 in about 200 isolated iterations. The N>1 instance is skipped with `ROCKSDB_GTEST_SKIP("G-30: ...")`; the N=1 instance runs. The owner is GC12's quiesce hunk (D123079329). A fix must hold the queues across the `UnlockWAL` window (for example, re-check under `mutex_` or wait for `UnlockWAL` before reading sizes); this diff does not attempt one.

**Bug found (invariant 5): new - WritePrepared `snapshots_version_` race between partition leaders.** TSan flags `WalPartitions8/WritePreparedTransactionTest.CommitOfDelayedPrepared/0` (an upstream test that now runs at N=8): `AdvanceMaxEvictedSeq` reads `snapshots_version_` without `snapshots_mutex_` (`utilities/transactions/write_prepared_txn_db.cc:736`), while another leader's `UpdateSnapshots` writes it under the lock (`:930`). At N>1 every partition leader runs `AddCommitted` -> `AdvanceMaxEvictedSeq` concurrently. Beyond the race itself: two leaders can both pass the unlocked check, and if the one with the smaller `new_max` takes the lock second, `UpdateSnapshots` writes the older version and the shorter snapshot list over the newer one. Snapshots between the two maxes then leave the list while `max_evicted_seq_` is already past them. That is a snapshot-visibility risk, inferred from the code but not shown by a test. Reproduction: dev-tsan, `--gtest_filter=WalPartitions8/WritePreparedTransactionTest.CommitOfDelayedPrepared/0 --gtest_repeat=5` gave 4 reports per 5 iterations in each of 3 runs, all the same pair of lines. All 9 N=1 instances, including the 6 two-queue ones, gave 0 reports in 3x5 iterations each. The lines are upstream (2018); none of the existing IDs covers them. The closest is G-18, shared state written by concurrent leaders, which belongs to GC10's owner. The N>1 instance is skipped with `ROCKSDB_GTEST_SKIP("new: ...")`, and the N=1 instances run. `NonAtomicCommitOfDelayedPrepared` and Q3's `PrepareBelowMaxEvictedAtNPartitions` still cover the delayed-prepared path at N>1 and are TSan clean.

**Q2 - GC10's concurrent-prepares test is enabled.** [G-56]
- `WritePreparedPartitionedWalTest.ConcurrentPreparesAcrossPartitions` (N=4, 4x100 concurrent prepare+commit) loses its `DISABLED_` prefix and its stale comment; the fixture's stale "which it does not support" comment is corrected. Passes; 100 of 100 repeats; TSan clean.
- Neuter: restore GC12's original `push` (`push_back` with `assert(heap_top_ < v)`): aborts on that assertion.

**Q3 - snapshots stay correct when `PreparedHeap::top()` moves backwards.** [N-5-4]
- `WritePreparedPartitionedWalTest.SnapshotBelowHeapTopMovingBackwards` (N=4): A's prepare on partition 0 is held at `AddPreparedCallback::AddPrepared::begin:pause` (after allocation, before the push); B's prepare on partition 1 allocates above it and is pushed first, then parks in its gate; a snapshot is taken; A is released, so A's push moves the top backwards. The held snapshot never sees A, before or after A commits; a snapshot after the commit does.
- Finding: two bounds protect it. GC07 keeps the snapshot sequence below A (`held_seq < a`), and `SmallestUnCommittedSeq` caps `min_uncommitted` at `LastSequence()+1 <= a`, so the snapshot is never paired with the higher top.
- `WritePreparedTransactionTest.PrepareBelowMaxEvictedAtNPartitions` (N=8, `commit_cache_bits=1`): A is held as above while three commits on other partitions evict entries committed above A; A then reaches `AddPrepared` below `future_max_evicted_seq_` and `CheckPreparedAgainstMax` moves it to `delayed_prepared_`. Before its commit A reads as uncommitted at old, current and new snapshots; after its commit only the later snapshot sees it.
- Neuters: let `PublishAppliedPrefix` publish past the applied prefix (`max(frontier, high)`): the held snapshot reads A's uncommitted "va" and `IsInSnapshot` is true. Skip the `delayed_prepared_` move in `CheckPreparedAgainstMax`: the eviction test reads the uncommitted "va" (and `IsInSnapshot` is true), which also shows the test reached the below-max path.

**Q4 - WriteUnprepared recovers across partitions.** [N-5-4]
- `WriteUnpreparedPartitionedWalTest.RecoversAcrossPartitions` (N=4, indexed, one queue, `write_batch_flush_threshold=1`): each transaction writes two column families on different partitions (two unprepared batches) and its XID routes prepare/commit markers to a third. From a crash image (synced writes, files copied while open): committed recovered, rolled back gone, the two prepared ones recover as prepared, one commits and one rolls back, and a second reopen finds nothing prepared.
- Neuters: route every write to partition 0 (`WalPartitionForWrite`): the spread precondition fails ("every column family routes to one partition"). Skip the recovered `AddPrepared` rebuild in `WriteUnpreparedTxnDB::Initialize`: the recovered prepared transactions' data reads as committed.

**Q5 - checkpoint and backup alongside `LockWAL`; the quiesce never hangs.** [G-30/G-31] Answer: partly. The holder's own checkpoint and the backup work at N=8, and no checkpoint hung. A checkpoint racing another thread's `LockWAL`/`UnlockWAL` loop completes but can produce a copy that does not open (G-30 residual above), so that property fails at N>1.
- `CheckpointTest.CheckpointByLockWALHolder`: the `LockWAL` holder's checkpoint returns (within 30 s) and the copy holds every write acknowledged before `LockWAL`, on every partition, in every recovery mode.
- `CheckpointTest.CheckpointRacingLockWAL`: five checkpoints race another thread's `LockWAL`/`UnlockWAL` loop while writers run on every partition. Each finishes within 30 s, and each copy should be a per-writer prefix holding every acked write, in every recovery mode. That holds at N=1. At N=8 every checkpoint finished in time, but 1 in about 100-200 iterations produced the unopenable copy. The N=8 instance is skipped (G-30).
- `BackupEngineTest.BackupWithoutFlushDuringWritesIsPrefix`: `CreateNewBackup(flush_before_backup=false)` during writes restores to such a prefix, in every recovery mode.
- All run at N=1 and N=8 and are TSan clean. The 100-repeat run had two `RunWithin` aborts (`CheckpointByLockWALHolder` and `CheckpointConcurrentWritesArePrefix` at N=8, each on its first iteration) while the host load average was about 2500 on 192 cores. Both then passed 200 of 200 isolated iterations, so they are counted as load, not hangs.
- Neuter: remove the quiesce (`db_filesnapshot.cc`): copies fail to open with "WAL index merge: unexplained hole at wal_index N", in 20 test iterations of the two concurrent checkpoint tests and 8 of 20 backup iterations.

## Fold-back split
Q1, Q3, Q4 and Q5 stay in this standalone diff (README row 37). Every hunk was mapped with `sl annotate -r 01ebc084d2ed`; all modified lines are upstream except the Q2 hunks.
- **Q1 (standalone):** `test_util/testharness.{h,cc}` (helper), `db/db_test_util.{h,cc}` (hook, option skip, shared helpers), and the hooks, instantiations, TEST_F->TEST_P conversions, adaptations and new tests in all twelve suites. Pure insertions next to D119600943/GC12 lines (`ldb_cmd_test.cc` include and the new test after `DumpWalOnPartitionedWals`; `backup_engine_test.cc` new tests after `BackupWithoutFlushCopiesIndexedWAL`) modify none of them.
- **Q2 -> D123079329:** `write_prepared_transaction_test.cc` hunk at the GC10 test (rename, comment) and the `CommitWithState` comment.
- **Q3 (standalone, needs D123476301 and GC07):** `SnapshotBelowHeapTopMovingBackwards` (uses GC10's fixture from D123079329) and `PrepareBelowMaxEvictedAtNPartitions`, plus the `db/snapshot_impl.h` include.
- **Q4 (standalone, needs D123928339's crash-image reopen):** `RecoversAcrossPartitions` and its includes.
- **Q5 (standalone, needs D123079329's quiesce):** the three tests above, including the G-30 skip inside the new `CheckpointRacingLockWAL`.
- The new-bug skip in `CommitOfDelayedPrepared` edits an upstream test, so it is Q1 (standalone).
- Cannot live lower: every N=8 instance needs the opt-in (in base since M1) and the N>1 write path (D123079329); the ones that reopen N>1 copies need D123928339.

## Assumptions (rule from `AB-Implementation-Requirement.md` section 4)
1. "N in {1,8} with WAL indexing on": the N=1 instance keeps each suite's default options (`kNone`, as before), so its assertions are unchanged; the N=8 instance turns indexing on. Rule 5 (N=1 unchanged).
2. `SetWalPartitions` also clears `recycle_log_file_num` at N>1: suites set it only to stress WAL reuse, and Open rejects it at N>1. Rule 5.
3. Tests whose mode Open or GC12 rejects at N>1 stay out of the N=8 run, with the rejection asserted once by a new suite test (secondary, repair, wal_manager, ldb) or by GC06's existing rejection test. Where a test shares an instantiation it cannot leave, it bypasses at N>1, or asserts the rejection (two-queue ingestion). Rule 2 (Q1 text).
4. The "opt build" requirement is met by the mechanism, not by an opt run: fbcode marks `rocksdb_test_lib` incompatible with `@mode/opt`, and a `DEBUG_LEVEL=0 make` of the test harness fails upstream (`SyncPoint` undeclared in `db_test_util.cc`). The helper uses only the opt-in, so the dev N=8 runs take the path opt builds take. Rule 5.
5. The G-14 hang is GC08's (Lane B) and is not fixed here; the two N>1 cases are skipped naming G-14. Invariant 5.
6. D127115188's disableWAL and failed-append ingestion cases are not re-added: GC12's tests pin the same behaviours. Rule 5 (least code).
7. Q3's eviction test runs on `WritePreparedTransactionTest` at N=8 only (bypassed at N=1, where holding a prepare holds every write), because `wp_commit_cache_bits` is private to that fixture's friends. Rule 5.
8. Notes were read from the `JustinGaoNotesChanges` commit exported to `/tmp`; nothing under the notes directory was touched. Rule 2.
9. The racing-checkpoint hole is filed as a G-30 residual ("checkpoint and backup copy all N chains as a consistent set") rather than a new ID. Invariant 5 ("naming the checklist ID (or "new")").
10. The 100-repeat requirement covers every N=8 instance whose test body uses SyncPoint or fault injection, plus every new test at both N: 193 test instances. The other N=8 instances ran once each in two full passes. A body is selected if it mentions `SyncPoint`, `FaultInjection`, `fault_fs`/`fault_env` or `TEST_SYNC_POINT`. Rule 5.

## Not done
- Fixing the `snapshots_version_` race between leaders (new). Found here; GC10's owner.
- Q5's racing property is not met at N>1 (G-30 residual). Finding it is done here; the fix belongs to GC12's owner (D123079329).
- The opt-mode suite run (Assumption 4).

## Safety boundaries and unsupported cases
- Tests only. No production, public header, option or WAL-format change; `db_bench` output is byte-identical to the base (Test Plan).
- N=1 instances run with each suite's original options and assertions. The only N=1-visible change is the `WalPartitions1/` name prefix on the converted TEST_F tests.
- Open hazards, not covered here:
  - The `AfterGetLive1/2` sync points sit inside the N>1 quiesce: any future test that runs a write-queue operation from them deadlocks at N>1 (new; test-only).
  - G-14 (GC08) until Lane B is folded.
  - G-30 residual: checkpoint or backup racing another thread's `UnlockWAL` at N>1 (above).
  - New: `WritePreparedTxnDB` snapshot-list version race between partition leaders (above).
  - ldb commands that open the DB cannot open an N>1 DB (OPTIONS file drops the opt-in); tooling question for GC13/GC18.
  - G-55/N-3-5/muse #19/G-57/N-7-4 are GC14a's.

Test Plan:
All runs are on devvm dev builds of the final tree unless noted. "Final tree" is `caeba6be1b7f` plus the two invariant-5 skips (`CheckpointRacingLockWAL`, `CommitOfDelayedPrepared`), which add skips and change nothing else.

1. `buck2 test fbcode//internal_repo_rocksdb/repo:{checkpoint_test,backup_engine_test,wal_manager_test,db_secondary_test,repair_test,ldb_cmd_test,external_sst_file_test,external_sst_file_basic_test,transaction_test,write_prepared_transaction_test,write_unprepared_transaction_test,optimistic_transaction_test}`:
   - final tree: Pass 5535, Fail 0, Timeout 0, Fatal 0, Skip 7 (5 G-14 skips, the G-30 skip and the new-race skip).
   - `caeba6be1b7f`: Pass 5537, Fail 0, Timeout 0, Fatal 0, Skip 5 (the 5 G-14 skips). Exit 64 is tpx's code for "passes and skips".
2. Full pass, one process per test (every test in every suite, 24-way parallel): 0 failures and 0 timeouts. Per-suite N=1 and N>1 counts are in the Q1 table. checkpoint_test and write_prepared_transaction_test were re-run after the skips: 110 pass + 1 skip, and 918 pass + 11 skip.
3. Which N each test opens at: a temporary `GC14B_TRACE` line in `DBImpl::ValidateOptions` logged every open during an earlier full pass. Every passing N=8 test opened at N>1 only, except the by-design cases in Q1. The trace was reverted with `sl revert`, and the commit does not contain it.
4. TSan (`@fbcode//mode/dev-tsan`), on every `WalPartitions*` instance, both partitioned fixtures, and the edited N=1 tests (`DoubleCrashInRecovery`, `TwoPhaseLogRollingTest*`, `DirectWriteCommitPath`, `DuplicateKeys`, `MarkLogWithPrepSection`, `RollbackPreparedAfterCommitWriteFailure`). Results by suite:
   - checkpoint 95 pass + 1 skip (final);
   - backup 118;
   - wal_manager 8;
   - secondary 2;
   - repair 2;
   - ldb 2;
   - external_sst 154;
   - external_sst_basic 60 + 2 upstream skips;
   - optimistic 34;
   - write_unprepared 78 + 4 G-14 skips;
   - write_prepared 76 + 2 skips (final);
   - transaction 410 + 58 skips + 3 disabled.
   0 ThreadSanitizer reports. Before the skip, `WalPartitions8/WritePreparedTransactionTest.CommitOfDelayedPrepared/0` reported the race above. Excluded: `ExternalSSTFileBasicTestN.LargeSizeSstFileWriter`, an upstream big-memory test (4 GiB key and value) that OOM-killed the TSan run twice. It is not WAL-related and passes in dev.
5. `--gtest_repeat=100` on 193 test instances: every N=8 instance whose body uses SyncPoint or fault injection, plus every new test at both N (Assumption 10). This includes Q2's `ConcurrentPreparesAcrossPartitions` and every Q3/Q4/Q5 test. All passed except:
   - `WalPartitions8/CheckpointTest.CheckpointRacingLockWAL/0`: 1 of 100 failed. Isolated, 1 of 200 failed. This is the G-30 residual; the test is now skipped.
   - `CheckpointByLockWALHolder` and `CheckpointConcurrentWritesArePrefix` at N=8: one `RunWithin` 30 s abort each, on the first iteration, during a load average of about 2500. Isolated, each passed 200 of 200.
   - `WalPartitions8/ExternalSSTFileTestN.IngestFlushRequestNotLostBehindQueuedFlush/0` (upstream): 1 of 100 failed, on iteration 2, which took 335 s (the median is 1 s), in the same overload window, with the "Timed out waiting" hang guard. Isolated, it passed 300 of 300 at N=8 and 100 of 100 at N=1.
6. Neuters (each change applied, the run observed, the change reverted):
   - Q2: restore the old `PreparedHeap::push`. The test aborts on `heap_top_ < v`.
   - Q3: publish past the applied prefix. The held snapshot reads uncommitted "va".
   - Q3: skip the `delayed_prepared_` move. The eviction test reads uncommitted "va".
   - Q4: route every write to partition 0. The precondition fails.
   - Q4: skip the recovered `AddPrepared` rebuild. Recovered prepared data reads as committed.
   - Q5: drop the quiesce. Checkpoint copies fail with "unexplained hole" in 20 of 20 iterations; backup in 8 of 20.
   - WalManager: drop the peek. The N=8 call is not NotSupported.
   - Helper: make `SetWalPartitions` a no-op. The repair and checkpoint N=8 tests fail.
7. N=1 byte identity: dev-mode `db_bench --benchmarks=fillseq --num=10000 --seed=20260928 --threads=1 --disable_auto_compactions=1`, no flush before close, built from this commit and from the base. Recorded value: the SHA-256 of the live WAL (`000004.log`):
   - `partition_wal_usage=none`: `6d1351117a289a2784449a68d5421b1aa385ab0b383273c2c5918befa9181b09`
   - `partition_by_column_family`: `9a69a3fc66777fadce05e8a999479a5f57364aca27cd6d22aa00e4631adfc796`
   Both match the base. No production file changed.
8. Opt mode: not run, because it is impossible here (Assumption 4). fbcode marks `rocksdb_test_lib` incompatible with `@mode/opt`, and a `DEBUG_LEVEL=0` make of the test harness fails upstream.
9. Repo-pinned `tools/third-party/clang-format/clang-format-diff.py` (with `tools/third-party/clang-format/clang-format`) over `sl diff -r 01ebc084d2ed`: no changes. `arc lint -a` on every modified file: no issues. No non-ASCII characters.
TBD

Differential Revision: https://phabricator.intern.facebook.com/D127275775
fbsource-commit: db6612fbcbee
@JustinGaoF

Copy link
Copy Markdown
Owner Author

Folded at M3 into pwal/m3 (see M3-FoldTasks.md).

@JustinGaoF JustinGaoF closed this Oct 27, 2026
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 pushed a commit that referenced this pull request Nov 19, 2026
…#15710)

Summary:
Pull Request resolved: meta#15710

## Background

RocksDB deletes an SST file once it is obsolete, meaning no Version references it anymore, usually because a compaction replaced it. Files that a running flush or compaction is still writing are also in no Version, but they must not be deleted. To protect them, each flush or compaction records the next file number in `pending_outputs_` when it starts. The obsolete-file purge then skips every SST numbered at or above the smallest recorded number (`min_pending_output`, exposed as `rocksdb.min-obsolete-sst-number-to-keep`). The purge applies this cutoff to every SST: both files found by scanning the DB directories and files that `VersionSet` already knows are obsolete (`obsolete_files_`, filled when the last Version referencing a file is destroyed).

`53af5d877` ("Redesign pending_outputs_", 2014) introduced the cutoff, replacing tracking of each job's exact output file numbers. At first the cutoff was applied only in `PurgeObsoleteFiles()`. That leaked files: a file taken from `obsolete_files_` and then held back was neither deleted nor tracked until the next full directory scan. `863009b5a` ("Fix deleting obsolete files #2", 2015) fixed the leak by also applying the cutoff in `VersionSet::GetObsoleteFiles()`, so such files stay in `obsolete_files_` until the cutoff moves past them. A `FIXME` left in `PurgeObsoleteFiles()` asks whether these files should be held back at all. More recently, [meta#15490](meta#15490) stopped prepared external ingestions from holding a `pending_outputs_` entry. They now protect only their reserved file numbers, so a long-lived prepared ingestion no longer holds back unrelated obsolete SSTs.

## The problem

While a long-running job is in progress, obsolete SSTs pile up on disk. Every SST created after the job started and since compacted away is kept until the job finishes, even though none of them can be an unfinished output: each was part of an installed Version, so holding it back protects nothing. Usually the wait is short, but a remote compaction can wait in `CompactionService::Wait()` for hours or days. Under a steady write load, obsolete SSTs can then grow to many times the size of the live data and fill the disk; `rocksdb.obsolete-sst-files-size` shows the growth.

## Previous behavior

- `GetObsoleteFiles()` handed off only obsolete SSTs numbered below `min_pending_output`; the rest stayed in `obsolete_files_`.
- `PurgeObsoleteFiles()` kept every SST candidate numbered at or above `min_pending_output`, from either source.

## New behavior

The purge deletes an SST that `VersionSet` reports as obsolete, whatever jobs are still running, apart from a brief exception when event listeners are configured (below). `GetObsoleteFiles()` hands off all obsolete SSTs, and `PurgeObsoleteFiles()` applies the cutoff only to SST candidates that came from the directory scan. Both parts are needed: changing only `GetObsoleteFiles()` would bring back the 2015 leak.

Unchanged:
- Unfinished outputs are found only by the directory scan, so the cutoff still protects them.
- Inputs of a running compaction stay protected: the compaction holds a reference on its input Version, so they never reach `obsolete_files_`.
- Live files, including trivially moved ones, are still excluded by the live-file set and `only_delete_metadata`.
- Files quarantined after a failed MANIFEST write are still checked before anything else.
- Obsolete blob files still honor the cutoff. `VersionBuilder` can report a blob file obsolete without it having been part of an installed Version, so the argument above does not cover them.

## Keeping event listener outputs available

The cutoff also had a side effect that listeners can observe. A job removes its `pending_outputs_` entry only after its `OnFlushCompleted()` or `OnCompactionCompleted()` callbacks return, so RocksDB did not delete the files those callbacks report while the callbacks ran, even if another compaction made them obsolete in the meantime. `EventListener` did not document this, but a listener that opens, copies, or links a reported file might depend on it. Without the cutoff for known-obsolete files, such a listener could find the file already deleted.

To keep that behavior, this change keeps a narrower form of the cutoff for known-obsolete SSTs, in `DBImpl::listener_pending_outputs_`. While a job might still report its outputs to listeners, its `pending_outputs_` number is also registered there, and `GetObsoleteFiles()` leaves obsolete SSTs at or above the smallest registered number in `obsolete_files_` for a later purge. A compaction registers just before installing its outputs and unregisters after `OnCompactionCompleted()` returns, so a remote compaction holds nothing back while it waits. A flush registers for its whole duration, which also covers a flush that installs its outputs over several MANIFEST writes. Nothing is registered when no listeners are configured.

This change also documents the behavior in `listener.h`, as best effort rather than a guarantee: RocksDB actively avoids deleting a file before a callback that reports it returns. The documented exceptions predate this change: the inputs that `OnCompactionCompleted()` reports (including trivially moved files), and files reported to `OnExternalFileIngested()`, whose protection ends when the ingestion is committed, before the callback runs.

Registering a lower bound on file numbers, as `pending_outputs_` does, rather than the exact output file numbers is a deliberate compromise, because more precision has diminishing returns. With listeners configured, RocksDB therefore still keeps unrelated obsolete SSTs created after a job started while a flush runs or while a compaction's completion callbacks run. That retention lasts as long as a local flush or the callbacks, not as long as a compaction waits. Alternatives considered:
- Track the exact output file numbers. This alternative keeps only the reported files, but the numbers would have to be passed out of `MemTableList::TryInstallMemtableFlushResults()` and `CompactionJob::Install()` at each install site, roughly 2.5 to 3 times the code, only to delete some files a little sooner.
- Hold a reference on the current Version while listeners run. This alternative is simpler, but the reference is taken after the outputs are installed, so it misses a flush that installs its outputs over several MANIFEST writes if a compaction deletes an earlier output in between.
- Keep newly installed outputs from being picked by compactions until listeners have been notified. A slow listener would then block compaction of new L0 files.

## Consequences

- `rocksdb.min-obsolete-sst-number-to-keep` returns the same value as before, but now bounds only unrecognized files found by a directory scan, not known-obsolete SSTs (apart from the brief retention with listeners described above). Its documentation is updated. An application that read the property to decide which obsolete SSTs it could still copy or link out of band would be affected. Like meta#15490, this change adds no option to restore the previous behavior.
- Secondary instances, including remote compaction workers opened by `DB::OpenAndCompact()`, may find obsolete SSTs deleted sooner than before. They already handle this for files below the cutoff: they read the MANIFEST through `ManifestTailer`, which builds the most recent Version that has no missing files.

Bonus: `CLAUDE.md` gets guidance on keeping crash test checks for one feature cheap, so that they do not take time and operations away from finding other failures. The guidance comes from designing the `db_stress` check described in the test plan.

Reviewed By: jaykorean

Differential Revision: D130987455

fbshipit-source-id: 1ec9c7127bec6017a6742b98bb53dba45139e87d
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