Skip to content

[Muse][GC] GC29a: tests and docs independent of the write path - #32

Closed
JustinGaoF wants to merge 1 commit into
pwal/gc28-joinfrom
pwal/gc29a-muse
Closed

JustinGaoF wants to merge 1 commit into
pwal/gc28-joinfrom
pwal/gc29a-muse

Conversation

@JustinGaoF

Copy link
Copy Markdown
Owner

[GC] GC29a

Reviewer question: Does the oracle check published-but-lost by default and
prove it can fail, does the rollback procedure work as written from N>1, do
the tool help, the stripping refusal and the recovery comments match the
code, do the N=8 consumer legs drive more than one partition, and do the
partitioned transaction tests clean up on every exit?

Answer, in short: yes. Tests, the crash oracle, tool help, comments, option
docs, release notes and one refusal message only. No behaviour change: the
single non-comment production edit is the text of the N>1 stripping refusal
(Q3 (b)), same status code and trigger. N=1 is byte-identical in both usages
(see Test plan). Base pwal/gc28-join @ 266205c verified (41 commits,
tree 32485b54e49a).

Decisions taken as Recommended (all four Dispatcher's-choice cells were
blank): D-GC29a (i) disableWAL Put injection, no production hook; D-GC29b
(i) helper + spanning tests + one-line cannot-spread comments; D-GC29c (i)
new wal_partitions>1 stripping branch naming both options; D-GC29d (i)
prepare + no re-enable until step 7.

== Q1: oracle published check on by default (FU2) ==

Property: the prefix oracle checks "published but lost" on every
process-crash cycle by default, proves it can fail, and the error-handler
comment matches the wake-on-error code.

How: kCheckPublished defaults to true (ROCKSDB_WAL_ORACLE_CHECK_PUBLISHED=0
still overrides it off for diagnosis); header/run-summary/comments state the
property (publication bounded by the WAL-written prefix via
PublishAppliedFrontierLocked's debug assert; a process crash drops nothing
written). New self-test DBWalOracleTest.CatchesPublishedButLost runs
quiescent-crash cycles, injects one disableWAL Put on a covered column
family after the writers finish, and requires exactly the
published-sequence violation (no hole, no acked-lost line); the same cycles
without the injection pass. error_handler.cc comment now says every
background error wakes parked gates to recheck and a gate fails only on a
fence or at shutdown, naming wal_durability_wait_mutex_ (GC28 moved waiting
off sequence_wal_index_mutex_).

Evidence: RecoveredStateIsPrefixOfHistory passes with default 40 cycles,
check on; 1000-cycle oracle run passes (see Test plan).
Neuter: kCheckPublished=false with the variable unset: CatchesPublishedButLost
fails, no cycle caught (observed).

== Q2: rollback procedure works from N>1 (FU4) ==

Property: the documented rollback works as written from N>1, covering
archived WALs, a crash midway and an outstanding prepare.

How (R1 docs): step 1 sets wal_partitions=1 in the same reopen as kNone
(PartitionWALUsage comment + partition_wal_usage.md); procedure says to
commit/roll back every prepared transaction before step 3 and not to
re-enable partitioning until step 7 holds; wal_partitions option doc and
wal_partitions.md point at the procedure (own lines, no reflow).
Tests (new db_wal_test.cc block directly after
RollbackProcedureLeavesNoIndexedWAL; existing test untouched):
RollbackProcedureLeavesNoIndexedWALAtAnyPartitionCount (R2 end-to-end,
N in {1,4} x archive {off,on}; N=4 writes every partition with an
unflushed tail each; checks ldb check_wal_index exit 0 with archive,
guard clear, every key present, kNone N=1 open accepted; neuter leg
asserts step 1 without wal_partitions=1 gives the exact NotSupported),
RollbackProcedureCrashMidwayRepeatsToCompletion (R4 FaultInjectionTestFS
drop after first kNone reopen; reopens kNone N=1 with every key; repeat
from step 1 completes), RollbackProcedureWithPrepareOutstanding (R5
TransactionDB N=4; prepare outstanding at step 1: indexed WAL live,
check_wal_index non-zero, guard set; commit and rollback variants both
complete steps 3-7 with the transaction outcome correct; cites
GC26TrueAlternationFailsClosed instead of duplicating it).

Evidence: new tests pass at N in {1,4}.
Neuters, each run: (a) skip wal_partitions=1: neuter leg gets the
NotSupported, main leg fails; (b) skip guard-clearing reopen:
check_wal_index reports guard set, non-zero; (c) skip archive purge:
non-zero naming the archived file; (d) R5 skip the commit: indexed WAL
stays live, non-zero (observed; see Test plan).

== Q3: help, refusal and comments match the code (FU10) ==

(a) Tool help (L6): db_bench/db_stress --partition_wal_usage text now says
the value turns on WAL indexing and --wal_partitions sets how many WALs
writes spread across. Argued, not tested; --help output in Test plan.
(b) Stripping refusal (G3-C-4): new wal_partitions>1 branch in
ColumnFamilyData::ValidateOptions ahead of the upstream checks returns
NotSupported naming wal_partitions>1 and persist_user_defined_timestamps;
doc list gains the combination; N=1 unchanged (branch requires N>1; the
concurrent-memtable condition preserves the non-concurrent leg's upstream
message, and N>1 already requires concurrent writes). Only the two named
fragments change: GC26ColumnFamilyRefusalsHoldAfterOpen's stripping case
(CreateColumnFamily) and StrippingFlushNeverMeetsAMask's concurrent leg
(DB::Open). Neuter: branch removed: both fragment checks fail on the
upstream message (observed).
(c) Recovery-mode sentence (L5): verified the four texts agree with
ProcessLogFilesMerged's D-10 mapping at base (no GC27 change to it; no
mismatch found). The R3.2 notes-only id now names WALRecoveryMode and the
release note. Argued, not tested.
(d) "Recovery never forces a flush" (G3-B-5): comment now says the
declaration needs no flush and names the two cases that flush anyway
(merge skipped an unexplained discard; kNone opener recovers an indexed
set). Argued, not tested.
(e) Stripping test comment now says the test pins the refusal (read-mask
argument removed; name kept). Argued, not tested.
(f) No further staleness found in the same passages.

