storage: drop v3 W publications that a recovery has superseded (row 5c amend)

codex01 row 5c review (87a922fa, AMEND). Lock graph first, unchanged:
syncMu (v3 leader) -> s.mu -> descMu -> fileSyncMu; Recover holds
s.mu -> descMu -> fileSyncMu and never takes syncMu. No edge is added.

- P1: a flusher refresh could read Wack 2 and pause while a same-open
  Recover dropped record 2 and reset Wack to 1; the resumed refresh then
  published W 2 and the next Recover reported a false wal_corrupt. Every
  recovery now bumps a recovery epoch first thing (under s.mu, before it
  reads the descriptor). Every publication of a W derived from cached
  wack/appended values (Sync batch, refreshW, SetWMode) captures the epoch
  with them and rechecks it inside its publication mutate, under descMu: a
  superseded publication is dropped (errV3RecoveredMeanwhile; the refresh
  treats it as nothing to do). A publication that wins the race completes
  before the recovery reads the descriptor, so its W is genuine.
  Held real-flusher control: the refresh caches W 2 and parks, the same
  instance recovers to R 1, the refresh resumes and publishes nothing, and
  the next Recover succeeds.
- P2: held tests register the store crash with t.Cleanup before the
  release cleanup, so a failure releases the hold before shutdown.
- P2: the empty-dirty-set refresh branch has its own control.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
pingqiuandClaude Opus 5.5 committed 2026-11-17 03:09:02 -08:00
1 parent 87a922fa18
commit 3e76473c07
3 files changed
+97 -10

No files matched your search

