diff --git a/seaweed-block/core/storage/flusher.go b/seaweed-block/core/storage/flusher.go index 285be2a33b..77c8825a5f 100644 --- a/seaweed-block/core/storage/flusher.go +++ b/seaweed-block/core/storage/flusher.go @@ -170,6 +170,9 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) { entries := store.dm.snapshot() store.mu.RUnlock() if len(entries) == 0 { + if store.v3 != nil { + return store.refreshW() // the mode-C idle refresh (DESIGN 6.2) + } return nil } if f.afterSnapshotForTest != nil { @@ -252,6 +255,9 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) { store.dm.compareAndDelete(e.LBA, e.LSN) } f.flushes.Add(1) + if store.v3 != nil { + return store.refreshW() // the mode-C idle refresh (DESIGN 6.2) + } return nil } diff --git a/seaweed-block/core/storage/walstore.go b/seaweed-block/core/storage/walstore.go index f938facd61..6f084e834d 100644 --- a/seaweed-block/core/storage/walstore.go +++ b/seaweed-block/core/storage/walstore.go @@ -1000,6 +1000,9 @@ func (s *WALStore) readFromExtent(lba uint32) ([]byte, error) { // written: re-resolve through the normal path (dirty map/WAL first) // before the extent. No lock is held here. if walRelOff, dataOffset, _, _, ok := s.dm.get(uint64(lba)); ok { + if s.v3 != nil { + return s.readFromWALV3(walRelOff) + } return s.readFromWAL(walRelOff, dataOffset) } } diff --git a/seaweed-block/core/storage/walstore_v3.go b/seaweed-block/core/storage/walstore_v3.go index 82095b435a..0af54406d9 100644 --- a/seaweed-block/core/storage/walstore_v3.go +++ b/seaweed-block/core/storage/walstore_v3.go @@ -205,6 +205,11 @@ func (s *WALStore) recoverV3() (uint64, error) { s.dm.clear() scan, err := scanWALV3(s.fd, d) if err != nil { + if d.BaseState == BaseInstalling { + // Installing keeps its typed not-ready outcome; the cause is a + // substrate error, not proven install-log damage (codex01 5b P2). + return 0, fmt.Errorf("%w: scan: %w", ErrBaseIncomplete, err) + } return 0, err } recs := make([]trustedRecordV3, 0, len(scan.Records)) @@ -262,8 +267,12 @@ func (s *WALStore) recoverV3() (uint64, error) { if s.walTail == 0 && o.R > 0 { s.walTail = 1 } + // The volatile acknowledged frontier is the recovered prefix, never an + // older in-memory maximum: a same-open recovery that dropped mode C's + // newest batch must not let a later refresh publish a W the WAL no + // longer holds (codex01 5b P1). v.appended.Store(o.R) - v.wack.Store(max(v.wack.Load(), o.R)) + v.wack.Store(o.R) return s.syncedLSN, nil } diff --git a/seaweed-block/core/storage/walstore_v3_test.go b/seaweed-block/core/storage/walstore_v3_test.go index 40afe74135..34921eadc6 100644 --- a/seaweed-block/core/storage/walstore_v3_test.go +++ b/seaweed-block/core/storage/walstore_v3_test.go @@ -8,6 +8,7 @@ import ( "runtime" "sync" "testing" + "time" ) // Row 5/5b store-level controls on the REAL *WALStore in its v3 mode @@ -411,6 +412,8 @@ func TestWALStoreV3SyncRechecksTheFaultAtTheAckBoundary(t *testing.T) { } prev := s.v3.wack.Load() parked, release := make(chan struct{}), make(chan struct{}) + rel := sync.OnceFunc(func() { close(release) }) + t.Cleanup(rel) var once sync.Once s.v3.testBeforeSlotWrite = func() error { once.Do(func() { close(parked); <-release }) @@ -418,20 +421,24 @@ func TestWALStoreV3SyncRechecksTheFaultAtTheAckBoundary(t *testing.T) { } aErr := make(chan error, 1) go func() { _, err := s.Sync(); aErr <- err }() - <-parked + waitV3(t, parked, "the parked publication") boom := errors.New("injected append write error") s.v3.w.writeAt = func([]byte, int64) (int, error) { return 0, boom } bErr := make(chan error, 1) go func() { _, err := s.Write(3, blk(3)); bErr <- err }() + deadline := time.Now().Add(10 * time.Second) for s.mu.TryLock() { // wait until B holds s.mu (it then blocks on descMu) s.mu.Unlock() + if time.Now().After(deadline) { + t.Fatal("timed out waiting for B to take s.mu") + } runtime.Gosched() } - close(release) - if err := <-bErr; !errors.Is(err, boom) { + rel() + if err := recvErrV3(t, bErr, "B"); !errors.Is(err, boom) { t.Fatalf("mode %d: B: err = %v, want the append write error", mode, err) } - if err := <-aErr; err == nil { + if err := recvErrV3(t, aErr, "A"); err == nil { t.Fatalf("mode %d: A acknowledged after B latched the store fault", mode) } if got := s.v3.wack.Load(); got != prev { @@ -479,6 +486,8 @@ func TestWALStoreV3SetWModeWaitsForAHeldBatch(t *testing.T) { t.Fatal(err) } parked, release := make(chan struct{}), make(chan struct{}) + rel := sync.OnceFunc(func() { close(release) }) + t.Cleanup(rel) var once sync.Once s.v3.testBeforeSlotWrite = func() error { once.Do(func() { close(parked); <-release }) @@ -486,7 +495,7 @@ func TestWALStoreV3SetWModeWaitsForAHeldBatch(t *testing.T) { } aErr := make(chan error, 1) go func() { _, err := s.Sync(); aErr <- err }() - <-parked + waitV3(t, parked, "the parked publication") setErr := make(chan error, 1) go func() { setErr <- s.SetWMode(WModeStrict) }() select { @@ -494,11 +503,11 @@ func TestWALStoreV3SetWModeWaitsForAHeldBatch(t *testing.T) { t.Fatalf("SetWMode returned (%v) while a C batch was held", err) default: } - close(release) - if err := <-aErr; err != nil { + rel() + if err := recvErrV3(t, aErr, "A"); err != nil { t.Fatal(err) } - if err := <-setErr; err != nil { + if err := recvErrV3(t, setErr, "SetWMode"); err != nil { t.Fatal(err) } cur := s.v3.pub.current() @@ -520,10 +529,12 @@ func TestWALStoreV3NoBatchAcksUnderAStaleModeAfterSetWMode(t *testing.T) { defer crashRecoveryHardeningStore(t, s) writeSynced(t, s, 1, 1) parked, release := make(chan struct{}), make(chan struct{}) + rel := sync.OnceFunc(func() { close(release) }) + t.Cleanup(rel) s.v3.testSetWModeHoldingRole = func() { close(parked); <-release } setErr := make(chan error, 1) go func() { setErr <- s.SetWMode(WModeStrict) }() // parks holding the leader role, before publishing - <-parked + waitV3(t, parked, "the parked publication") if _, err := s.Write(2, blk(2)); err != nil { t.Fatal(err) } @@ -532,12 +543,12 @@ func TestWALStoreV3NoBatchAcksUnderAStaleModeAfterSetWMode(t *testing.T) { s.v3.testLeaderWaiting = func() { wonce.Do(func() { close(waiting) }) } bErr := make(chan error, 1) go func() { _, err := s.Sync(); bErr <- err }() - <-waiting // B is about to take the leader role SetWMode holds - close(release) - if err := <-setErr; err != nil { + waitV3(t, waiting, "B at the leader role") // B is about to take the leader role SetWMode holds + rel() + if err := recvErrV3(t, setErr, "SetWMode"); err != nil { t.Fatal(err) } - if err := <-bErr; err != nil { + if err := recvErrV3(t, bErr, "B"); err != nil { t.Fatal(err) } if cur := s.v3.pub.current(); cur.WMode != WModeStrict || cur.W != 2 { @@ -577,3 +588,122 @@ func TestWALStoreV3SetWModeCrashCases(t *testing.T) { t.Fatalf("a failed SetWMode changed the mode on disk: %d", m) } } + +func waitV3(t *testing.T, ch <-chan struct{}, what string) { + t.Helper() + select { + case <-ch: + case <-time.After(10 * time.Second): + t.Fatalf("timed out waiting for %s", what) + } +} + +func recvErrV3(t *testing.T, ch <-chan error, what string) error { + t.Helper() + select { + case err := <-ch: + return err + case <-time.After(10 * time.Second): + t.Fatalf("timed out waiting for %s", what) + return nil + } +} + +// codex01 5b P1: a SAME-instance recovery that drops mode C's newest batch +// resets the acknowledged frontier to R, so a later refresh cannot publish +// a W the WAL no longer holds and the next Recover does not report a false +// corruption. Fresh-open tests mask this (they start from the slot W). +func TestWALStoreV3SameOpenRecoverResetsTheAcknowledgedFrontier(t *testing.T) { + s, path := newStoreV3(t, WModeLagged) + defer crashRecoveryHardeningStore(t, s) + writeSynced(t, s, 1, 2) // slot W 1 (lagged), acknowledged W 2 + damageRecord(t, path, 2) + rec1 := recordOffset(t, path, 1) + before, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if _, err := s.Recover(); err != nil { + t.Fatalf("same-open Recover with the newest C batch damaged: %v (want the documented truncation)", err) + } + if got := s.v3.wack.Load(); got != 1 { + t.Fatalf("acknowledged W after the same-open recovery = %d, want R = 1", got) + } + if err := s.refreshW(); err != nil { + t.Fatal(err) + } + if w := s.v3.pub.current().W; w > 1 { + t.Fatalf("refresh published W %d over a recovered prefix of 1", w) + } + if _, err := s.Recover(); err != nil { + t.Fatalf("second same-open Recover: %v (a false wal_corrupt from a stale W)", err) + } + after, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + end1 := rec1 + int64(walEntryHeaderSizeV3+v3TestBlock) + if !bytes.Equal(before[rec1:end1], after[rec1:end1]) { + t.Fatal("the kept record 1 changed") + } + if !bytes.Equal(after[end1:walOffsetV3+v3TestWAL], make([]byte, walOffsetV3+v3TestWAL-int(end1))) { + t.Fatal("the dropped record 2 was not fenced") + } + if !bytes.Equal(readV3(t, s, 1), blk(1)) { + t.Fatal("LBA 1 lost") + } +} + +// codex01 5b P2: a scan failure under an installing descriptor keeps the +// typed not-ready outcome and leaves the file unchanged. +func TestWALStoreV3InstallingScanErrorIsTypedNotReady(t *testing.T) { + s, path := newStoreV3(t, WModeLagged) + if _, err := s.v3.pub.publish(nil, nil, func(n *descriptorV3) error { + n.BaseState, n.BaseLSN = BaseInstalling, 0 + n.BaseCursor = n.RetainedHead + n.BaseInstallID[0] = 7 + return nil + }); err != nil { + t.Fatal(err) + } + crashRecoveryHardeningStore(t, s) + if err := os.Truncate(path, walOffsetV3+100); err != nil { // the WAL region is now short + t.Fatal(err) + } + before, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + _, err = reopenV3(t, path) + if !errors.Is(err, ErrBaseIncomplete) || errors.Is(err, ErrInstallSuffixDamaged) { + t.Fatalf("installing scan error: err = %v, want ErrBaseIncomplete (not labelled damaged)", err) + } + after, err2 := os.ReadFile(path) + if err2 != nil { + t.Fatal(err2) + } + if !bytes.Equal(before, after) { + t.Fatal("a refused installing recovery changed the file") + } +} + +// codex01 5b P2: the real flusher cycle performs the mode-C idle refresh, +// also when no dirty entries remain, so the window closes without a Sync. +func TestWALStoreV3FlusherCycleRunsTheIdleRefresh(t *testing.T) { + s, path := newStoreV3(t, WModeLagged) + writeSynced(t, s, 1, 3) // slot W 2 (lagged), acknowledged W 3 + if err := s.flusher.flushOnceInternal(false); err != nil { + t.Fatal(err) + } + if w := s.v3.pub.current().W; w != 3 { + t.Fatalf("slot W after a flusher cycle = %d, want 3 (the idle refresh)", w) + } + if err := s.flusher.flushOnceInternal(false); err != nil { // now no dirty entries + t.Fatal(err) + } + crashRecoveryHardeningStore(t, s) + damageRecord(t, path, 3) + if _, err := reopenV3(t, path); !isWALCorrupt(err) { + t.Fatalf("after the flusher's refresh: err = %v, want wal_corrupt", err) + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index e0eb529bde..527fafb71c 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -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` (`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` (`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 |