== Q4: Review-M3 T1, T2, T6, T7 ==

T1 (N=8 legs drive one partition): FIXED. New helper
CountWalPartitionsWithRecords (db_test_util.h/.cc: SyncWAL, then count
partitions whose current WALs hold data records via log::Reader; metadata
records are skipped by the reader so any data record counts). New spanning
tests in every WalPartitions8 suite that lacked one: ingestion (both
external_sst suites), optimistic commit, each writing CFs covering >=2
partitions, asserting >=2 appended, then running the suite's consumer. The
backup and checkpoint every-partition tests now assert via the helper.
wal_manager_test (synthetic files) and repair_test (RepairDB refuses
partitioned WALs) get one-line cannot-spread comments. testharness.h
comment states N=8 coverage. Neuter: default-CF-only writes: count
assertion fails (observed).
T2 (crash-fired-mid-run not recorded): FIXED. CycleResult records
crash_at vs events; summary prints per-trigger-kind mid-run counts;
RecoveredStateIsPrefixOfHistory fails when >=10 cycles ran and none
crashed mid-run. Neuter: crash_at past every cycle's events: assertion
fails with 0 mid-run (observed).
T6 (mixed-set rejection untested): VERIFIED CLOSED by GC26
(GC26TrueAlternationFailsClosed, db_write_test.cc). Record only.
T7 (failed writes never asserted absent): FIXED, assertions only.
FenceHidesFailedWriteFromWalIterator asserts failed reads NotFound while
stopped and after Resume() (refused here: WAL tracking, which N>1
requires, refuses WAL-write-error recovery, so the DB stays stopped),
then reopens and asserts the base outcome (value: the record landed whole
and D-1/GC26 Q1 recovers it) with the reason in a comment. Note the reopen
step is new but required by the spec to assert the reopen outcome; no
existing step or assertion changed. ChangeStreamStopsBelowHeldLowerWrite
asserts key_a and key_b both absent. Neuters: first test, skip the
recovery flush's drop at the fence: failed reads back after Resume()
(observed); second test: no production neuter exists; argued that a hole
above a lost record is what the assertion catches.

== Q5: Review-M3 Lows classified (no code) ==

L-d OPEN: listener can suppress a kMemTable error (D-1 override in
error_handler.cc covers kWriteCallback only); HandleMemTableInsertFailure
installs a released_by_recovery=false fence with no BG error set. Argued,
not tested.
L-f OPEN: WriteRecoverableState seeds from versions_->LastSequence()
without two write queues, i.e. every N>1 DB. Argued, not tested.
L-h CLOSED at base by GC28: RunSyncGate uses only the coalesced gate sync
(SyncWalsFromCompletionGate) with the Q2 fallback (non-thread-safe files
fsynced under the partition mutex); the second-round SyncWAL is gone (Q3);
the remaining SyncWAL callers (WriteImpl two_write_queues leg,
WriteImplWALOnly) are unreachable at N>1 (both options refused). Public
SyncWAL() still returns NotSupported fail-closed to direct callers. GC30
may change this code; owner re-checks after the join. Argued, not tested.
L-i OPEN: parked write returns ShutdownInProgress("parked write") after
CancelAllBackgroundWork without Close, though under D-9 it parked
post-append+insert and will be recovered. Argued, not tested.

== Q6: partitioned transaction tests clean up (test Low) ==

Property: every TransactionPartitionedWalTest test and FU14SnapshotRace
releases transactions/DB and disables+clears SyncPoint state on every exit.

How: Defer guards (+ unique_ptr/destructor where they fit); only ownership
and cleanup changed, no step or assertion, none weakened or removed.

Evidence: scratch ASSERT failure injected after EnableProcessing in
FailedSyncPrepareLeavesNoStaleFence, TransactionPartitionedWalTest.* under
ASan --gtest_repeat=2: both repeats fail as expected with no sanitizer
report (clean run: 12/12 twice before injection). Neuter: guard dropped
(file hash verified changed, d311672e -> 00e9fe8b): both repeats fail and
LeakSanitizer reports the leaked open DB. File restored to hash d311672e,
no scratch markers remain (verified).

== Q7: GC27 carry-overs ==

Not done (no room; listed under Not done).

== Existing tests changed ==

  • db/db_write_test.cc (GC30 owner-set exceptions): FenceHidesFailedWriteFromWalIterator and ChangeStreamStopsBelowHeldLowerWrite gain T7 assertions only, no existing step/assertion changed; StrippingFlushNeverMeetsAMask gains the Q3 (b) fragment and the Q3 (e) comment; GC26ColumnFamilyRefusalsHoldAfterOpen gains the Q3 (b) fragment. No test added to this file.
  • utilities/transactions/transaction_test.cc (GC30 owner-set exception): the 12 TransactionPartitionedWalTest tests and FU14SnapshotRace change only DB/transaction/SyncPoint ownership and cleanup; no step or assertion changed.
  • utilities/backup/backup_engine_test.cc, utilities/checkpoint/checkpoint_test.cc: the existing every-partition tests now assert through CountWalPartitionsWithRecords.
  • db/db_wal_oracle_test.cc: kCheckPublished default, header/summary/comment text, mid-run recording; existing self-tests unchanged in shape.
  • All other touched test files gain new tests or one-line comments only.

