From 8bdaf88f666e096910a84095bfec09e1256d50c5 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 03:38:12 -0800 Subject: [PATCH] fix(storage): serialize WAL reuse with dirty retirement and revalidate catch-up reclamation --- seaweed-block/core/storage/flusher.go | 6 + .../core/storage/format_v3_test_support.go | 3 + .../storage/walstore_map_checkpoint_v3.go | 51 +++++++- .../core/storage/walstore_reclaim_v3_test.go | 116 ++++++++++++++++++ .../core/storage/walstore_recovery.go | 9 +- seaweed-block/core/storage/walstore_v3.go | 14 +++ .../core/transport/catchup_format_v3_test.go | 64 ++++++++++ seaweed-block/docs/design/invariants.md | 4 +- 8 files changed, 261 insertions(+), 6 deletions(-) diff --git a/seaweed-block/core/storage/flusher.go b/seaweed-block/core/storage/flusher.go index 6ef8e25607..ad587a4d6b 100644 --- a/seaweed-block/core/storage/flusher.go +++ b/seaweed-block/core/storage/flusher.go @@ -58,6 +58,8 @@ type flusher struct { afterSnapshotForTest func() // Pauses after materialization/fsync, before map proof preparation. Tests only. afterExtentSyncForTest func() + // Pauses after checkpoint/reuse publication, before the outer DM cleanup. + afterCheckpointForTest func() } type flusherConfig struct { @@ -266,6 +268,10 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) { } } + if f.afterCheckpointForTest != nil { + f.afterCheckpointForTest() + } + // Step 4: remove flushed entries from the dirty map using // compare-and-delete. If a concurrent Write() bumped an entry's // LSN after our snapshot, this leaves the newer entry alone. diff --git a/seaweed-block/core/storage/format_v3_test_support.go b/seaweed-block/core/storage/format_v3_test_support.go index 911bfef3e9..ad932eae5c 100644 --- a/seaweed-block/core/storage/format_v3_test_support.go +++ b/seaweed-block/core/storage/format_v3_test_support.go @@ -43,6 +43,9 @@ func SetInstallHooksV3Test(s *WALStore, beforeAdmit, admitted func()) { // scan, before source-lifetime revalidation. Set before starting the sender. func SetScanReadV3Test(s *WALStore, hook func()) { s.v3.testScanRead = hook } +// SetScanBeforeReadV3Test parks a real sender after capture, before WAL I/O. +func SetScanBeforeReadV3Test(s *WALStore, hook func()) { s.v3.testScanBeforeRead = hook } + // BaseStateV3Test reports the selected descriptor's BASE state and ID. func BaseStateV3Test(s *WALStore) (BaseState, [16]byte) { d := s.v3.pub.current() diff --git a/seaweed-block/core/storage/walstore_map_checkpoint_v3.go b/seaweed-block/core/storage/walstore_map_checkpoint_v3.go index 7bbc72d014..568eefa2fe 100644 --- a/seaweed-block/core/storage/walstore_map_checkpoint_v3.go +++ b/seaweed-block/core/storage/walstore_map_checkpoint_v3.go @@ -64,7 +64,14 @@ func (s *WALStore) persistOwnedMapCheckpointV3(highestLSN, recoveryGen uint64) e } } if cp <= v.pub.current().CheckpointLSN { - return nil + v.syncMu.Lock() + defer v.syncMu.Unlock() + s.mu.Lock() + defer s.mu.Unlock() + if !v.flushLifetimeValidV3(recoveryGen) { + return ErrMapCoverageStale + } + return s.rolloverCheckpointV3Locked() } // The extent was fsynced by the flusher. d, err := s.publishCheckpointV3(cp, false, recoveryGen) @@ -131,7 +138,12 @@ func (s *WALStore) publishCheckpointV3(cp uint64, seed bool, recoveryGen uint64) // An incomplete BASE still needs its entire install-lane suffix. tail = min(tail, current.BaseCursor) } - d, err := v.pub.publishMapV3(&s.mu, nil, prepared, func(n *descriptorV3) error { + // Keep writer admission excluded until both durable publications AND the + // old dirty references are settled. The ordinary publisher releases a + // supplied store lock before I/O, so acquire it here and pass nil instead. + s.mu.Lock() + defer s.mu.Unlock() + d, err := v.pub.publishMapV3(nil, nil, prepared, func(n *descriptorV3) error { n.W = max(n.W, wack) n.CheckpointLSN = cp n.RetainedTail = max(n.RetainedTail, tail) @@ -147,9 +159,44 @@ func (s *WALStore) publishCheckpointV3(cp uint64, seed bool, recoveryGen uint64) if _, err := v.pub.rolloverIfPinned(); err != nil { return descriptorV3{}, err } + // Only a successful checkpoint plus rollover may retire retry ownership. + // Every current entry <= cp is durable in extent (a newer concurrent write + // has a higher LSN and survives). No writer can reuse a released slot until + // this store lock is released, after these references have disappeared. + s.retireCheckpointDirtyV3Locked(d.CheckpointLSN) if seed { v.appended.Store(max(v.appended.Load(), cp)) v.wack.Store(wack) } return d, nil } + +// Caller holds store.mu; the successful durable checkpoint proves the current +// versions at/below cp are in extent. Each shard preserves newer WAL entries. +func (s *WALStore) retireCheckpointDirtyV3Locked(cp uint64) { + for i := range s.dm.shards { + shard := &s.dm.shards[i] + shard.mu.Lock() + for lba, e := range shard.m { + if e.lsn <= cp { + delete(shard.m, lba) + } + } + shard.mu.Unlock() + } +} + +// Caller holds store.mu (and, except write admission, the leader role). +// No writer may use the newly released floor until its obsolete dirty +// references are retired. On failure keep those exact retry entries. +func (s *WALStore) rolloverCheckpointV3Locked() error { + d, floor, valid := s.v3.pub.walSnapshotV3() + if valid && floor >= d.RetainedTail { + return nil + } + if _, err := s.v3.pub.rolloverIfPinned(); err != nil { + return err + } + s.retireCheckpointDirtyV3Locked(d.CheckpointLSN) + return nil +} diff --git a/seaweed-block/core/storage/walstore_reclaim_v3_test.go b/seaweed-block/core/storage/walstore_reclaim_v3_test.go index e33368885a..345ef81f1a 100644 --- a/seaweed-block/core/storage/walstore_reclaim_v3_test.go +++ b/seaweed-block/core/storage/walstore_reclaim_v3_test.go @@ -123,9 +123,20 @@ func TestWALStoreV3ReclaimSecondSlotFailureKeepsOldPin(t *testing.T) { } return writeSlot(off, data) } + before := s.dm.snapshot() if err := s.flusher.flushOnce(); !errors.Is(err, ErrDescriptorPublishUncertain) || writes != 2 { t.Fatalf("rollover failure was not surfaced: writes=%d err=%v", writes, err) } + after := s.dm.snapshot() + if len(before) == 0 || len(after) != len(before) { + t.Fatalf("failed rollover changed dirty retry count: before=%+v after=%+v", before, after) + } + for _, e := range before { + off, dataOff, lsn, length, ok := s.dm.get(e.LBA) + if !ok || off != e.WALOffset || dataOff != e.DataOffset || lsn != e.LSN || length != e.Length { + t.Fatalf("failed rollover changed retry identity for %+v", e) + } + } if floor, valid := s.v3.pub.reuseFloor(); valid && floor != 0 { t.Fatalf("failed rollover granted reuse over the old slot: floor=%d", floor) } @@ -195,3 +206,108 @@ func TestWALStoreV3ReclaimAfterInstallingPhysicalReopen(t *testing.T) { t.Fatalf("recovered install bytes: %v", err) } } + +// Hold the actual flusher after its durable publication, before its outer +// cleanup, then make the writer reuse the old dirty entry's physical slot. +func TestWALStoreV3ReclaimRetiresReferencesBeforeReuse(t *testing.T) { + path := filepath.Join(t.TempDir(), "volume") + s, err := createMappedWALStoreV3ForTest(path, 32, 4096, 64*1024, WModeStrict, 4) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = s.Close() }) + for i := uint32(0); i < 15; i++ { + if _, err := s.Write(i, blk(byte(i+1))); err != nil { + t.Fatal(err) + } + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + s.flusher.afterCheckpointForTest = func() { + s.flusher.afterCheckpointForTest = nil + if _, err := s.Write(15, blk(16)); err != nil { + t.Fatal(err) + } + if got, err := s.Read(0); err != nil || !bytes.Equal(got, blk(1)) { + t.Fatalf("durable old extent must remain readable during physical WAL reuse: %v", err) + } + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + if got, err := s.Read(15); err != nil || !bytes.Equal(got, blk(16)) { + t.Fatalf("new dirty version was not preserved: %v", err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + crashReadOnlyStoreV3(t, s) + r, err := openWALStoreV3ForTest(path) + if err != nil { + t.Fatal(err) + } + defer r.Close() + if _, err := r.Recover(); err != nil { + t.Fatal(err) + } + for lba, want := range map[uint32][]byte{0: blk(1), 15: blk(16)} { + if got, err := r.Read(lba); err != nil || !bytes.Equal(got, want) { + t.Fatalf("post-reuse crash-style reopen LBA%d: %v", lba, err) + } + } +} + +func TestWALStoreV3ReclaimRolloverProgressWithoutNewCheckpoint(t *testing.T) { + for _, trigger := range []string{"idle", "unchanged-checkpoint", "admission", "batch-admission"} { + t.Run(trigger, func(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + s.SetRecoveryRetentionLSNs(2) + writeSynced(t, s, 0, 1) + writeSynced(t, s, 1, 2) + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + d := s.v3.pub.current() + s.SetRecoveryRetentionLSNs(1) + tail := s.v3.w.reclaimThroughV3(d.CheckpointLSN - 1) + // Model a completed first-slot checkpoint publication before its idle + // fallback rollover, with already-durable map/checkpoint and extent. + if _, err := s.v3.pub.publish(nil, nil, func(n *descriptorV3) error { + n.RetainedTail = tail + n.RetainedHead = max(n.RetainedHead, tail) + return nil + }); err != nil { + t.Fatal(err) + } + if floor, ok := s.v3.pub.reuseFloor(); !ok || floor >= tail { + t.Fatal("setup lacks a pinned fallback") + } + switch trigger { + case "idle": + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + case "unchanged-checkpoint": + if err := s.persistOwnedMapCheckpointV3(d.CheckpointLSN, s.v3.recoverGen.Load()); err != nil { + t.Fatal(err) + } + case "batch-admission": + if _, err := s.WriteBatch(2, [][]byte{blk(3), blk(4)}); err != nil { + t.Fatal(err) + } + case "admission": + if _, err := s.Write(2, blk(3)); err != nil { + t.Fatal(err) + } + } + if floor, ok := s.v3.pub.reuseFloor(); !ok || floor != tail { + t.Fatalf("%s did not settle old-slot pin without a new checkpoint: floor=%d want=%d valid=%v", trigger, floor, tail, ok) + } + if got := s.v3.pub.current().CheckpointLSN; got != d.CheckpointLSN { + t.Fatalf("trigger fabricated checkpoint progress: %d", got) + } + }) + } +} diff --git a/seaweed-block/core/storage/walstore_recovery.go b/seaweed-block/core/storage/walstore_recovery.go index 3a641344d2..b833ccfaec 100644 --- a/seaweed-block/core/storage/walstore_recovery.go +++ b/seaweed-block/core/storage/walstore_recovery.go @@ -275,7 +275,7 @@ func (s *WALStore) scanLBAsV3(fromLSN uint64, fn func(RecoveryEntry) error) erro installEpoch := v.installEpoch d := v.pub.current() headLSN := s.nextLSN - checkpointLSN, retentionLSNs := s.checkpointLSN, s.recoveryRetentionLSNs + checkpointLSN, retentionLSNs := d.CheckpointLSN, s.recoveryRetentionLSNs s.mu.RUnlock() if d.BaseState == BaseInstalling { return fmt.Errorf("%w: catch-up from an installing source", ErrBaseInstalling) @@ -302,6 +302,9 @@ func (s *WALStore) scanLBAsV3(fromLSN uint64, fn func(RecoveryEntry) error) erro if fromLSN >= headLSN { return nil } + if h := v.testScanBeforeRead; h != nil { + h() + } scan, err := scanWALV3(s.fd, d) if err != nil { return fmt.Errorf("storage: walstore ScanLBAs (v3): %w", err) @@ -313,7 +316,9 @@ func (s *WALStore) scanLBAsV3(fromLSN uint64, fn func(RecoveryEntry) error) erro now := v.pub.current() stable := v.recoverGen.Load() == gen && v.installEpoch == installEpoch && now.Nonce == d.Nonce && now.BaseState == d.BaseState && - now.BaseInstallID == d.BaseInstallID + now.BaseInstallID == d.BaseInstallID && now.BaseCursor == d.BaseCursor && + now.RetainedTail == d.RetainedTail && now.CheckpointLSN == d.CheckpointLSN && + s.recoveryRetentionLSNs == retentionLSNs s.mu.RUnlock() if !stable { if now.BaseState == BaseInstalling { diff --git a/seaweed-block/core/storage/walstore_v3.go b/seaweed-block/core/storage/walstore_v3.go index 7fdfc8c12a..11dfd550d9 100644 --- a/seaweed-block/core/storage/walstore_v3.go +++ b/seaweed-block/core/storage/walstore_v3.go @@ -126,6 +126,8 @@ type walStoreV3State struct { // testScanRead runs in a v3 ScanLBAs after its scan and before its // revalidation. testScanRead func() + // Pauses after the capture, before physical scan I/O. Tests only. + testScanBeforeRead func() } // errV3RecoveredMeanwhile: a recovery ran between an outer Sync's capture @@ -585,6 +587,9 @@ func (s *WALStore) appendWriteV3(lba uint32, data []byte, lsn uint64) (uint64, e return 0, err } } + if err := s.rolloverCheckpointV3Locked(); err != nil { + return 0, err + } phys, err := s.v3.w.append(e, s.v3.wack.Load()) if err != nil { if errors.Is(err, errWALPwrite) { @@ -631,6 +636,9 @@ func (s *WALStore) writeBatchV3Locked(startLBA uint32, blocks [][]byte, firstLSN } } e := walEntryV3{LSN: firstLSN, BatchCount: n, Type: walEntryWriteBatch, LBA: uint64(startLBA), Length: uint32(len(payload)), Data: payload} + if err := s.rolloverCheckpointV3Locked(); err != nil { + return nil, err + } phys, err := s.v3.w.append(e, s.v3.wack.Load()) s.walMutation.Add(1) if err != nil { @@ -750,6 +758,12 @@ func (s *WALStore) refreshW() error { } v.syncMu.Lock() defer v.syncMu.Unlock() + s.mu.Lock() + rolloverErr := s.rolloverCheckpointV3Locked() + s.mu.Unlock() + if rolloverErr != nil { + return rolloverErr + } wack := v.wack.Load() if wack <= v.pub.current().W { return nil diff --git a/seaweed-block/core/transport/catchup_format_v3_test.go b/seaweed-block/core/transport/catchup_format_v3_test.go index 60d8efe88c..4c78884114 100644 --- a/seaweed-block/core/transport/catchup_format_v3_test.go +++ b/seaweed-block/core/transport/catchup_format_v3_test.go @@ -318,3 +318,67 @@ func TestCatchUpV3CompletedBASESuffix(t *testing.T) { }) } } + +func TestCatchUpV3ScanOverlappingCheckpointReuseIsRecycled(t *testing.T) { + primary, err := storage.CreateMappedWALStoreV3Test(filepath.Join(t.TempDir(), "primary.v3"), 64, v3RepBlock, 4) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = primary.Close() }) + primary.DisableAutoFlushForRecoveryTest() + for i := 1; i <= 250; i++ { + if _, err := primary.Write(0, v3RepBlk(byte(i))); err != nil { + t.Fatal(err) + } + } + if _, err := primary.Sync(); err != nil { + t.Fatal(err) + } + parked, resume := make(chan struct{}), make(chan struct{}) + var releaseOnce sync.Once + release := func() { releaseOnce.Do(func() { close(resume) }) } + defer release() + var scans atomic.Int32 + storage.SetScanBeforeReadV3Test(primary, func() { + if scans.Add(1) == 1 { + close(parked) + <-resume + } + }) + replica := v3Rep(t) + l := v3Listen(t, replica) + exec := NewBlockExecutor(primary, l.Addr()) + closed := make(chan adapter.SessionCloseResult, 1) + exec.SetOnSessionClose(func(r adapter.SessionCloseResult) { closed <- r }) + if err := exec.StartCatchUp("r1", 1, 1, 1, 1, 251); err != nil { + t.Fatal(err) + } + select { + case <-parked: + case <-time.After(5 * time.Second): + t.Fatal("sender did not capture old tail") + } + if err := storage.FlushMappedWALStoreV3Test(primary); err != nil { + t.Fatal(err) + } + for i := 251; i <= 270; i++ { + if _, err := primary.Write(0, v3RepBlk(byte(i%256))); err != nil { + t.Fatal(err) + } + } + if _, err := primary.Sync(); err != nil { + t.Fatal(err) + } + release() + select { + case result := <-closed: + if result.Success || result.FailureKind != engine.RecoveryFailureWALRecycled { + t.Fatalf("overlapped real reuse must route to rebuild, never false corruption: %+v", result) + } + case <-time.After(5 * time.Second): + t.Fatal("sender did not finish") + } + if got := v3Read(t, replica, 0); !bytes.Equal(got, make([]byte, v3RepBlock)) { + t.Fatal("failed catch-up emitted a partial replay") + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 0dd431221b..8c4b976479 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -63,7 +63,7 @@ stateDiagram-v2 | FaultLatched | FaultLatched | every later `Sync`, write, checkpoint and `Recover` on the same open store is refused | `core/storage/walstore.go` `stickyIOFault` | `INV-WAL-FSYNC-STICKY-001` | | any | Closed | `Close`; a store with a latched fault does not write the final superblock | `core/storage/walstore.go` `WALStore.Close` | — | -The format-v3 record codec (plan row 2) is dark: no production M1 transition selects it yet. Its framing/validation boundary is tested separately (`INV-WAL-V3-RECORD-001`); writer/cursor/lap admission and production activation land in later ordered rows. Existing machine diagrams and ACTIVE recovery guards are unchanged. Before reading v3 slots, both read/write and offline read-only open acquire an exclusive nonblocking file lock; the offline migration CLI acquires the same lock before any descriptor read or mutation (`INV-WAL-V3-OWNER-001`). Contention refuses open/migration without changing bytes; descriptor close or process exit releases ownership. This implements the existing offline-migration precondition, not a new serving state. The mapped v3 checkpoint also carries a complete-record physical tail through the covered LSN minus the configured retention window; partial batches remain retained. The existing sole publisher then performs metadata-only rollover when the fallback still pins that prefix. Reuse still requires both valid same-nonce slot tails; a failed rollover latches and grants no reuse (`INV-WAL-V3-RECLAIM-001`). +The format-v3 record codec (plan row 2) is dark: no production M1 transition selects it yet. Its framing/validation boundary is tested separately (`INV-WAL-V3-RECORD-001`); writer/cursor/lap admission and production activation land in later ordered rows. Existing machine diagrams and ACTIVE recovery guards are unchanged. Before reading v3 slots, both read/write and offline read-only open acquire an exclusive nonblocking file lock; the offline migration CLI acquires the same lock before any descriptor read or mutation (`INV-WAL-V3-OWNER-001`). Contention refuses open/migration without changing bytes; descriptor close or process exit releases ownership. This implements the existing offline-migration precondition, not a new serving state. The mapped v3 checkpoint also carries a complete-record physical tail through the covered LSN minus the configured retention window; partial batches remain retained. The existing sole publisher then performs metadata-only rollover when the fallback still pins that prefix. Reuse still requires both valid same-nonce slot tails and retirement of checkpointed dirty references under writer exclusion; idle, unchanged-checkpoint and admission paths also settle a pinned fallback. An unlocked catch-up scan revalidates the coherent checkpoint and tail before emitting anything. A failed rollover latches and grants no reuse (`INV-WAL-V3-RECLAIM-001`). Recovery warnings such as `wal_hole_suspected` are recorded in Serving without changing health (`INV-WAL-WARN-NO-HEALTH-001`). The open gaps of this machine (a corrupted synced record mid-history only warns; forged records in user data) are listed in the [core known issues](block-design.md#24-known-issues-and-work-in-progress) and are not ledger rows. @@ -281,7 +281,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-WAL-V3-DESCRIPTOR-001` | A v3 descriptor slot is used only if it is valid. It needs a matching CRC32C (Castagnoli), every reserved byte zero, an accepted impl, a nonzero slotGen at most 2^64-2 and a nonzero nonce. Its geometry must be consistent with checked arithmetic, its BASE fields must follow their per-state rules, and CheckpointLSN ≤ mapCoveredCheckpoint ≤ W must hold. Of the two slots, the valid selectable one with the higher slotGen wins. A prepared migration slot is never selected. Equal generations with different bytes, or slots that disagree on identity or geometry, are refused. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `decodeSlotV3`, `selectSlotV3`, `nextSlotGenV3` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3Selection`, `TestSlotV3CounterExhaustion`, `TestSlotV3InstalledMayHaveCursorBelowTail` (`core/storage/superblock_v3_test.go`) | — | STUB | | `INV-WAL-V3-RECORD-001` | A dark impl-3 record codec uses the fixed 62-byte prefix and 70-byte overhead, CRC32C and an explicit EntrySize. It refuses unknown types/flags, a zero nonce, invalid per-type geometry, overflowing count/LSN/cursor or LBA spans, nonzero padding, bad CRC/footer and truncation before allocating a payload. Codec success alone is not nonce/cursor/lap replay admission. | M1 (v3 codec only; no production transition yet) | `core/storage/wal_entry_v3.go` `payloadSizeV3`, `encodeWALEntryV3`, `decodeWALEntryV3` | `TestWALEntryV3_CanonicalBarrierBytes`, `TestWALEntryV3_TypeFootprints`, `TestWALEntryV3_RefusesInvalidEncode`, `TestWALEntryV3_RefusesMalformedWire`, `FuzzWALEntryV3_DecodeNeverPanics` | `WALRecovery` abstract record validity; physical byte rules are code-test obligations | STUB | | `INV-WAL-V3-LSN-ORDER-001` | A dark v3 writer accepts only a first LSN above its highest consumed LSN; a batch consumes its whole validated range. Equal/lower requests return ErrWALLSNOrder before any pwrite or cursor change. Constructor coverage and a recovered kept frontier count as consumed; a fenced-away suffix does not. | M1 (dark append only) | `core/storage/wal_io_v3.go` `append`, `newWALWriterV3`, `restoreScanV3` | `TestWALLSNOrderV3_RefusesDuplicateAndLower`, `TestWALLSNOrderV3_BatchConsumesFullRange`, `TestWALLSNOrderV3_RestoreUsesKeptNotDroppedFrontier`, `TestWALLSNOrderV3_DescriptorFloorIsAlreadyConsumed`, `TestWALIOV3_ValidatedFrontierIntervals`, `TestWALIOV3_ConcurrentAppendsHaveUniqueCursors` | Physical LSN-strict prefix is a contract constraint; r16 model correspondence is pending | STUB | -| `INV-WAL-V3-RECLAIM-001` | A mapped v3 checkpoint releases only complete validated record ends covered by the checkpoint and outside the retention window; an installing BASE retains its install suffix. Physical recovery rebuilds the volatile boundary index only from the trusted kept scan, without restoring a disconnect cursor. Tail/head/map/checkpoint/W publish together, followed by metadata-only rollover; both slot tails still pin reuse. Failure grants no reuse and retains retry work. | M1 checkpoint / existing two-slot retirement | `wal_io_v3.go` `reclaimThroughV3`, `rememberReclaimScanV3`; `walstore_map_checkpoint_v3.go` `publishCheckpointV3`; `descriptor_v3.go` `rolloverIfPinned` | `TestWALStoreV3CheckpointReclaimsAcrossRingLaps`, `TestWALStoreV3ReclaimKeepsPartialBatchAndRetention`, `TestWALStoreV3ReclaimRebuildsIndexAfterPhysicalRecovery`, `TestWALStoreV3ReclaimAfterInstallingPhysicalReopen`, `TestWALStoreV3ReclaimSecondSlotFailureKeepsOldPin`, tagged `TestCatchUpV3AfterCheckpointRingReuse` | Existing dual-slot retirement and nonce/cursor contract; concrete index/recovery/caller wiring is a code-test obligation | STUB | +| `INV-WAL-V3-RECLAIM-001` | A mapped v3 checkpoint releases only complete validated record ends covered by the checkpoint and outside the retention window; an installing BASE retains its install suffix. Physical recovery rebuilds the volatile boundary index only from the trusted kept scan, without restoring a disconnect cursor. Tail/head/map/checkpoint/W publish together, followed by metadata-only rollover; both slot tails still pin reuse. Failure grants no reuse and retains exact dirty retry identity. Checkpoint publication excludes writer admission through both-slot rollover and dirty-reference retirement. Idle, unchanged-checkpoint and admission settle pending rollover; catch-up revalidates tail/checkpoint before delivering its buffered scan. | M1 checkpoint / existing two-slot retirement | `wal_io_v3.go` `reclaimThroughV3`, `rememberReclaimScanV3`; `walstore_map_checkpoint_v3.go` `publishCheckpointV3`; `descriptor_v3.go` `rolloverIfPinned` | `TestWALStoreV3CheckpointReclaimsAcrossRingLaps`, `TestWALStoreV3ReclaimKeepsPartialBatchAndRetention`, `TestWALStoreV3ReclaimRebuildsIndexAfterPhysicalRecovery`, `TestWALStoreV3ReclaimAfterInstallingPhysicalReopen`, `TestWALStoreV3ReclaimSecondSlotFailureKeepsOldPin`, `TestWALStoreV3ReclaimRetiresReferencesBeforeReuse`, `TestWALStoreV3ReclaimRolloverProgressWithoutNewCheckpoint`, tagged `TestCatchUpV3AfterCheckpointRingReuse`, `TestCatchUpV3ScanOverlappingCheckpointReuseIsRecycled` | Existing dual-slot retirement and nonce/cursor contract; concrete index/recovery/caller wiring is a code-test obligation | STUB | | `INV-WAL-V3-OWNER-001` | v3 read/write open, offline readonly open and migrate-v3 acquire the same exclusive nonblocking OS file lock before reading slots or changing bytes. Contention refuses with volume locked; descriptor close releases it, allowing retry. | M1 open admission / offline migration precondition | `core/storage/volume_lock*.go`; `walstore_v3.go`; `walstore_readonly_v3.go`; `cmd/sw-block/migrate.go` | `TestMigrateV3RefusesAnOpenV3Volume`, `TestMigrateV3ExcludesOpenUntilCommitFinishes` (tag `swblock_format_v3_test`), `TestWALStoreV3OwnerExcludesOpenAndReadOnly` | OS mutual exclusion is a caller obligation, outside the abstract crash model; existing open states unchanged | STUB | | `INV-WAL-V3-CATCHUP-001` | A dark v3 catch-up source refuses while installing, including an empty at-head request. Requests covered by an installed BASE require rebuild (typed WALRecycled); damage in retained WAL remains an integrity failure. Before emitting any entries the scan revalidates recovery generation, nonce, BASE state/ID and install epoch, so begin/complete/retire ABA cannot publish a superseded prefix. | M1 BASE lifecycle / M3 CatchingUp (dark callers) | `core/storage/walstore_recovery.go` `ScanLBAs`, `scanLBAsV3`, `v3CatchUpEntries` | `TestCatchUpV3InstallingAtHeadRefuses`, `TestCatchUpV3CompletedBASEUsesRebuild`, `TestCatchUpV3InstallRetireABARefusesOldScan`, `TestCatchUpV3CorruptFirstRecordFails`, `TestCatchUpV3CorruptMiddleRecordFails`, `TestCatchUpV3CompletedBASESuffix` (tag `swblock_format_v3_test`, actual catch-up sender) | Existing BASE and catch-up transitions unchanged; this physical scan/source-lifetime obligation is covered by deterministic caller tests | STUB | | `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 |