Skip to content

Hotcold - #86

Closed
skynet wants to merge 51 commits into
masterfrom
hotcold
Closed

skynet wants to merge 51 commits into
masterfrom
hotcold

Conversation

@skynet

@skynet skynet commented Feb 17, 2014

Copy link
Copy Markdown

No description provided.

Summary:
Added DBImplHotCold class stub that will be expanded in future commits. Added
function DB::OpenWithHotCold(), with the same interface as DB::Open(), to create
an instance of this implementation class.

Test Plan:
Wrote a small program that opens a DBImplHotCold instance and wrote and read a
few records.

Reviewers: sheki, emayanke, dhruba, vamsi

CC: leveldb

Differential Revision: https://reviews.facebook.net/D7053
Summary:
Added DBImplHotCold class stub that will be expanded in future commits. Added
function DB::OpenWithHotCold(), with the same interface as DB::Open(), to create
an instance of this implementation class.

Test Plan:
Wrote a small program that opens a DBImplHotCold instance and wrote and read a
few records.

Reviewers: sheki, emayanke, dhruba, vamsi

Reviewed By: vamsi

CC: leveldb

Differential Revision: https://reviews.facebook.net/D7053
Summary: In order to benchmark the overhead of metrics taking I added a flag to db_bench that calls `DB::OpenWithHotCold()` instead of `DB::Open()` when it is set.

Test Plan: Added print statements to lines before `DB::Open()` and `DB::OpenWithHotCold()` to see whether the flag affects which one gets called.

Reviewers: vamsi, dhruba

Reviewed By: dhruba

CC: leveldb

Differential Revision: https://reviews.facebook.net/D7485
Summary:
Changed `DoCompactionWork()` to output multiple files and imported https://reviews.facebook.net/D8025 (Ideally all issues with version_set.h, version_set.cc and version_set_test.cc should be brought up there so I can keep that patch up to date and we can decide whether to mainline it separately) so we can handle overlapping files in level 1+.

Added code to determine whether a record is hot or cold given the metrics DB and an iterator on the database (which allows us to get all the necessary data in order to lookup the hotness)

Test Plan:
make check

db_bench --benchmarks=readrandomwriterandom --hotcold=1

Reviewers: dhruba, vamsi, chip, heyongqiang

Reviewed By: vamsi

CC: leveldb

Differential Revision: https://reviews.facebook.net/D8163
… in hot file

Summary:
Before this update both hot and cold file had to be queried in order to get the latest value for a given key. Now if the key is found in the hot file then we know the latest value is in the hot file.

Changed compaction to not allow a user key to have a record with a smaller sequence number in the hot file if there is a record with a larger sequence number in the cold file.

Added short circuiting to `Version::Get()` to assume that if a key is found in a newer file then it has a newer sequence number.

Test Plan:
`make check`

ran `db_bench` compiled with assertions on and in hot cold mode.

Reviewers: vamsi, dhruba

Reviewed By: vamsi

CC: leveldb

Differential Revision: https://reviews.facebook.net/D8451
…ckMetrics in Block::MetricsIter

Summary: Metrics no longer pass through `Table` to the cache and instead go directly from `Block::MetricsIter`. Additionally `BlockMetrics` is now only created when a `Seek()` is performed.

Test Plan: make check

Reviewers: vamsi, dhruba

Reviewed By: vamsi

CC: leveldb

Differential Revision: https://reviews.facebook.net/D8427
…and added readhotwriterandom to db_bench

Summary:
Changed `Block::MetricsIter` to only record metrics when the seek finds the value the user was looking for.

Added extra benchmark to db_bench.

Test Plan: make check

Reviewers: vamsi, dhruba

Reviewed By: vamsi

CC: leveldb

Differential Revision: https://reviews.facebook.net/D8433
Summary: Added an option to `Options` to specify which levels have metrics recorded and used that option in `Version::Get()` to stop metrics being recorded for wrong levels and in `DBImpl` to stop `DoCompactionWork()` trying to split on hotcold for levels where no metrics are available.

Test Plan: make check

Reviewers: vamsi, dhruba

Reviewed By: vamsi

CC: leveldb

Differential Revision: https://reviews.facebook.net/D8511
Summary:
Before this patch we had to send metrics to `Cache`, which then sent the metrics to `DBImpl`. Now we directly send them to `DBImpl`, by the use of a pointer to a pointer of a `BlockMetrics` instance. We can do this safely and without additional locks because:

* `Block::MetricsIter` runs in the same thread as `DBImpl::Get()` (in which the `BlockMetrics` pointer resides)
* `DBImpl::Get()` locks `DBImpl` again after the `Block::MetricsIter` is destroyed, so we don't have to do an additional lock.

Test Plan: make check

Reviewers: vamsi, dhruba

Reviewed By: vamsi

CC: leveldb

Differential Revision: https://reviews.facebook.net/D8583
Summary: readhotwriterandom now generates a certain number of keys randomly. This number is a percentage (determined by hotkeyspercentage) of --num. Then when a key is needed one of the keys in that list is chosen randomly.

Test Plan: Ran db_bench with small --num parameter to see if the keys are random and that we only use a subset of the "hot" keys.

Reviewers: vamsi, dhruba

Reviewed By: vamsi

CC: leveldb

Differential Revision: https://reviews.facebook.net/D8613
@skynet skynet closed this Feb 17, 2014
@siying
siying deleted the hotcold branch October 25, 2016 20:44
201341 pushed a commit to 201341/rocksdb that referenced this pull request Jan 23, 2021
Win32 fixes + US-EAST-1 fix
Nazgolze pushed a commit to Nazgolze/rocksdb-1 that referenced this pull request Sep 21, 2021
gz pushed a commit to gz/rocksdb that referenced this pull request Dec 13, 2022
Use PathBuf/Path type for file paths
JustinGaoF added a commit to JustinGaoF/rocksdb 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 to JustinGaoF/rocksdb 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 to JustinGaoF/rocksdb 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 to JustinGaoF/rocksdb 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.

2 participants