== Fold-back split (git blame at base + Differential Revision) ==

  • Q1: db_wal_oracle_test.cc -> D126533193; error_handler.cc comment -> D123701876.
  • Q2: PartitionWALUsage comment -> D118367634; partition_wal_usage.md -> D126533192; wal_partitions option-doc pointer and doc list -> D117251769 (GC27 split: wal_partitions paragraphs -> D117251769); wal_partitions.md -> the GC18 flip standalone (no Differential Revision); new rollback tests -> new code, D126533192.
  • Q3: (a) tool help -> D118371518; (b) column_family.cc branch and doc list -> D117251769, test fragments -> D123928339 (both tests); (c) R3.2 comment -> D120649665; (d) flush comment -> D120415420; (e) test comment -> D123928339.
  • Q4: T1 -> D127275775 (helper is new code serving it); T2 -> D126533193; T7 FenceHidesFailedWriteFromWalIterator -> D127093323, ChangeStreamStopsBelowHeldLowerWrite -> D123928339; T6 -> none.
  • Q5: none (no hunk).
  • Q6: each test's own diff: SwitchWALFindsOldestWalAcrossPartitions and the FU14SnapshotRace helper -> D123971668; PreparedUnindexedWalSurvivesPartitioning and SyncPrepareAfterSyncCommitSurvivesCrash -> D123928339; SnapshotCommitPublishesAboveHeldLowerWrite and FailedSyncPrepareLeavesNoStaleFence -> D123701876; EmptyDisableWalCommitSnapshotIsPublished, FU14TimestampedSnapshotListStaysSorted, FU14TimestampedSnapshotSurvivesCompaction, GC22TimestampedSnapshotReservedBeforePublish, GC22TimestampedSnapshotsOutOfSequenceOrder -> D123551605; GC23SnapshotReservationInProperties and GC23TimestampedSnapshotsSurviveFlushStress -> D127275775.

