Skip to content

[Muse][GC] GC26: Resume, N-changes and rollback leave the DB openable; recovery modes follow D-10 - #24

Closed
JustinGaoF wants to merge 1 commit into
pwal/gc24from
pwal/gc26-muse
Closed

JustinGaoF wants to merge 1 commit into
pwal/gc24from
pwal/gc26-muse

Conversation

@JustinGaoF

Copy link
Copy Markdown
Owner

[GC] GC26: Resume, N-changes and rollback leave the DB openable; recovery modes follow D-10

Reviewer question: Do Resume, N changes and rollback now always leave the
DB openable, and do the recovery modes follow D-10?

Yes. Resume reads burned indices back before voiding (Q1), Open attests
every recovered chain head (Q2), an unindexed suffix above a partitioned
indexed set merges then replays (Q3), skip mode skips unexplained holes
and applies the records above them while tolerate/absolute still fail
(Q4/D-10, documented), and the five leftovers are done (Q5).

Q1 -- Resume reads a burned index back before voiding it (D-GC25a, G3-A-2).
Property: before writing an explanation void, Resume reads the burned
index back from its quarantined WAL. No record landed: void. A whole
record landed: no void; the record recovers (D-1). Torn: treated as not
landed. Read-back failure: Resume fails, DB stays stopped. Every mode
opens after such a Resume.
How: ReadBackBurnedWALIndices scans the burning WAL once with
log::Reader (checksums on, kSkipAnyCorruptedRecords) and collects
whole landed records; ExplainBurnedWALIndices voids only indices with
no landed record. NotFound/PathNotFound reads as absent (purged WAL).
Keep to ExplainBurnedWALIndices and helpers; no write-path change.
Evidence: BurnedIndexReadbackKeepsDbOpenable (landed/not-landed/torn x
4 modes x N{2,8} x 2PC on/off), ResumeFailsWhenBurnedIndexReadbackFails;
ResumedTwoPCHoleKeepsAckedWritesAfterCrash,
RepeatedTwoPCHolesStayExplainedAfterCrash,
ResumeFailsWhenBurnedIndexCannotBeExplained and the GC24 real-fault
test stay green.
Neuter: skip the read-back (always void). The landed case fails every
reopen with "index 4 bears records and a void cover" (demonstrated).

Q2 -- Open attests every recovered chain head (D-GC25b, G3-B-1).
Property: reducing N (4->2, 4->1, 8->2) with an outstanding prepare,
then flushing and reopening, opens in every mode with every
acknowledged write.
How: RecoveredWALIndexPredecessors collects every placed head;
WriteExtraWALIndexPredecessorSpans writes the extra spans newest-first
into new WAL heads (honoring StartWALFile:WriteSpan suppression); the
reader accumulates predecessor_spans_ (second span accepted, no longer
corruption); the merge folds every AttestedSpan.
Evidence: ReducedWalPartitionsWithPinnedPrepareReopen (4->2, 4->1, 8->2
plus 4->4 control); log_test WALIndexSecondPredecessorSpanAccepted;
log_merge HeadAttestingTwoRetiredPredecessorsExplainsBoth.
Neuter: no-op the extra spans (newest-only attestation). The probe
fails with "unexplained hole at wal_index 1 with records above it"
(demonstrated).