+43 -7
View File
@@ -31,6 +31,16 @@ type walStoreV3State struct {
appended atomic.Uint64 // highest LSN pwritten to the WAL
wack atomic.Uint64 // highest acknowledged LSN (Sync completed)
// recoverEpoch is bumped first thing by every recovery, under s.mu and
// before it reads the descriptor. Every publication that carries a W
// derived from the cached wack/appended values (a Sync batch, the idle
// refresh, SetWMode) captures it with those values and rechecks it in
// its publication mutate, under descMu. A recovery that lowered the
// frontier in between therefore makes that publication a no-op, and a
// publication that won the race finished before the recovery read the
// descriptor (codex01 row 5c). No lock edge is added.
recoverEpoch atomic.Uint64
// syncMu is the group-commit leader role for the v3-only publications
// that run outside the committer (refreshW, SetWMode).
syncMu sync.Mutex
@@ -49,6 +59,25 @@ type walStoreV3State struct {
// testSetWModeHoldingRole runs in SetWMode after it has taken the leader
// role and before it publishes the new mode.
testSetWModeHoldingRole func()
// testRefreshCached runs in refreshW after it has read the acknowledged
// W and before it publishes.
testRefreshCached func()
}
// errV3RecoveredMeanwhile: a recovery ran between reading the acknowledged
// frontier and publishing it; nothing is published.
var errV3RecoveredMeanwhile = errors.New("storage: v3 recovery ran meanwhile; stale publication dropped")
// publishCachedW publishes a W derived from values read at recovery epoch
// ep, unless a recovery has run since (checked under descMu).
func (v *walStoreV3State) publishCachedW(ep uint64, set func(n *descriptorV3)) (descriptorV3, error) {
return v.pub.publish(nil, nil, func(n *descriptorV3) error {
if v.recoverEpoch.Load() != ep {
return errV3RecoveredMeanwhile
}
set(n)
return nil
})
}
var errV3NotYet = errors.New("storage: operation not yet supported on a v3 store (later plan row)")
@@ -201,6 +230,7 @@ func openWALStoreV3ForTest(path string) (*WALStore, error) {
// captureMu, lifecycleMu and s.mu, as v2 Recover does.
func (s *WALStore) recoverV3() (uint64, error) {
v := s.v3
v.recoverEpoch.Add(1) // before the descriptor is read (see recoverEpoch)
d := v.pub.current()
s.dm.clear()
scan, err := scanWALV3(s.fd, d)
@@ -338,6 +368,7 @@ func (s *WALStore) syncWALBatchV3() error {
}
v.syncMu.Lock()
defer v.syncMu.Unlock()
ep := v.recoverEpoch.Load()
H, prev := v.appended.Load(), v.wack.Load()
switch v.pub.current().WMode {
case WModeStrict:
@@ -345,7 +376,7 @@ func (s *WALStore) syncWALBatchV3() error {
if err := s.syncFile(nil, func() error { return s.syncWALFile() }); err != nil {
return err
}
if _, err := v.pub.publish(nil, nil, func(n *descriptorV3) error { n.W = H; return nil }); err != nil {
if _, err := v.publishCachedW(ep, func(n *descriptorV3) { n.W = H }); err != nil {
return err
}
default:
@@ -353,7 +384,7 @@ func (s *WALStore) syncWALBatchV3() error {
// W, and the publication's one fsync covers this batch's records
// and the slot. The slot never names an LSN beyond a completed fsync.
s.walSyncCalls.Add(1)
if _, err := v.pub.publish(nil, nil, func(n *descriptorV3) error { n.W = prev; return nil }); err != nil {
if _, err := v.publishCachedW(ep, func(n *descriptorV3) { n.W = prev }); err != nil {
return err
}
}
@@ -382,11 +413,18 @@ func (s *WALStore) refreshW() error {
}
v.syncMu.Lock()
defer v.syncMu.Unlock()
ep := v.recoverEpoch.Load()
wack := v.wack.Load()
if wack <= v.pub.current().W {
return nil
}
_, err := v.pub.publish(nil, nil, func(n *descriptorV3) error { n.W = wack; return nil })
if h := v.testRefreshCached; h != nil {
h()
}
_, err := v.publishCachedW(ep, func(n *descriptorV3) { n.W = wack })
if errors.Is(err, errV3RecoveredMeanwhile) {
return nil // the refresh is best effort; the recovery superseded it
}
return err
}
@@ -407,11 +445,9 @@ func (s *WALStore) SetWMode(m WMode) error {
if h := v.testSetWModeHoldingRole; h != nil {
h()
}
ep := v.recoverEpoch.Load()
wack := v.wack.Load()
_, err := v.pub.publish(nil, nil, func(n *descriptorV3) error {
n.WMode, n.W = m, wack
return nil
})
_, err := v.publishCachedW(ep, func(n *descriptorV3) { n.WMode, n.W = m, wack })
return err
}
+53 -2
View File
@@ -480,7 +480,7 @@ func TestWALStoreV3RecoversAHistoryEndingAtTheLastRepresentableCursor(t *testing
// acknowledges under C before SetWMode(A) publishes the new mode.
func TestWALStoreV3SetWModeWaitsForAHeldBatch(t *testing.T) {
s, _ := newStoreV3(t, WModeLagged)
defer crashRecoveryHardeningStore(t, s)
t.Cleanup(func() { crashRecoveryHardeningStore(t, s) })
writeSynced(t, s, 1, 1)
if _, err := s.Write(2, blk(2)); err != nil {
t.Fatal(err)
@@ -526,7 +526,7 @@ func TestWALStoreV3SetWModeWaitsForAHeldBatch(t *testing.T) {
// once SetWMode has committed.
func TestWALStoreV3NoBatchAcksUnderAStaleModeAfterSetWMode(t *testing.T) {
s, _ := newStoreV3(t, WModeLagged)
defer crashRecoveryHardeningStore(t, s)
t.Cleanup(func() { crashRecoveryHardeningStore(t, s) })
writeSynced(t, s, 1, 1)
parked, release := make(chan struct{}), make(chan struct{})
rel := sync.OnceFunc(func() { close(release) })
@@ -707,3 +707,54 @@ func TestWALStoreV3FlusherCycleRunsTheIdleRefresh(t *testing.T) {
t.Fatalf("after the flusher's refresh: err = %v, want wal_corrupt", err)
}
}
// codex01 row 5c P1: a refresh that read the acknowledged W before a
// same-open recovery lowered it must not publish it afterwards. Real
// flusher cycle: it flushes, enters the idle refresh, caches W 2 and parks;
// record 2 is then damaged and the same instance recovers to R 1; the
// refresh resumes and must publish nothing, so the next Recover succeeds.
func TestWALStoreV3RefreshCachedAcrossARecoveryPublishesNothing(t *testing.T) {
s, path := newStoreV3(t, WModeLagged)
t.Cleanup(func() { crashRecoveryHardeningStore(t, s) })
writeSynced(t, s, 1, 2) // slot W 1 (lagged), acknowledged W 2
parked, release := make(chan struct{}), make(chan struct{})
rel := sync.OnceFunc(func() { close(release) })
t.Cleanup(rel)
var once sync.Once
s.v3.testRefreshCached = func() { once.Do(func() { close(parked); <-release }) }
flushErr := make(chan error, 1)
go func() { flushErr <- s.flusher.flushOnceInternal(false) }()
waitV3(t, parked, "the refresh holding a cached W")
damageRecord(t, path, 2)
if _, err := s.Recover(); err != nil {
t.Fatalf("same-open Recover: %v", err)
}
if got := s.v3.wack.Load(); got != 1 {
t.Fatalf("acknowledged W after recovery = %d, want 1", got)
}
rel()
if err := recvErrV3(t, flushErr, "the flusher cycle"); err != nil {
t.Fatalf("flusher cycle: %v", err)
}
if w := s.v3.pub.current().W; w > 1 {
t.Fatalf("the stale refresh published W %d after the recovery to R 1", w)
}
if _, err := s.Recover(); err != nil {
t.Fatalf("second Recover: %v (a false wal_corrupt from a stale refresh)", err)
}
}
// codex01 row 5c P2: the empty-dirty-set branch of the flusher cycle runs the
// idle refresh on its own (discriminated separately from the flush branch).
func TestWALStoreV3FlusherEmptyCycleRunsTheIdleRefresh(t *testing.T) {
s, _ := newStoreV3(t, WModeLagged)
t.Cleanup(func() { crashRecoveryHardeningStore(t, s) })
writeSynced(t, s, 1, 2) // slot W 1 (lagged), acknowledged W 2
s.dm.clear() // nothing dirty: the cycle takes the empty branch
if err := s.flusher.flushOnceInternal(false); err != nil {
t.Fatal(err)
}
if w := s.v3.pub.current().W; w != 2 {
t.Fatalf("slot W after an empty flusher cycle = %d, want 2 (the idle refresh)", w)
}
}
+1 -1
View File
@@ -284,7 +284,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w
| `INV-WAL-V3-BINDING-001` | The dark v3 writer stamps the selected nonce and absolute cursor, fits each append/padding inside the dual-slot reuse floor, and refuses later I/O after a pwrite failure. A dark scanner checks nonce and exact expected cursor before using Length/count, checks the full record again, skips only geometric end slack, and stops at the first untrusted record without payload resynchronization. It returns a typed scan result, never ACK or serving permission. | M1 Recovering (dark muscles only) | `core/storage/wal_io_v3.go` `append`, `scanWALV3`, `walSnapshotV3` | `TestWALIOV3_RealWriterReopenScan`, `TestWALIOV3_WrapPaddingAndSlack`, `TestWALIOV3_StopsAtBindingBeforeEmbeddedRecord`, `TestWALIOV3_EmbeddedRecordInPayloadIsNotScanned`, `TestWALIOV3_InstalledScanBeginsAtMaxTail`, `TestWALIOV3_FloorAndPwriteFailureRefuse` | Record/lap admission is abstracted in composed WALFormatR5; physical framing/wrap boundaries remain code-test obligations | STUB |
| `INV-WAL-V3-MAP-BYTES-001` | A dark v3 map candidate names immutable, owned, identity- and geometry-checked pages and root. Domain-separated body digests, reserved/unused bytes, exact page counts, file bounds and non-aliasing intervals all validate before entries escape. Persistence orders pages/fsync, root/fsync, directory fsync; any failure yields no candidate and no retry I/O. Append-only retention preserves both slots and pending candidates. | M1 (dark map preparation only) | `core/storage/chunk_lsn_map_v3.go` `Prepare`, `readChunkLSNMapV3` | `TestChunkLSNMapV3_CanonicalVectors`, `TestChunkLSNMapV3_PersistReloadAndReuse`, `TestChunkLSNMapV3_CorruptionAndBounds`, `TestChunkLSNMapV3_FailureDoesNotPublishOrReuse`, `TestChunkLSNMapV3_OrderOwnedOpenAndClippedPage`, `TestChunkLSNMapV3_RejectsRehashedMalformedRecords` | WALFormatR5 abstract map dependency; physical encoding/digest/order are code obligations | STUB |
| `INV-WAL-V3-PUBLISH-001` | Every v3 descriptor change goes through one publisher. It writes the fallback slot with slotGen+1 under `descMu`. It takes `WALStore.mu` only to snapshot and releases it before slot I/O, and fsync is the leaf. It rebases onto the authoritative descriptor: W and the checkpoint are max-merged, and identity, geometry and nonce changes are refused, as are tail regression, a map root change without a higher generation and any BASE edge outside DESIGN 8.5 (installed -> installing is refused). A failed slot write (full or partial) or fsync publishes nothing. It latches the store fault inside the fsync leaf, before `fileSyncMu` is released, so a queued store Sync cannot acknowledge through it, keeps the uncertain candidate pinned and refuses every later publication, rollover and reuse until a reopen reads the slots back. A fault latched mid-flight is refused at the success boundary. A counter above 2^64-2 is refused with `ErrCounterExhausted` before any write. When the fallback slot pins reuse, a metadata-only rollover advances the floor, and no floor is ever computed across nonces. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `publish`, `mergeDescriptorV3`, `baseTransitionAllowedV3`, `rolloverIfPinned`, `reuseFloor` | `TestDescriptorV3PublishAlternatesSlotsAndReopenSelectsNewest`, `TestDescriptorV3MergeIsMonotonicAndRefusesForbiddenChanges`, `TestDescriptorV3ConcurrentPublishersNeverRegress`, `TestDescriptorV3LockOrderRecorder`, `TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing`, `TestDescriptorV3FaultLatchedDuringPublicationRefusesAtSuccessBoundary`, `TestDescriptorV3FullRingRolloverAdvancesTheFloorWithoutAnyChange`, `TestDescriptorV3RolloverFsyncFailureKeepsTheFloorPinned`, `TestDescriptorV3MixedNoncesNeverYieldAReuseFloor`, `TestDescriptorV3BaseTransitionTable`, `TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate`, `TestDescriptorV3PublicationCounterExhaustion`, `TestDescriptorV3QueuedStoreSyncCannotAckAfterSlotWriteError` (`core/storage/descriptor_v3_test.go`) | — | STUB |
| `INV-WAL-V3-W-001` | v3 Sync acknowledges only after an fsync covers the batch. In mode C (the default) the slot carries the previous batch's acknowledged W and the batch's single fsync covers WAL and slot; in mode A the WAL fsync precedes a slot publication with W = H. Recovery refuses (`wal_corrupt`) when the contiguous prefix R above max(CheckpointLSN, BaseLSN) is below W* = max(slot W, max trusted DurableLSN). Mode C's only unprotected acknowledged data is the newest batch, against media corruption before the next Sync or the idle refresh; `SetWMode` and the refresh close that window. | M1 Recovering → Serving \| RecoveryFailed; M1 write lifecycle: Appended → Synced (v3) | `core/storage/walstore_v3.go` `WALStore.syncWALBatchV3`, `refreshW`, `SetWMode`, `recoverV3`, `appendWriteV3`; `core/storage/recovery_v3.go` `decideRecoveryV3`, `contiguousPrefixV3` | `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes`, `TestWALStoreV3ModeCWindowIsExactlyTheNewestBatch`, `TestWALStoreV3RefreshAndSetWModeCloseTheWindow`, `TestWALStoreV3TornUnsyncedTailIsNeverAFalseCorrupt`, `TestWALStoreV3AppendWriteErrorLatchesTheStore`, `TestWALStoreV3FlusherWritesTheExtentButHoldsTheCheckpointUntilTheMap`, `TestWALStoreV3SyncRechecksTheFaultAtTheAckBoundary`, `TestWALStoreV3SetWModeWaitsForAHeldBatch`, `TestWALStoreV3NoBatchAcksUnderAStaleModeAfterSetWMode`, `TestWALStoreV3SetWModeCrashCases`, `TestWALStoreV3SameOpenRecoverResetsTheAcknowledgedFrontier`, `TestWALStoreV3InstallingScanErrorIsTypedNotReady`, `TestWALStoreV3FlusherCycleRunsTheIdleRefresh` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3Decision`, `TestRecoveryV3ContiguousPrefix` (`core/storage/recovery_v3_test.go`) | `WALFormat` composed model (claude05, r14 run) | STUB |
| `INV-WAL-V3-W-001` | v3 Sync acknowledges only after an fsync covers the batch. In mode C (the default) the slot carries the previous batch's acknowledged W and the batch's single fsync covers WAL and slot; in mode A the WAL fsync precedes a slot publication with W = H. Recovery refuses (`wal_corrupt`) when the contiguous prefix R above max(CheckpointLSN, BaseLSN) is below W* = max(slot W, max trusted DurableLSN). Mode C's only unprotected acknowledged data is the newest batch, against media corruption before the next Sync or the idle refresh; `SetWMode` and the refresh close that window. | M1 Recovering → Serving \| RecoveryFailed; M1 write lifecycle: Appended → Synced (v3) | `core/storage/walstore_v3.go` `WALStore.syncWALBatchV3`, `refreshW`, `SetWMode`, `recoverV3`, `appendWriteV3`; `core/storage/recovery_v3.go` `decideRecoveryV3`, `contiguousPrefixV3` | `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes`, `TestWALStoreV3ModeCWindowIsExactlyTheNewestBatch`, `TestWALStoreV3RefreshAndSetWModeCloseTheWindow`, `TestWALStoreV3TornUnsyncedTailIsNeverAFalseCorrupt`, `TestWALStoreV3AppendWriteErrorLatchesTheStore`, `TestWALStoreV3FlusherWritesTheExtentButHoldsTheCheckpointUntilTheMap`, `TestWALStoreV3SyncRechecksTheFaultAtTheAckBoundary`, `TestWALStoreV3SetWModeWaitsForAHeldBatch`, `TestWALStoreV3NoBatchAcksUnderAStaleModeAfterSetWMode`, `TestWALStoreV3SetWModeCrashCases`, `TestWALStoreV3SameOpenRecoverResetsTheAcknowledgedFrontier`, `TestWALStoreV3InstallingScanErrorIsTypedNotReady`, `TestWALStoreV3FlusherCycleRunsTheIdleRefresh`, `TestWALStoreV3RefreshCachedAcrossARecoveryPublishesNothing`, `TestWALStoreV3FlusherEmptyCycleRunsTheIdleRefresh` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3Decision`, `TestRecoveryV3ContiguousPrefix` (`core/storage/recovery_v3_test.go`) | `WALFormat` composed model (claude05, r14 run) | STUB |
| `INV-WAL-V3-FENCE-001` | Before any append after a v3 recovery, the store zeroes exactly the logical WAL interval [E, floor+WALSize) (floor = both slots' same-nonce reuse floor) split at the physical wrap, fsyncs it through the leaf, then publishes retainedHead = E; no byte before E or outside the interval changes, so records dropped by one recovery never resurface after a second crash. | M1 Recovering → Serving (v3) | `core/storage/walstore_v3.go` `WALStore.fenceV3`, `recoverV3`; `core/storage/recovery_v3.go` `fenceRangesV3` | `TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash`, `TestWALStoreV3NoFenceResurrectsInBothModes`, `TestWALStoreV3FenceTouchesNoByteBeforeTheHead`, `TestWALStoreV3RecoversAHistoryEndingAtTheLastRepresentableCursor` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3FenceRangesAreExact` (`core/storage/recovery_v3_test.go`) | `WALFormat` `NoResurrection` (claude05) | STUB |
| `INV-FE-FUA-SYNC-001` | A FUA write completes only after `Sync` succeeds. | M1 Serving (frontend) | `core/frontend/nvme/io.go` `IOHandler.write`; `core/frontend/ublk/dispatch.go` `handler.serve` | `TestNVMeWriteFUACompletion` (`core/frontend/nvme/fua_test.go`); `TestDispatch_WriteFUASyncsBeforeCompleting` (`core/frontend/ublk/dispatch_test.go`) | — | ACTIVE |
| `INV-FE-FLUSH-SYNC-001` | A flush is a `Sync` of the backend, and a failed `Sync` fails the command instead of acknowledging it. | M1 Serving (frontend) | `core/frontend/nvme/io.go` `IOHandler.Handle`; `core/frontend/ublk/dispatch.go` `handler.serve` | `TestT3b_NVMe_Flush_DispatchesToBackend` (`core/frontend/nvme/t3b_flush_test.go`); `TestDispatch_FlushSyncs`, `TestDispatch_BackendFailuresAreReportedNotAcknowledged` (`core/frontend/ublk/dispatch_test.go`) | — | ACTIVE |