== Assumptions ==

  • All four blank decision cells taken as Recommended (D-GC29a (i), D-GC29b (i), D-GC29c (i), D-GC29d (i)); no questions asked.
  • GC28 moved parked-gate waiting off sequence_wal_index_mutex_; the wake at base takes wal_durability_wait_mutex_ (error_handler.cc comment names it).
  • T1 helper counts data records via log::Reader: the reader skips metadata records, so any data record in a partition's current WALs counts it.
  • Q2 R5 is a sibling test in the same new db_wal_test.cc block (spec's "yours to decide").
  • Q2 N=4 archive leg purges the archive by deletion (MockSleep would leak the clock); N=4 no-archive leg retires at the step-1 merge flush.
  • Q3 (b) branch conditions on allow_concurrent_memtable_write so the non-concurrent leg keeps the upstream message; N>1 requires concurrent writes, so the trigger is unchanged.
  • T7's reopen step in FenceHidesFailedWriteFromWalIterator is required to assert the reopen outcome; no existing step or assertion changed.
  • Where GC27/GC28 already changed a cited line, its version is kept and only what is still wrong is fixed.

== Not done ==

  • Q7: GC27RecordCutAtSeedSupersedesFromSeed; db_tailing_iter_test at wal_partitions=8 (not run, no room); ImportWaitsForPendingSyncGroup; GC27PerRecordInsertFailureBelowPendingReportStopsPIT; oracle "explanation void lands, then crash" mode (1000 cycles, N in {2,8}); writers' Corruption returns in a release (NDEBUG) build: cannot be built, the test harness is debug-only (db_test_util.cc fails in release: SyncPoint undeclared and DBImpl TEST_* methods absent under NDEBUG; the same Corruption-return behaviour is pinned by WALIndexMissingAssignmentFailsWrite and WALIndexNonIncreasingFailsWrite in debug). Each other item needs a test, a neuter, TSan and (for SyncPoint ones) 100 repeats; no room in this round.
  • GC29b items (notes-only ids other than R3.2, LOCK ORDER audit, T3-T5, vacuous two_write_queues legs, GC25 ports) not started, as specified.

== Test plan ==

Base: git rev-parse HEAD = 266205c;
git rev-list --count d6a7847..HEAD = 41; tree 32485b54e49a; status
clean before branching. All builds/tests use J=41 (nproc/4) and
TEST_TMPDIR=~/pwal-3p/gc-29a-muse-tmp. That tmp dir was deleted externally
twice during this job; byte identity was re-run from scratch afterwards
(hashes reproduced exactly) and the Q6 restore was hash-verified, so no
result below depends on a lost log file.

  1. Final debug rerun (this session): python3 build_tools/gtest-parallel
    -w 41 over db_write_test, db_wal_test, db_wal_oracle_test,
    transaction_test, optimistic_transaction_test, backup_engine_test,
    checkpoint_test, external_sst_file_test, external_sst_file_basic_test,
    wal_manager_test, repair_test, ldb_cmd_test, db_options_test,
    column_family_test, db_with_timestamp_basic_test: 8197/8197 tests,
    GTEST_PARALLEL_EXIT=0, 0 FAILED lines. No singly reruns needed.
  2. Earlier full debug run (same diff, before mode switches): 8197 tests,
    12 failed (11 timeout/load flakes, each green singly; MergeMiniStress/3
    killed under load in fallocate/futex, then passed singly).
  3. Oracle: RecoveredStateIsPrefixOfHistory passes at default 40 cycles
    with the check on. 1000-cycle run: 140093 acked, 138622 recovered,
    129 holes, 0 published-lost, 927 crashed mid-run. TSan 40-cycle run
    summary: crashed mid-run in 36 (ack 9, append 5, gate_sync 10, park 12).
  4. TSan (USE_CLANG=1 COMPILE_WITH_TSAN=1): build exit 0; db_wal_test
    rollback tests, db_write_test T7/strip tests, transaction_test Q6
    tests, oracle, ingestion, optimistic, backup, checkpoint suites pass,
    no ThreadSanitizer reports.
  5. Repeats 100x: fence, change-stream, crash-midway, Q6 transaction
    tests pass (Q6 100/100 on the third attempt; two earlier attempts
    wedged in fallocate/futex under host load and were killed).
  6. Neuters: Q1 (kCheckPublished=false: CatchesPublishedButLost fails);
    Q2 (a)-(d) as described in Q2; Q3 (b) (branch removed: both fragment
    checks fail on the upstream message); T1 (default-CF-only: count
    fails); T2 (crash_at past all events: 0 mid-run, assertion fails);
    T7 first test (skip recovery flush's fence drop: failed reads back
    after Resume()); Q6 (guard dropped: LSAN leak report, see 7).
  7. Q6 ASan (COMPILE_WITH_ASAN=1 COMPILE_WITH_UBSAN=1): clean
    TransactionPartitionedWalTest.* --gtest_repeat=2: 12/12 twice, no
    sanitizer output. Injected ASSERT failure + dropped guard: both
    repeats fail, LeakSanitizer reports the leaked open DB. Restored to
    sha256 d311672e..., 0 scratch markers, diff 109/20.
  8. Byte identity (release db_bench fillseq, threads=1, num=10000,
    seed=20260928, disable_auto_compactions=1): usage none, *.log SHA-256
    base 6d1351117a289a2784449a68d5421b1aa385ab0b383273c2c5918befa9181b09
    == commit 6d1351117a289a2784449a68d5421b1aa385ab0b383273c2c5918befa9181b09;
    usage partition_by_column_family, base
    9a69a3fc66777fadce05e8a999479a5f57364aca27cd6d22aa00e4631adfc796 ==
    commit 9a69a3fc66777fadce05e8a999479a5f57364aca27cd6d22aa00e4631adfc796.
    Reproduced in a second independent pair of runs with identical hashes.
    Release log_test is not buildable (see Not done); no release test run.
  9. Help text: ./db_bench --help and ./db_stress --help both print
    "-partition_wal_usage (WAL record ordering. 'none' to disable (vanilla
    WAL format); 'partition_by_column_family' to turn on WAL indexing,
    tagging each WAL record with an ordering number. --wal_partitions sets
    how many WAL files writes spread across.)".
  10. Formatting: make check-format exit 0 (clang-format 21.1.2, "Nothing
    needs to be reformatted!"); make check-sources exit 0.

[GC] GC29a

Reviewer question: Does the oracle check published-but-lost by default and
prove it can fail, does the rollback procedure work as written from N>1, do
the tool help, the stripping refusal and the recovery comments match the
code, do the N=8 consumer legs drive more than one partition, and do the
partitioned transaction tests clean up on every exit?

Answer, in short: yes. Tests, the crash oracle, tool help, comments, option
docs, release notes and one refusal message only. No behaviour change: the
single non-comment production edit is the text of the N>1 stripping refusal
(Q3 (b)), same status code and trigger. N=1 is byte-identical in both usages
(see Test plan). Base pwal/gc28-join @ 266205c verified (41 commits,
tree 32485b5).

Decisions taken as Recommended (all four Dispatcher's-choice cells were
blank): D-GC29a (i) disableWAL Put injection, no production hook; D-GC29b
(i) helper + spanning tests + one-line cannot-spread comments; D-GC29c (i)
new wal_partitions>1 stripping branch naming both options; D-GC29d (i)
prepare + no re-enable until step 7.

== Q1: oracle published check on by default (FU2) ==

Property: the prefix oracle checks "published but lost" on every
process-crash cycle by default, proves it can fail, and the error-handler
comment matches the wake-on-error code.

How: kCheckPublished defaults to true (ROCKSDB_WAL_ORACLE_CHECK_PUBLISHED=0
still overrides it off for diagnosis); header/run-summary/comments state the
property (publication bounded by the WAL-written prefix via
PublishAppliedFrontierLocked's debug assert; a process crash drops nothing
written). New self-test DBWalOracleTest.CatchesPublishedButLost runs
quiescent-crash cycles, injects one disableWAL Put on a covered column
family after the writers finish, and requires exactly the
published-sequence violation (no hole, no acked-lost line); the same cycles
without the injection pass. error_handler.cc comment now says every
background error wakes parked gates to recheck and a gate fails only on a
fence or at shutdown, naming wal_durability_wait_mutex_ (GC28 moved waiting
off sequence_wal_index_mutex_).

Evidence: RecoveredStateIsPrefixOfHistory passes with default 40 cycles,
check on; 1000-cycle oracle run passes (see Test plan).
Neuter: kCheckPublished=false with the variable unset: CatchesPublishedButLost
fails, no cycle caught (observed).

== Q2: rollback procedure works from N>1 (FU4) ==

Property: the documented rollback works as written from N>1, covering
archived WALs, a crash midway and an outstanding prepare.

How (R1 docs): step 1 sets wal_partitions=1 in the same reopen as kNone
(PartitionWALUsage comment + partition_wal_usage.md); procedure says to
commit/roll back every prepared transaction before step 3 and not to
re-enable partitioning until step 7 holds; wal_partitions option doc and
wal_partitions.md point at the procedure (own lines, no reflow).
Tests (new db_wal_test.cc block directly after
RollbackProcedureLeavesNoIndexedWAL; existing test untouched):
RollbackProcedureLeavesNoIndexedWALAtAnyPartitionCount (R2 end-to-end,
N in {1,4} x archive {off,on}; N=4 writes every partition with an
unflushed tail each; checks ldb check_wal_index exit 0 with archive,
guard clear, every key present, kNone N=1 open accepted; neuter leg
asserts step 1 without wal_partitions=1 gives the exact NotSupported),
RollbackProcedureCrashMidwayRepeatsToCompletion (R4 FaultInjectionTestFS
drop after first kNone reopen; reopens kNone N=1 with every key; repeat
from step 1 completes), RollbackProcedureWithPrepareOutstanding (R5
TransactionDB N=4; prepare outstanding at step 1: indexed WAL live,
check_wal_index non-zero, guard set; commit and rollback variants both
complete steps 3-7 with the transaction outcome correct; cites
GC26TrueAlternationFailsClosed instead of duplicating it).

Evidence: new tests pass at N in {1,4}.
Neuters, each run: (a) skip wal_partitions=1: neuter leg gets the
NotSupported, main leg fails; (b) skip guard-clearing reopen:
check_wal_index reports guard set, non-zero; (c) skip archive purge:
non-zero naming the archived file; (d) R5 skip the commit: indexed WAL
stays live, non-zero (observed; see Test plan).

== Q3: help, refusal and comments match the code (FU10) ==

(a) Tool help (L6): db_bench/db_stress --partition_wal_usage text now says
the value turns on WAL indexing and --wal_partitions sets how many WALs
writes spread across. Argued, not tested; --help output in Test plan.
(b) Stripping refusal (G3-C-4): new wal_partitions>1 branch in
ColumnFamilyData::ValidateOptions ahead of the upstream checks returns
NotSupported naming wal_partitions>1 and persist_user_defined_timestamps;
doc list gains the combination; N=1 unchanged (branch requires N>1; the
concurrent-memtable condition preserves the non-concurrent leg's upstream
message, and N>1 already requires concurrent writes). Only the two named
fragments change: GC26ColumnFamilyRefusalsHoldAfterOpen's stripping case
(CreateColumnFamily) and StrippingFlushNeverMeetsAMask's concurrent leg
(DB::Open). Neuter: branch removed: both fragment checks fail on the
upstream message (observed).
(c) Recovery-mode sentence (L5): verified the four texts agree with
ProcessLogFilesMerged's D-10 mapping at base (no GC27 change to it; no
mismatch found). The R3.2 notes-only id now names WALRecoveryMode and the
release note. Argued, not tested.
(d) "Recovery never forces a flush" (G3-B-5): comment now says the
declaration needs no flush and names the two cases that flush anyway
(merge skipped an unexplained discard; kNone opener recovers an indexed
set). Argued, not tested.
(e) Stripping test comment now says the test pins the refusal (read-mask
argument removed; name kept). Argued, not tested.
(f) No further staleness found in the same passages.