Q3 -- An unindexed suffix above a partitioned indexed set merges, then
replays (D-GC25c, G3-B-2). Only true alternation fails closed;
superseded records are never replayed.
How: CheckWALFilesCarryWALIndex returns unindexed_low/indexed_high; a
suffix (every unindexed WAL above every indexed one) routes to
ProcessLogFilesMerged(merge_from, merge_upto), excluded from members/
expected_wals, then replays sequentially on a clean end.
Evidence: RollbackToNoneWithPinnedPrepareReopens (all 4 modes, acked
writes + prepare intact, later commit/rollback works);
AlternatingIndexedSetsFailClosed (closes T6).
Neuter: force unindexed_suffix=false (today's gate). The rollback probe
fails with "WAL 47 carries no WAL index but follows indexed WAL 24"
(demonstrated).

Q4 -- Recovery modes follow D-10, and the docs say so (F007).
Property: skip skips an unexplained hole and a tail gap in an indexed
set and applies the records above; superseded records are never
applied, even under skip. Tolerate/absolute fail on a hole with
records above. Point-in-time opens the prefix, unchanged.
How: WALIndexMerger takes continue_past_unexplained_holes (set with
the discard flag under skip); the frontier branch is unreachable under
skip; all-finished past the lost floor ends the stream under skip only
(strict modes keep the base frontier); skips and trailing loss warn
(SkippedUnexplainedHoles/SkippedTrailingLostWAL). Docs: WALRecoveryMode,
wal_partitions and partition_wal_usage text plus new release note
unreleased_history/behavior_changes/partition_wal_recovery_modes.md.
Evidence: SkipModeSkipsPristineHoleAppliesAbove (N{1,2}),
SkipModeSkipsBoundaryLossAtOnePartition, SkipModeSkipsTornTailAtOnePartition,
FirstSessionBottomLossIsDetected (extended),
PristineHoleFailsExceptPointInTimeAndSkip (renamed+extended),
MixedVoidAndHoleMapsPerMode (extended: void skipped mid-stream, hole
skipped, "burned" never applied), merge-level
SupersededBelowPristineHoleSkipsPastIt; D-10 flips to MissingMidChainWalPerMode,
TornTailsInSeveralPartitionsPerMode, GC23MissingCurrentIndexedWalAfterPrefix,
GC24LostCurrentWalBelowSurvivorIsAHole, DamagedPartitionWalHeadIsBoundedPerMode
(sanctioned Invariant-3 exceptions: they encoded the pre-D-10 refusal).
Neuter: skip_holes=false (today's refusal). The skip tests fail with
"unexplained hole at wal_index 2/3 with records above it" in both
suites (demonstrated); they failed the same way at the base pre-fix.

Q5 -- Leftovers.
(a) Ported GC24HistoryFloorScopeOnUpgrade (Muse GC24 loser): passes.
Neuter: HeadBounded holds whenever attested_wals_ is empty; the
spans-off layouts open instead of failing "head damaged and
unattested" (demonstrated).
(b) Ported the ResumeImpl retry-flush normalization
(BurnedWalIndicesPending) and GC24RetryFlushRecoveryWithBurnedIndexProgresses
(Muse GC24 loser): the first Resume takes the full path, rotates,
explains (via the Q1 read-back) and recovers. Neuter: drop the
override; the forced Resume fails "no healthy WAL to explain burned
WAL index 3" (demonstrated).
(c) WalPartitionsCreateCFRejectsConflicts (CreateColumnFamily rejects
all five; stripping via the generic concurrent-write check) and
WalPartitionsSetOptionsRuntimeConflicts (max_successive_merges, the
mutable one, reaches the N>1 guard at runtime and is refused by it;
immutables refuse generically). Neuter: drop the ValidateOptions N>1
guards; the CreateColumnFamily cases pass (argued, not run).
(d) Removed the three dead AllowWalPartitions hook callbacks
(db_write_test FU14H6, transaction_test SyncPrepare + FU14SnapshotRace
Open; the sync point has no producer). Zero references remain; suites
green. No neuter (deletion).
(e) finalize_and_sanitize clears test_secondary and
continuous_verification_interval in the final N>1 branch. Python check
of the sanitizer: N>1 cleared, N=1 untouched, 10/10 stable. Neuter:
drop the two lines; the N>1 asserts fail (argued, not run). No
db_stress run (deferred per spec).

Credits: Q5a/Q5b tests and the Q5b normalization ported from GC24's
closed loser (Muse), pwal/ab/gc24-muse-PR21 (9665b17). No
MANIFEST tags, release twin, masking, cookie registry, prefix-open or
read-mask code ported.

Fold-back split (git blame at the base + Differential Revision lines;
areas follow the round's Question->diff map):

  • Q1: db_impl_write.cc ExplainBurnedWALIndices read-back+gating ->
    D123701876 (added by GC21 47da494); ReadBackBurnedWALIndices, decls
    and the log_reader.h include are new code. Tests new code.
  • Q2: RecoveredWALIndexPredecessor(s), Open call sites ->
    D123928339 (M2.9 0d5bfa7); WriteExtraWALIndexPredecessorSpans body,
    reader span accumulation and merger accessors are new code;
    span folding touches D120649665 (4d090d8) lines; log_test span
    update touches D120621828 (a79df69). Tests new code.
  • Q3: CheckWALFilesCarryWALIndex signature, RecoverLogFiles routing,
    ProcessLogFilesMerged signature -> D123928339 (M2.9 0d5bfa7); new
    parameters and suffix routing are new code. Tests new code.
  • Q4: merger flags/skip branches/trailing-loss termination, frontier
    message edit -> D120649665 (4d090d8); new flags, counters,
    accessors and warn text are new code. Option-docs text ->
    D117251769 / D118367634 (per map). Release note is a new file.
    Flipped base cells stay with their tests: PristineHole/MixedVoid ->
    D120649665 (4d090d8); MissingMidChain/TornTails -> M3 coverage
    a855854; GC23MissingCurrent -> GC23 d6ada40; GC24LostCurrent ->
    GC24 121a5a0; DamagedPartition/SkipModeFails/FailingWalFS fault
    modes -> D123928339 (M2.9 0d5bfa7).
  • Q5: (a) ported test -> D120624825; (b) normalization new code +
    ported test -> D123928339 and D123701876; (c) new tests ->
    D123079329 and D123701876; (d) removals -> the GC18 flip standalone;
    (e) sanitizer -> D126533194.

Assumptions:

  • Q1: a torn record counts as not landed (its bytes cannot form a whole
    checksum-valid record conflicting with the void); any other read-back
    failure fails Resume. NotFound and PathNotFound both read as absent
    (purged WAL).
  • Q4: the pristine hole is built by moving indices 3,4 to 30,31: moving
    3->30 alone leaves a physically impossible out-of-order file (30
    before 4), which the merge rejects.
  • Q5b: the port adds explicit SyncPoint Enable/Disable around the
    Context callback (the loser relied on ambient enablement).
  • Q5c: max_successive_merges SetOptions reaches the N>1 guard at runtime
    and is refused by it (it is the set's one mutable option);
    memtable_factory takes no string value through SetOptions, so it has
    no runtime case (CreateColumnFamily covers its guard).
  • D-10 flips to base tests (listed under Q4 plus the two renames and the
    FirstSessionBottomLoss/MixedVoid extensions) are sanctioned
    Invariant-3 exceptions: each encoded the pre-D-10 skip refusal.
  • Verification found and fixed a hang: under skip, the lost-floor
    branch skipped past the floor with all members finished, climbing
    expected_ without bound (observed at 125B). All-finished now ends the
    stream under skip only; strict modes keep the base frontier.
  • GatePostWaitSyncFailureWakesParkedGate (w_parks 3 vs 2, ~1/15) and
    GateSyncToleratesCoupledRotation (1 miss under 83-way load, 6/6
    standalone) are pre-existing load flakes in unmodified gate
    choreography code; the full suite is green at -w40.

Not done: none.

Test plan:

  • Debug suites, all pass: db_write_test 408/408; db_wal_test +
    db_options_test + error_handler_fs_test 2214; log_merge_test 212;
    log_test 483; db_basic_test + db_secondary_test 378; transaction_test
    3435; write_prepared_transaction_test + db_wal_oracle_test 933.
  • TSan (clang) on every new/changed test: 20 + 6 + 2 + 8 + 4 pass, no
    races reported.
  • Repeats: Q1 pair 200 OK; MixedVoidAndHoleMapsPerMode 100/100;
    GC24HistoryFloorScopeOnUpgrade + GC24RetryFlushRecovery 100/100;
    Q2+Q3 trio 100/100.
  • Oracle: ROCKSDB_WAL_ORACLE_CYCLES=1000 seed 1 passes (N=2 in 499,
    N=8 in 501; 352 power-loss cycles lost an acked write as designed).
  • N=1 byte identity: fillseq num=10000 seed=20260928, usages none and
    partition_by_column_family: SHA-256 of *.log identical base vs
    commit (6d135111... / 9a69a3fc...).
  • make check-format clean (clang-format 21.1.2); make check-sources
    clean; tools/db_crashtest.py compiles; Q5e sanitizer check 10/10.
  • Neuters: Q1, Q2, Q3, Q4 (both suites), Q5a, Q5b demonstrated failing
    as listed above; fixes restored and re-verified (9/9).
  • db_stress: not run (deferred per spec).

…very modes follow D-10

[GC] GC26: Resume, N-changes and rollback leave the DB openable; recovery modes follow D-10

Reviewer question: Do Resume, N changes and rollback now always leave the
DB openable, and do the recovery modes follow D-10?

Yes. Resume reads burned indices back before voiding (Q1), Open attests
every recovered chain head (Q2), an unindexed suffix above a partitioned
indexed set merges then replays (Q3), skip mode skips unexplained holes
and applies the records above them while tolerate/absolute still fail
(Q4/D-10, documented), and the five leftovers are done (Q5).

Q1 -- Resume reads a burned index back before voiding it (D-GC25a, G3-A-2).
  Property: before writing an explanation void, Resume reads the burned
  index back from its quarantined WAL. No record landed: void. A whole
  record landed: no void; the record recovers (D-1). Torn: treated as not
  landed. Read-back failure: Resume fails, DB stays stopped. Every mode
  opens after such a Resume.
  How: ReadBackBurnedWALIndices scans the burning WAL once with
  log::Reader (checksums on, kSkipAnyCorruptedRecords) and collects
  whole landed records; ExplainBurnedWALIndices voids only indices with
  no landed record. NotFound/PathNotFound reads as absent (purged WAL).
  Keep to ExplainBurnedWALIndices and helpers; no write-path change.
  Evidence: BurnedIndexReadbackKeepsDbOpenable (landed/not-landed/torn x
  4 modes x N{2,8} x 2PC on/off), ResumeFailsWhenBurnedIndexReadbackFails;
  ResumedTwoPCHoleKeepsAckedWritesAfterCrash,
  RepeatedTwoPCHolesStayExplainedAfterCrash,
  ResumeFailsWhenBurnedIndexCannotBeExplained and the GC24 real-fault
  test stay green.
  Neuter: skip the read-back (always void). The landed case fails every
  reopen with "index 4 bears records and a void cover" (demonstrated).

Q2 -- Open attests every recovered chain head (D-GC25b, G3-B-1).
  Property: reducing N (4->2, 4->1, 8->2) with an outstanding prepare,
  then flushing and reopening, opens in every mode with every
  acknowledged write.
  How: RecoveredWALIndexPredecessors collects every placed head;
  WriteExtraWALIndexPredecessorSpans writes the extra spans newest-first
  into new WAL heads (honoring StartWALFile:WriteSpan suppression); the
  reader accumulates predecessor_spans_ (second span accepted, no longer
  corruption); the merge folds every AttestedSpan.
  Evidence: ReducedWalPartitionsWithPinnedPrepareReopen (4->2, 4->1, 8->2
  plus 4->4 control); log_test WALIndexSecondPredecessorSpanAccepted;
  log_merge HeadAttestingTwoRetiredPredecessorsExplainsBoth.
  Neuter: no-op the extra spans (newest-only attestation). The probe
  fails with "unexplained hole at wal_index 1 with records above it"
  (demonstrated).

Q3 -- An unindexed suffix above a partitioned indexed set merges, then
  replays (D-GC25c, G3-B-2). Only true alternation fails closed;
  superseded records are never replayed.
  How: CheckWALFilesCarryWALIndex returns unindexed_low/indexed_high; a
  suffix (every unindexed WAL above every indexed one) routes to
  ProcessLogFilesMerged(merge_from, merge_upto), excluded from members/
  expected_wals, then replays sequentially on a clean end.
  Evidence: RollbackToNoneWithPinnedPrepareReopens (all 4 modes, acked
  writes + prepare intact, later commit/rollback works);
  AlternatingIndexedSetsFailClosed (closes T6).
  Neuter: force unindexed_suffix=false (today's gate). The rollback probe
  fails with "WAL 47 carries no WAL index but follows indexed WAL 24"
  (demonstrated).

Q4 -- Recovery modes follow D-10, and the docs say so (F007).
  Property: skip skips an unexplained hole and a tail gap in an indexed
  set and applies the records above; superseded records are never
  applied, even under skip. Tolerate/absolute fail on a hole with
  records above. Point-in-time opens the prefix, unchanged.
  How: WALIndexMerger takes continue_past_unexplained_holes (set with
  the discard flag under skip); the frontier branch is unreachable under
  skip; all-finished past the lost floor ends the stream under skip only
  (strict modes keep the base frontier); skips and trailing loss warn
  (SkippedUnexplainedHoles/SkippedTrailingLostWAL). Docs: WALRecoveryMode,
  wal_partitions and partition_wal_usage text plus new release note
  unreleased_history/behavior_changes/partition_wal_recovery_modes.md.
  Evidence: SkipModeSkipsPristineHoleAppliesAbove (N{1,2}),
  SkipModeSkipsBoundaryLossAtOnePartition, SkipModeSkipsTornTailAtOnePartition,
  FirstSessionBottomLossIsDetected (extended),
  PristineHoleFailsExceptPointInTimeAndSkip (renamed+extended),
  MixedVoidAndHoleMapsPerMode (extended: void skipped mid-stream, hole
  skipped, "burned" never applied), merge-level
  SupersededBelowPristineHoleSkipsPastIt; D-10 flips to MissingMidChainWalPerMode,
  TornTailsInSeveralPartitionsPerMode, GC23MissingCurrentIndexedWalAfterPrefix,
  GC24LostCurrentWalBelowSurvivorIsAHole, DamagedPartitionWalHeadIsBoundedPerMode
  (sanctioned Invariant-3 exceptions: they encoded the pre-D-10 refusal).
  Neuter: skip_holes=false (today's refusal). The skip tests fail with
  "unexplained hole at wal_index 2/3 with records above it" in both
  suites (demonstrated); they failed the same way at the base pre-fix.

Q5 -- Leftovers.
  (a) Ported GC24HistoryFloorScopeOnUpgrade (Muse GC24 loser): passes.
  Neuter: HeadBounded holds whenever attested_wals_ is empty; the
  spans-off layouts open instead of failing "head damaged and
  unattested" (demonstrated).
  (b) Ported the ResumeImpl retry-flush normalization
  (BurnedWalIndicesPending) and GC24RetryFlushRecoveryWithBurnedIndexProgresses
  (Muse GC24 loser): the first Resume takes the full path, rotates,
  explains (via the Q1 read-back) and recovers. Neuter: drop the
  override; the forced Resume fails "no healthy WAL to explain burned
  WAL index 3" (demonstrated).
  (c) WalPartitionsCreateCFRejectsConflicts (CreateColumnFamily rejects
  all five; stripping via the generic concurrent-write check) and
  WalPartitionsSetOptionsRuntimeConflicts (max_successive_merges, the
  mutable one, reaches the N>1 guard at runtime and is refused by it;
  immutables refuse generically). Neuter: drop the ValidateOptions N>1
  guards; the CreateColumnFamily cases pass (argued, not run).
  (d) Removed the three dead AllowWalPartitions hook callbacks
  (db_write_test FU14H6, transaction_test SyncPrepare + FU14SnapshotRace
  Open; the sync point has no producer). Zero references remain; suites
  green. No neuter (deletion).
  (e) finalize_and_sanitize clears test_secondary and
  continuous_verification_interval in the final N>1 branch. Python check
  of the sanitizer: N>1 cleared, N=1 untouched, 10/10 stable. Neuter:
  drop the two lines; the N>1 asserts fail (argued, not run). No
  db_stress run (deferred per spec).

Credits: Q5a/Q5b tests and the Q5b normalization ported from GC24's
closed loser (Muse), pwal/ab/gc24-muse-PR21 (9665b17). No
MANIFEST tags, release twin, masking, cookie registry, prefix-open or
read-mask code ported.

Fold-back split (git blame at the base + Differential Revision lines;
areas follow the round's Question->diff map):
- Q1: db_impl_write.cc ExplainBurnedWALIndices read-back+gating ->
  D123701876 (added by GC21 47da494); ReadBackBurnedWALIndices, decls
  and the log_reader.h include are new code. Tests new code.
- Q2: RecoveredWALIndexPredecessor(s), Open call sites ->
  D123928339 (M2.9 0d5bfa7); WriteExtraWALIndexPredecessorSpans body,
  reader span accumulation and merger accessors are new code;
  span folding touches D120649665 (4d090d8) lines; log_test span
  update touches D120621828 (a79df69). Tests new code.
- Q3: CheckWALFilesCarryWALIndex signature, RecoverLogFiles routing,
  ProcessLogFilesMerged signature -> D123928339 (M2.9 0d5bfa7); new
  parameters and suffix routing are new code. Tests new code.
- Q4: merger flags/skip branches/trailing-loss termination, frontier
  message edit -> D120649665 (4d090d8); new flags, counters,
  accessors and warn text are new code. Option-docs text ->
  D117251769 / D118367634 (per map). Release note is a new file.
  Flipped base cells stay with their tests: PristineHole/MixedVoid ->
  D120649665 (4d090d8); MissingMidChain/TornTails -> M3 coverage
  a855854; GC23MissingCurrent -> GC23 d6ada40; GC24LostCurrent ->
  GC24 121a5a0; DamagedPartition/SkipModeFails/FailingWalFS fault
  modes -> D123928339 (M2.9 0d5bfa7).
- Q5: (a) ported test -> D120624825; (b) normalization new code +
  ported test -> D123928339 and D123701876; (c) new tests ->
  D123079329 and D123701876; (d) removals -> the GC18 flip standalone;
  (e) sanitizer -> D126533194.

Assumptions:
- Q1: a torn record counts as not landed (its bytes cannot form a whole
  checksum-valid record conflicting with the void); any other read-back
  failure fails Resume. NotFound and PathNotFound both read as absent
  (purged WAL).
- Q4: the pristine hole is built by moving indices 3,4 to 30,31: moving
  3->30 alone leaves a physically impossible out-of-order file (30
  before 4), which the merge rejects.
- Q5b: the port adds explicit SyncPoint Enable/Disable around the
  Context callback (the loser relied on ambient enablement).
- Q5c: max_successive_merges SetOptions reaches the N>1 guard at runtime
  and is refused by it (it is the set's one mutable option);
  memtable_factory takes no string value through SetOptions, so it has
  no runtime case (CreateColumnFamily covers its guard).
- D-10 flips to base tests (listed under Q4 plus the two renames and the
  FirstSessionBottomLoss/MixedVoid extensions) are sanctioned
  Invariant-3 exceptions: each encoded the pre-D-10 skip refusal.
- Verification found and fixed a hang: under skip, the lost-floor
  branch skipped past the floor with all members finished, climbing
  expected_ without bound (observed at 125B). All-finished now ends the
  stream under skip only; strict modes keep the base frontier.
- GatePostWaitSyncFailureWakesParkedGate (w_parks 3 vs 2, ~1/15) and
  GateSyncToleratesCoupledRotation (1 miss under 83-way load, 6/6
  standalone) are pre-existing load flakes in unmodified gate
  choreography code; the full suite is green at -w40.

Not done: none.

Test plan:
- Debug suites, all pass: db_write_test 408/408; db_wal_test +
  db_options_test + error_handler_fs_test 2214; log_merge_test 212;
  log_test 483; db_basic_test + db_secondary_test 378; transaction_test
  3435; write_prepared_transaction_test + db_wal_oracle_test 933.
- TSan (clang) on every new/changed test: 20 + 6 + 2 + 8 + 4 pass, no
  races reported.
- Repeats: Q1 pair 200 OK; MixedVoidAndHoleMapsPerMode 100/100;
  GC24HistoryFloorScopeOnUpgrade + GC24RetryFlushRecovery 100/100;
  Q2+Q3 trio 100/100.
- Oracle: ROCKSDB_WAL_ORACLE_CYCLES=1000 seed 1 passes (N=2 in 499,
  N=8 in 501; 352 power-loss cycles lost an acked write as designed).
- N=1 byte identity: fillseq num=10000 seed=20260928, usages none and
  partition_by_column_family: SHA-256 of *.log identical base vs
  commit (6d135111... / 9a69a3fc...).
- make check-format clean (clang-format 21.1.2); make check-sources
  clean; tools/db_crashtest.py compiles; Q5e sanitizer check 10/10.
- Neuters: Q1, Q2, Q3, Q4 (both suites), Q5a, Q5b demonstrated failing
  as listed above; fixes restored and re-verified (9/9).
- db_stress: not run (deferred per spec).
@JustinGaoF JustinGaoF changed the title [Muse][GC] GC26: Resume, N-changes and rollback leave the DB openable; recovery modes follow D-10 [GC] GC26: Resume, N-changes and rollback leave the DB openable; recovery modes follow D-10 Oct 30, 2026
@JustinGaoF

Copy link
Copy Markdown
Owner Author

GC26 selection changed by the owner after the comparison: the other candidate (#25) is accepted. Closing this one; the original commit is kept as pwal/ab/gc26-muse-PR24.

@JustinGaoF JustinGaoF closed this Oct 30, 2026
@JustinGaoF JustinGaoF changed the title [GC] GC26: Resume, N-changes and rollback leave the DB openable; recovery modes follow D-10 [Muse][GC] GC26: Resume, N-changes and rollback leave the DB openable; recovery modes follow D-10 Oct 30, 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