== Q4: Review-M3 T1, T2, T6, T7 ==

T1 (N=8 legs drive one partition): FIXED. New helper
CountWalPartitionsWithRecords (db_test_util.h/.cc: SyncWAL, then count
partitions whose current WALs hold data records via log::Reader; metadata
records are skipped by the reader so any data record counts). New spanning
tests in every WalPartitions8 suite that lacked one: ingestion (both
external_sst suites), optimistic commit, each writing CFs covering >=2
partitions, asserting >=2 appended, then running the suite's consumer. The
backup and checkpoint every-partition tests now assert via the helper.
wal_manager_test (synthetic files) and repair_test (RepairDB refuses
partitioned WALs) get one-line cannot-spread comments. testharness.h
comment states N=8 coverage. Neuter: default-CF-only writes: count
assertion fails (observed).
T2 (crash-fired-mid-run not recorded): FIXED. CycleResult records
crash_at vs events; summary prints per-trigger-kind mid-run counts;
RecoveredStateIsPrefixOfHistory fails when >=10 cycles ran and none
crashed mid-run. Neuter: crash_at past every cycle's events: assertion
fails with 0 mid-run (observed).
T6 (mixed-set rejection untested): VERIFIED CLOSED by GC26
(GC26TrueAlternationFailsClosed, db_write_test.cc). Record only.
T7 (failed writes never asserted absent): FIXED, assertions only.
FenceHidesFailedWriteFromWalIterator asserts failed reads NotFound while
stopped and after Resume() (refused here: WAL tracking, which N>1
requires, refuses WAL-write-error recovery, so the DB stays stopped),
then reopens and asserts the base outcome (value: the record landed whole
and D-1/GC26 Q1 recovers it) with the reason in a comment. Note the reopen
step is new but required by the spec to assert the reopen outcome; no
existing step or assertion changed. ChangeStreamStopsBelowHeldLowerWrite
asserts key_a and key_b both absent. Neuters: first test, skip the
recovery flush's drop at the fence: failed reads back after Resume()
(observed); second test: no production neuter exists; argued that a hole
above a lost record is what the assertion catches.

== Q5: Review-M3 Lows classified (no code) ==

L-d OPEN: listener can suppress a kMemTable error (D-1 override in
error_handler.cc covers kWriteCallback only); HandleMemTableInsertFailure
installs a released_by_recovery=false fence with no BG error set. Argued,
not tested.
L-f OPEN: WriteRecoverableState seeds from versions_->LastSequence()
without two write queues, i.e. every N>1 DB. Argued, not tested.
L-h CLOSED at base by GC28: RunSyncGate uses only the coalesced gate sync
(SyncWalsFromCompletionGate) with the Q2 fallback (non-thread-safe files
fsynced under the partition mutex); the second-round SyncWAL is gone (Q3);
the remaining SyncWAL callers (WriteImpl two_write_queues leg,
WriteImplWALOnly) are unreachable at N>1 (both options refused). Public
SyncWAL() still returns NotSupported fail-closed to direct callers. GC30
may change this code; owner re-checks after the join. Argued, not tested.
L-i OPEN: parked write returns ShutdownInProgress("parked write") after
CancelAllBackgroundWork without Close, though under D-9 it parked
post-append+insert and will be recovered. Argued, not tested.

== Q6: partitioned transaction tests clean up (test Low) ==

Property: every TransactionPartitionedWalTest test and FU14SnapshotRace
releases transactions/DB and disables+clears SyncPoint state on every exit.

How: Defer guards (+ unique_ptr/destructor where they fit); only ownership
and cleanup changed, no step or assertion, none weakened or removed.

Evidence: scratch ASSERT failure injected after EnableProcessing in
FailedSyncPrepareLeavesNoStaleFence, TransactionPartitionedWalTest.* under
ASan --gtest_repeat=2: both repeats fail as expected with no sanitizer
report (clean run: 12/12 twice before injection). Neuter: guard dropped
(file hash verified changed, d311672e -> 00e9fe8b): both repeats fail and
LeakSanitizer reports the leaked open DB. File restored to hash d311672e,
no scratch markers remain (verified).

== Q7: GC27 carry-overs ==

Not done (no room; listed under Not done).

== Existing tests changed ==

- db/db_write_test.cc (GC30 owner-set exceptions): FenceHidesFailedWriteFromWalIterator and ChangeStreamStopsBelowHeldLowerWrite gain T7 assertions only, no existing step/assertion changed; StrippingFlushNeverMeetsAMask gains the Q3 (b) fragment and the Q3 (e) comment; GC26ColumnFamilyRefusalsHoldAfterOpen gains the Q3 (b) fragment. No test added to this file.
- utilities/transactions/transaction_test.cc (GC30 owner-set exception): the 12 TransactionPartitionedWalTest tests and FU14SnapshotRace change only DB/transaction/SyncPoint ownership and cleanup; no step or assertion changed.
- utilities/backup/backup_engine_test.cc, utilities/checkpoint/checkpoint_test.cc: the existing every-partition tests now assert through CountWalPartitionsWithRecords.
- db/db_wal_oracle_test.cc: kCheckPublished default, header/summary/comment text, mid-run recording; existing self-tests unchanged in shape.
- All other touched test files gain new tests or one-line comments only.

== Fold-back split (git blame at base + Differential Revision) ==

- Q1: db_wal_oracle_test.cc -> D126533193; error_handler.cc comment -> D123701876.
- Q2: PartitionWALUsage comment -> D118367634; partition_wal_usage.md -> D126533192; wal_partitions option-doc pointer and doc list -> D117251769 (GC27 split: wal_partitions paragraphs -> D117251769); wal_partitions.md -> the GC18 flip standalone (no Differential Revision); new rollback tests -> new code, D126533192.
- Q3: (a) tool help -> D118371518; (b) column_family.cc branch and doc list -> D117251769, test fragments -> D123928339 (both tests); (c) R3.2 comment -> D120649665; (d) flush comment -> D120415420; (e) test comment -> D123928339.
- Q4: T1 -> D127275775 (helper is new code serving it); T2 -> D126533193; T7 FenceHidesFailedWriteFromWalIterator -> D127093323, ChangeStreamStopsBelowHeldLowerWrite -> D123928339; T6 -> none.
- Q5: none (no hunk).
- Q6: each test's own diff: SwitchWALFindsOldestWalAcrossPartitions and the FU14SnapshotRace helper -> D123971668; PreparedUnindexedWalSurvivesPartitioning and SyncPrepareAfterSyncCommitSurvivesCrash -> D123928339; SnapshotCommitPublishesAboveHeldLowerWrite and FailedSyncPrepareLeavesNoStaleFence -> D123701876; EmptyDisableWalCommitSnapshotIsPublished, FU14TimestampedSnapshotListStaysSorted, FU14TimestampedSnapshotSurvivesCompaction, GC22TimestampedSnapshotReservedBeforePublish, GC22TimestampedSnapshotsOutOfSequenceOrder -> D123551605; GC23SnapshotReservationInProperties and GC23TimestampedSnapshotsSurviveFlushStress -> D127275775.

== Assumptions ==

- All four blank decision cells taken as Recommended (D-GC29a (i), D-GC29b (i), D-GC29c (i), D-GC29d (i)); no questions asked.
- GC28 moved parked-gate waiting off sequence_wal_index_mutex_; the wake at base takes wal_durability_wait_mutex_ (error_handler.cc comment names it).
- T1 helper counts data records via log::Reader: the reader skips metadata records, so any data record in a partition's current WALs counts it.
- Q2 R5 is a sibling test in the same new db_wal_test.cc block (spec's "yours to decide").
- Q2 N=4 archive leg purges the archive by deletion (MockSleep would leak the clock); N=4 no-archive leg retires at the step-1 merge flush.
- Q3 (b) branch conditions on allow_concurrent_memtable_write so the non-concurrent leg keeps the upstream message; N>1 requires concurrent writes, so the trigger is unchanged.
- T7's reopen step in FenceHidesFailedWriteFromWalIterator is required to assert the reopen outcome; no existing step or assertion changed.
- Where GC27/GC28 already changed a cited line, its version is kept and only what is still wrong is fixed.

== Not done ==

- Q7: GC27RecordCutAtSeedSupersedesFromSeed; db_tailing_iter_test at wal_partitions=8 (not run, no room); ImportWaitsForPendingSyncGroup; GC27PerRecordInsertFailureBelowPendingReportStopsPIT; oracle "explanation void lands, then crash" mode (1000 cycles, N in {2,8}); writers' Corruption returns in a release (NDEBUG) build: cannot be built, the test harness is debug-only (db_test_util.cc fails in release: SyncPoint undeclared and DBImpl TEST_* methods absent under NDEBUG; the same Corruption-return behaviour is pinned by WALIndexMissingAssignmentFailsWrite and WALIndexNonIncreasingFailsWrite in debug). Each other item needs a test, a neuter, TSan and (for SyncPoint ones) 100 repeats; no room in this round.
- GC29b items (notes-only ids other than R3.2, LOCK ORDER audit, T3-T5, vacuous two_write_queues legs, GC25 ports) not started, as specified.

== Test plan ==

Base: git rev-parse HEAD = 266205c;
git rev-list --count d6a7847..HEAD = 41; tree 32485b5; status
clean before branching. All builds/tests use J=41 (nproc/4) and
TEST_TMPDIR=~/pwal-3p/gc-29a-muse-tmp. That tmp dir was deleted externally
twice during this job; byte identity was re-run from scratch afterwards
(hashes reproduced exactly) and the Q6 restore was hash-verified, so no
result below depends on a lost log file.

1. Final debug rerun (this session): python3 build_tools/gtest-parallel
   -w 41 over db_write_test, db_wal_test, db_wal_oracle_test,
   transaction_test, optimistic_transaction_test, backup_engine_test,
   checkpoint_test, external_sst_file_test, external_sst_file_basic_test,
   wal_manager_test, repair_test, ldb_cmd_test, db_options_test,
   column_family_test, db_with_timestamp_basic_test: 8197/8197 tests,
   GTEST_PARALLEL_EXIT=0, 0 FAILED lines. No singly reruns needed.
2. Earlier full debug run (same diff, before mode switches): 8197 tests,
   12 failed (11 timeout/load flakes, each green singly; MergeMiniStress/3
   killed under load in fallocate/futex, then passed singly).
3. Oracle: RecoveredStateIsPrefixOfHistory passes at default 40 cycles
   with the check on. 1000-cycle run: 140093 acked, 138622 recovered,
   129 holes, 0 published-lost, 927 crashed mid-run. TSan 40-cycle run
   summary: crashed mid-run in 36 (ack 9, append 5, gate_sync 10, park 12).
4. TSan (USE_CLANG=1 COMPILE_WITH_TSAN=1): build exit 0; db_wal_test
   rollback tests, db_write_test T7/strip tests, transaction_test Q6
   tests, oracle, ingestion, optimistic, backup, checkpoint suites pass,
   no ThreadSanitizer reports.
5. Repeats 100x: fence, change-stream, crash-midway, Q6 transaction
   tests pass (Q6 100/100 on the third attempt; two earlier attempts
   wedged in fallocate/futex under host load and were killed).
6. Neuters: Q1 (kCheckPublished=false: CatchesPublishedButLost fails);
   Q2 (a)-(d) as described in Q2; Q3 (b) (branch removed: both fragment
   checks fail on the upstream message); T1 (default-CF-only: count
   fails); T2 (crash_at past all events: 0 mid-run, assertion fails);
   T7 first test (skip recovery flush's fence drop: failed reads back
   after Resume()); Q6 (guard dropped: LSAN leak report, see 7).
7. Q6 ASan (COMPILE_WITH_ASAN=1 COMPILE_WITH_UBSAN=1): clean
   TransactionPartitionedWalTest.* --gtest_repeat=2: 12/12 twice, no
   sanitizer output. Injected ASSERT failure + dropped guard: both
   repeats fail, LeakSanitizer reports the leaked open DB. Restored to
   sha256 d311672e..., 0 scratch markers, diff 109/20.
8. Byte identity (release db_bench fillseq, threads=1, num=10000,
   seed=20260928, disable_auto_compactions=1): usage none, *.log SHA-256
   base 6d1351117a289a2784449a68d5421b1aa385ab0b383273c2c5918befa9181b09
   == commit 6d1351117a289a2784449a68d5421b1aa385ab0b383273c2c5918befa9181b09;
   usage partition_by_column_family, base
   9a69a3fc66777fadce05e8a999479a5f57364aca27cd6d22aa00e4631adfc796 ==
   commit 9a69a3fc66777fadce05e8a999479a5f57364aca27cd6d22aa00e4631adfc796.
   Reproduced in a second independent pair of runs with identical hashes.
   Release log_test is not buildable (see Not done); no release test run.
9. Help text: ./db_bench --help and ./db_stress --help both print
   "-partition_wal_usage (WAL record ordering. 'none' to disable (vanilla
   WAL format); 'partition_by_column_family' to turn on WAL indexing,
   tagging each WAL record with an ordering number. --wal_partitions sets
   how many WAL files writes spread across.)".
10. Formatting: make check-format exit 0 (clang-format 21.1.2, "Nothing
    needs to be reformatted!"); make check-sources exit 0.
@JustinGaoF

Copy link
Copy Markdown
Owner Author

GC29a A/B round: the other candidate (#31) was accepted. Closing this one; its commit is kept as pwal/ab/gc29a-muse-PR32.

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

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

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

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

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

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

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

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

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

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

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

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

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

M1: absorbs GC03 (all 19: SyncWal claim + `claimed` filter,
`TEST_WalSyncMarks`, `DBWALSyncMarkOwnershipTest`,
`SyncClosedWalsEmptiedByWaitLeavesLaterMark`,
`LeadershipSyncFinishesMarksPastHorizon`), GC13 Q3/Q5/Q6 (25: leadership
claim bool + unsynced count, `wal_sync_claimed`/`wal_sync_up_to` record,
gate wait, fan-out + `synced_size` advance,
`RunCompletionGate(sync_micros)`, sync barrier; tests
`SyncFanoutAndMutexHistograms`, `WalPartitionHistogramsSilentAtN1`), GC15
Q5 comments (2). Hand-ported inline per X11; D123971668 must re-extract
as a pure move. `kWalPartitionsRejection` updated to this diff's wording
(X10). Exceptions: `TEST_WalSyncMarks` decl after
`TEST_GetWalMergeBuffer` (public TEST block; D123928339 inserts
`TEST_AliveWalFiles`/`TEST_CurrentWalNumber` before it to match T0);
GC13#159 claim-decl change rides the D123971668 extraction. Gate:
lib builds; `db_write_test` 133/0 (5 new); `DBWALSyncMarkOwnershipTest`
4/4; `db_options_test` 55/0; `MixedSyncWritesCompleteUnderConcurrency`
x1000 (run during fold, result in M1 record).
M1 re-verification (2026-10-20, after rebasing the stack onto master f0c3a35689fc and clang-formatting): per-diff gate at this diff passed (CI format check, `rocksdb_lib` build, touched test targets); tip suites 8126/0; N=1 byte identity equals T0.

M2 fold: new or moved tests here: WalPartitionsRejectionsNameTheirOptions, IngestionThenWritesKeepLastSequenceMonotone. B.1 at this diff (format check, `rocksdb_lib`, touched test targets): PASS; db_options_test + db_wal_test + db_write_test 2271 pass.

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

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

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

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

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

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

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

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

Subscribers: jewoongh, rbanerjee2

Differential Revision: https://phabricator.intern.facebook.com/D123551605
JustinGaoF added a commit that referenced this pull request Nov 10, 2026
…M2.6)

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

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

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

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

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

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

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

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

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

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

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

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

M1: absorbs GC03 (all 19: SyncWal claim + `claimed` filter,
`TEST_WalSyncMarks`, `DBWALSyncMarkOwnershipTest`,
`SyncClosedWalsEmptiedByWaitLeavesLaterMark`,
`LeadershipSyncFinishesMarksPastHorizon`), GC13 Q3/Q5/Q6 (25: leadership
claim bool + unsynced count, `wal_sync_claimed`/`wal_sync_up_to` record,
gate wait, fan-out + `synced_size` advance,
`RunCompletionGate(sync_micros)`, sync barrier; tests
`SyncFanoutAndMutexHistograms`, `WalPartitionHistogramsSilentAtN1`), GC15
Q5 comments (2). Hand-ported inline per X11; D123971668 must re-extract
as a pure move. `kWalPartitionsRejection` updated to this diff's wording
(X10). Exceptions: `TEST_WalSyncMarks` decl after
`TEST_GetWalMergeBuffer` (public TEST block; D123928339 inserts
`TEST_AliveWalFiles`/`TEST_CurrentWalNumber` before it to match T0);
GC13#159 claim-decl change rides the D123971668 extraction. Gate:
lib builds; `db_write_test` 133/0 (5 new); `DBWALSyncMarkOwnershipTest`
4/4; `db_options_test` 55/0; `MixedSyncWritesCompleteUnderConcurrency`
x1000 (run during fold, result in M1 record).
M1 re-verification (2026-10-20, after rebasing the stack onto master f0c3a35689fc and clang-formatting): per-diff gate at this diff passed (CI format check, `rocksdb_lib` build, touched test targets); tip suites 8126/0; N=1 byte identity equals T0.

M2 fold: new or moved tests here: WalPartitionsRejectionsNameTheirOptions, IngestionThenWritesKeepLastSequenceMonotone. B.1 at this diff (format check, `rocksdb_lib`, touched test targets): PASS; db_options_test + db_wal_test + db_write_test 2271 pass.

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

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

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

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

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

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

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

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

Subscribers: jewoongh, rbanerjee2

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

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

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

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

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

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

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

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

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

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

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

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

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

M1: absorbs GC03 (all 19: SyncWal claim + `claimed` filter,
`TEST_WalSyncMarks`, `DBWALSyncMarkOwnershipTest`,
`SyncClosedWalsEmptiedByWaitLeavesLaterMark`,
`LeadershipSyncFinishesMarksPastHorizon`), GC13 Q3/Q5/Q6 (25: leadership
claim bool + unsynced count, `wal_sync_claimed`/`wal_sync_up_to` record,
gate wait, fan-out + `synced_size` advance,
`RunCompletionGate(sync_micros)`, sync barrier; tests
`SyncFanoutAndMutexHistograms`, `WalPartitionHistogramsSilentAtN1`), GC15
Q5 comments (2). Hand-ported inline per X11; D123971668 must re-extract
as a pure move. `kWalPartitionsRejection` updated to this diff's wording
(X10). Exceptions: `TEST_WalSyncMarks` decl after
`TEST_GetWalMergeBuffer` (public TEST block; D123928339 inserts
`TEST_AliveWalFiles`/`TEST_CurrentWalNumber` before it to match T0);
GC13#159 claim-decl change rides the D123971668 extraction. Gate:
lib builds; `db_write_test` 133/0 (5 new); `DBWALSyncMarkOwnershipTest`
4/4; `db_options_test` 55/0; `MixedSyncWritesCompleteUnderConcurrency`
x1000 (run during fold, result in M1 record).
M1 re-verification (2026-10-20, after rebasing the stack onto master f0c3a35689fc and clang-formatting): per-diff gate at this diff passed (CI format check, `rocksdb_lib` build, touched test targets); tip suites 8126/0; N=1 byte identity equals T0.

M2 fold: new or moved tests here: WalPartitionsRejectionsNameTheirOptions, IngestionThenWritesKeepLastSequenceMonotone. B.1 at this diff (format check, `rocksdb_lib`, touched test targets): PASS; db_options_test + db_wal_test + db_write_test 2271 pass.

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

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

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

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

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

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

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

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

Subscribers: jewoongh, rbanerjee2

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

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

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

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

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

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

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

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

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

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

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

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

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

M1: absorbs GC03 (all 19: SyncWal claim + `claimed` filter,
`TEST_WalSyncMarks`, `DBWALSyncMarkOwnershipTest`,
`SyncClosedWalsEmptiedByWaitLeavesLaterMark`,
`LeadershipSyncFinishesMarksPastHorizon`), GC13 Q3/Q5/Q6 (25: leadership
claim bool + unsynced count, `wal_sync_claimed`/`wal_sync_up_to` record,
gate wait, fan-out + `synced_size` advance,
`RunCompletionGate(sync_micros)`, sync barrier; tests
`SyncFanoutAndMutexHistograms`, `WalPartitionHistogramsSilentAtN1`), GC15
Q5 comments (2). Hand-ported inline per X11; D123971668 must re-extract
as a pure move. `kWalPartitionsRejection` updated to this diff's wording
(X10). Exceptions: `TEST_WalSyncMarks` decl after
`TEST_GetWalMergeBuffer` (public TEST block; D123928339 inserts
`TEST_AliveWalFiles`/`TEST_CurrentWalNumber` before it to match T0);
GC13#159 claim-decl change rides the D123971668 extraction. Gate:
lib builds; `db_write_test` 133/0 (5 new); `DBWALSyncMarkOwnershipTest`
4/4; `db_options_test` 55/0; `MixedSyncWritesCompleteUnderConcurrency`
x1000 (run during fold, result in M1 record).
M1 re-verification (2026-10-20, after rebasing the stack onto master f0c3a35689fc and clang-formatting): per-diff gate at this diff passed (CI format check, `rocksdb_lib` build, touched test targets); tip suites 8126/0; N=1 byte identity equals T0.

M2 fold: new or moved tests here: WalPartitionsRejectionsNameTheirOptions, IngestionThenWritesKeepLastSequenceMonotone. B.1 at this diff (format check, `rocksdb_lib`, touched test targets): PASS; db_options_test + db_wal_test + db_write_test 2271 pass.

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

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

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

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

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

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

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

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

Subscribers: jewoongh, rbanerjee2

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