diff --git a/seaweed-block/core/storage/reset_store_v3_test.go b/seaweed-block/core/storage/reset_store_v3_test.go index b39ed6ee62..0bdfb4fa8a 100644 --- a/seaweed-block/core/storage/reset_store_v3_test.go +++ b/seaweed-block/core/storage/reset_store_v3_test.go @@ -3,6 +3,7 @@ package storage import ( "bytes" "errors" + "io" "os" "sync" "sync/atomic" @@ -375,3 +376,86 @@ func TestWALStoreV3ReadOfADamagedLiveRecordIsAnIntegrityFault(t *testing.T) { t.Fatalf("Read of a damaged live record: err = %v, want a WAL integrity failure", err) } } + +// codex01 e72acd40 P2 (1): a same-open Recover can fence a dropped record +// and re-allocate its LSN to the same LBA at the same position. A read +// parked across that saw the fenced bytes; on re-resolution the entry looks +// unchanged (same position and LSN), but it is a new write: the read must +// retry and return it, not report WAL damage. +func TestWALStoreV3ReadAcrossARecoveryThatReusesTheSamePositionAndLSNIsNotDamage(t *testing.T) { + s, path := newStoreV3(t, WModeStrict) + t.Cleanup(func() { crashRecoveryHardeningStore(t, s) }) + resolved, invalid := newHeldV3(t), newHeldV3(t) + writeSynced(t, s, 1, 1) // LSN 1 + if _, err := s.Write(1, blk(0xC1)); err != nil { // LSN 2, not acknowledged + t.Fatal(err) + } + off, _, lsn, _, _ := s.dm.get(1) + if lsn != 2 { + t.Fatalf("setup: LBA 1 dirty LSN %d, want 2", lsn) + } + s.v3.testReadResolved = resolved.hold + rd := make(chan []byte, 1) + res := resolved.start(func() error { + b, err := s.Read(1) + rd <- b + return err + }) + waitV3(t, resolved.parked, "Read after resolving LSN 2") + s.v3.testReadResolved = nil + damageRecord(t, path, 2) + if _, err := s.Recover(); err != nil { // drops LSN 2 and fences its bytes + t.Fatalf("Recover: %v", err) + } + s.v3.testReadInvalid = invalid.hold + resolved.rel() // the pread sees the fenced bytes and fails validation + waitV3(t, invalid.parked, "Read after the failed validation") + s.v3.testReadInvalid = nil + if _, err := s.Write(1, blk(0xC2)); err != nil { // LSN 2 again, same LBA + t.Fatal(err) + } + if off2, _, lsn2, _, _ := s.dm.get(1); off2 != off || lsn2 != 2 { + t.Fatalf("setup: the new write is at %d LSN %d, want the reused %d LSN 2", off2, lsn2, off) + } + invalid.rel() + if err := resolved.result(res, "Read"); err != nil { + t.Fatalf("Read across a reusing recovery: %v (a false WAL integrity failure)", err) + } + if got := <-rd; !bytes.Equal(got, blk(0xC2)) { + t.Fatalf("Read returned %x..., want the current write %x...", got[0], byte(0xC2)) + } +} + +// codex01 e72acd40 P2 (2): a failed pread is substrate I/O, never WAL +// integrity. EOF policy: the WAL region lies inside the file, so a file +// shorter than its geometry (io.EOF) is substrate I/O too. +func TestWALStoreV3ReadIOErrorsAreSubstrateIONotWALIntegrity(t *testing.T) { + isIO := func(err error) bool { + var rf *RecoveryFailure + return errors.As(err, &rf) && rf.Kind == StorageRecoveryFailureSubstrateIO + } + t.Run("short file (EOF)", func(t *testing.T) { + s, path := newStoreV3(t, WModeStrict) + t.Cleanup(func() { crashRecoveryHardeningStore(t, s) }) + writeSynced(t, s, 1, 1) + if err := os.Truncate(path, int64(walOffsetV3)); err != nil { + t.Fatal(err) + } + _, err := s.Read(1) + if !isIO(err) || isWALCorrupt(err) || !errors.Is(err, io.EOF) { + t.Fatalf("Read past the end of a truncated file: err = %v, want a substrate I/O failure wrapping io.EOF", err) + } + }) + t.Run("read error", func(t *testing.T) { + s, _ := newStoreV3(t, WModeStrict) + writeSynced(t, s, 1, 1) + s.committer.Stop() + if err := s.fd.Close(); err != nil { // every later pread fails + t.Fatal(err) + } + _, err := s.Read(1) + if !isIO(err) || isWALCorrupt(err) || !errors.Is(err, os.ErrClosed) { + t.Fatalf("Read on a failing file: err = %v, want a substrate I/O failure", err) + } + }) +} diff --git a/seaweed-block/core/storage/walstore_v3.go b/seaweed-block/core/storage/walstore_v3.go index dc08ce4b70..39955543db 100644 --- a/seaweed-block/core/storage/walstore_v3.go +++ b/seaweed-block/core/storage/walstore_v3.go @@ -75,6 +75,9 @@ type walStoreV3State struct { // testReadResolved runs in a v3 read after the dirty map resolved the // LBA's WAL position and before the record is read. testReadResolved func() + // testReadInvalid runs in a v3 read after a record failed validation and + // before the entry is re-resolved. + testReadInvalid func() } // errV3RecoveredMeanwhile: a recovery ran between an outer Sync's capture @@ -541,16 +544,22 @@ func (s *WALStore) SetWMode(m WMode) error { // readDirtyV3 serves a v3 read from the dirty map, if the LBA has an entry // (handled false: read the extent). A reader holds no lock across its WAL // read, so the position it resolved may be reused before the pread: after a -// reset (cursor 0 again, codex01 row 8 P1) or a same-open recovery. The -// read therefore validates the WHOLE record it read, payload included -// (CRC, footer, write type, LBA and LSN against the resolving entry), and -// re-resolves on a mismatch. An LSN is never at two live positions with -// the same LBA, so a matching record is the resolved write. If the entry -// is unchanged and the record still does not match, the WAL is damaged. -// No lock is taken: lock graph unchanged. +// reset (cursor 0 again, codex01 row 8 P1) or a same-open recovery that +// fenced and reused it. The read therefore validates the WHOLE record it +// read, payload included (CRC, footer, write type, LBA and LSN against the +// resolving entry), and re-resolves on a mismatch. LSN allocation runs on +// across a reset, so a matching LBA and LSN identify the resolved write; +// no nonce is checked. A same-open recovery can re-allocate a dropped LSN +// to the same LBA at the same position, so the "entry unchanged" damage +// verdict also requires the same recovery generation (a reset bumps it +// too) across the whole attempt (codex01 e72acd40 P2). A pread error is a +// substrate I/O failure, never WAL integrity: only a record that fails +// validation within one stable lifetime is damage. No lock is taken: the +// lock graph is unchanged. func (s *WALStore) readDirtyV3(lba uint32) (data []byte, handled bool, err error) { const attempts = 8 for i := 0; i < attempts; i++ { + gen := s.v3.recoverGen.Load() off, _, lsn, _, ok := s.dm.get(uint64(lba)) if !ok { return nil, false, nil @@ -558,36 +567,46 @@ func (s *WALStore) readDirtyV3(lba uint32) (data []byte, handled bool, err error if h := s.v3.testReadResolved; h != nil { h() } - data, rerr := s.readRecordV3(lba, off, lsn) - if rerr == nil { + data, ioErr, verr := s.readRecordV3(lba, off, lsn) + if ioErr != nil { + return nil, true, NewSubstrateIOFailure(ioErr, "v3 WAL read") + } + if verr == nil { return data, true, nil } - if off2, _, lsn2, _, ok2 := s.dm.get(uint64(lba)); ok2 && off2 == off && lsn2 == lsn { - return nil, true, NewWALIntegrityFailure(rerr, "v3 WAL read of a live dirty entry") + if h := s.v3.testReadInvalid; h != nil { + h() + } + off2, _, lsn2, _, ok2 := s.dm.get(uint64(lba)) + if ok2 && off2 == off && lsn2 == lsn && s.v3.recoverGen.Load() == gen { + return nil, true, NewWALIntegrityFailure(verr, "v3 WAL read of a live dirty entry") } } return nil, true, fmt.Errorf("storage: v3 WAL read of LBA %d did not settle in %d attempts", lba, attempts) } // readRecordV3 reads and validates the whole v3 write record at walRelOff. -func (s *WALStore) readRecordV3(lba uint32, walRelOff, lsn uint64) ([]byte, error) { +// ioErr is a failed or short pread: the WAL region lies inside the file, so +// io.EOF (a file shorter than its geometry) is substrate I/O too. verr is a +// record that was read but does not validate as the resolved write. +func (s *WALStore) readRecordV3(lba uint32, walRelOff, lsn uint64) (data []byte, ioErr, verr error) { size := uint64(walEntryHeaderSizeV3) + uint64(s.sb.BlockSize) if walRelOff+size > s.sb.WALSize { - return nil, fmt.Errorf("storage: v3 WAL read: record at %d crosses the ring end", walRelOff) + return nil, nil, fmt.Errorf("storage: v3 WAL read: record at %d crosses the ring end", walRelOff) } full := make([]byte, size) if _, err := s.fd.ReadAt(full, int64(s.sb.WALOffset+walRelOff)); err != nil { - return nil, fmt.Errorf("storage: v3 WAL read: %w", err) + return nil, fmt.Errorf("storage: v3 WAL read at %d: %w", walRelOff, err), nil } e, err := decodeWALEntryV3(full, s.sb.BlockSize, s.sb.VolumeSize/uint64(s.sb.BlockSize)) if err != nil { - return nil, err + return nil, nil, err } if e.Type != walEntryWrite || e.LBA != uint64(lba) || e.LSN != lsn || uint32(len(e.Data)) != s.sb.BlockSize { - return nil, fmt.Errorf("storage: v3 WAL read: record at %d is LBA %d LSN %d, want LBA %d LSN %d", + return nil, nil, fmt.Errorf("storage: v3 WAL read: record at %d is LBA %d LSN %d, want LBA %d LSN %d", walRelOff, e.LBA, e.LSN, lba, lsn) } - return e.Data, nil + return e.Data, nil, nil } // readDirtyRecordV3 is the flusher's record read for a v3 store: it decodes diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 19dcbb2c44..c7fa0245b3 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -287,7 +287,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `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. Flushed entries above the published checkpoint remain retry work, so a later Sync plus cycle can advance checkpoint and map coverage together. | 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`; `core/storage/flusher.go` `flushOnceInternal` | `TestWALStoreV3CloseKeepsTheNewestSlotAAndItsW`, `TestWALStoreV3LegacySuperblockWritersRefuse` (`core/storage/walstore_close_v3_test.go`); `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes`, `TestWALStoreV3ModeCWindowIsExactlyTheNewestBatch`, `TestWALStoreV3RefreshAndSetWModeCloseTheWindow`, `TestWALStoreV3TornUnsyncedTailIsNeverAFalseCorrupt`, `TestWALStoreV3AppendWriteErrorLatchesTheStore`, `TestWALStoreV3FlusherWritesTheExtentButHoldsTheCheckpointUntilTheMap`, `TestWALStoreV3SyncRechecksTheFaultAtTheAckBoundary`, `TestWALStoreV3SetWModeWaitsForAHeldBatch`, `TestWALStoreV3NoBatchAcksUnderAStaleModeAfterSetWMode`, `TestWALStoreV3SetWModeCrashCases`, `TestWALStoreV3SameOpenRecoverResetsTheAcknowledgedFrontier`, `TestWALStoreV3InstallingScanErrorIsTypedNotReady`, `TestWALStoreV3FlusherCycleRunsTheIdleRefresh`, `TestWALStoreV3RefreshDuringRecoverWaitsAndPublishesNothing`, `TestWALStoreV3RecoverWaitsForABatchAckAndNothingRevivesTheCut`, `TestWALStoreV3OuterSyncCompletionIsRefusedAcrossARecovery`, `TestWALStoreV3FlusherCheckpointIsClampedToTheAcknowledgedW`, `TestWALStoreV3FlusherEmptyCycleRunsTheIdleRefresh` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3Decision`, `TestRecoveryV3ContiguousPrefix` (`core/storage/recovery_v3_test.go`); `TestWALStoreV3_FlushedProgressRetriesAfterLaterSync` (`core/storage/walstore_flushed_progress_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-WAL-V3-RESET-001` | A v3 nonce/position reset is refused, writing nothing, unless the dirty map is empty (no entry names an old-incarnation WAL position) and every appended LSN is checkpointed (CheckpointLSN >= appended, hence = acknowledged W). It publishes the new nonce with an empty cursor space into one slot and then the other, and is successful only after both. A crash between the two opens the new incarnation; no reuse floor exists across the two nonces, and no writer binds until Recover's head publication completes the other slot. LSNs, W and the map root are unchanged. A read holds no lock across its WAL read; it validates the whole record it read (CRC, footer, type, LBA, LSN) against the resolving dirty entry and re-resolves on a mismatch, so a position reused by the new incarnation never serves another block. | M1 Serving → Serving (reset, dark) | `core/storage/reset_v3.go` `WALStore.resetIncarnationV3`, `descriptorPublisherV3.resetIncarnationV3`, `halfResetV3`; `core/storage/descriptor_v3.go` `mergeDescriptorV3Mode`; `core/storage/walstore_v3.go` open and `recoverV3` | `TestResetV3RefusesWhileUncheckpointed`, `TestResetV3RefusesTheCurrentOrAZeroNonce`, `TestResetV3RetainedButCheckpointedBytesDoNotBlock`, `TestResetV3PublishesBothSlotsAndOnlyThenHasAFloor`, `TestResetV3CrashOutcomes`, `TestResetV3OrdinaryPublicationsCannotChangeTheNonce` (`core/storage/reset_v3_test.go`); `TestWALStoreV3ResetRefusesUncheckpointedOrUnacknowledgedData`, `TestWALStoreV3ResetPublishesBothSlotsAndWritesRecoverAcrossACrash`, `TestWALStoreV3ResetCrashOutcomes`, `TestWALStoreV3HalfResetRefusesWritesUntilRecover`, `TestWALStoreV3ReadParkedAcrossAResetAndOverwriteReturnsItsOwnBlock`, `TestWALStoreV3ReadMissRecheckParkedAcrossAResetReturnsItsOwnBlock`, `TestWALStoreV3ReadOfADamagedLiveRecordIsAnIntegrityFault` (`core/storage/reset_store_v3_test.go`) | `WALFormat` reset (claude05 r4.5, pending) | STUB | +| `INV-WAL-V3-RESET-001` | A v3 nonce/position reset is refused, writing nothing, unless the dirty map is empty (no entry names an old-incarnation WAL position) and every appended LSN is checkpointed (CheckpointLSN >= appended, hence = acknowledged W). It publishes the new nonce with an empty cursor space into one slot and then the other, and is successful only after both. A crash between the two opens the new incarnation; no reuse floor exists across the two nonces, and no writer binds until Recover's head publication completes the other slot. LSNs, W and the map root are unchanged. A read holds no lock across its WAL read; it validates the whole record it read (CRC, footer, type, LBA, LSN) against the resolving dirty entry and re-resolves on a mismatch, so a position reused by the new incarnation never serves another block (LSN allocation runs on across a reset; no nonce is checked). It reports WAL damage only for an unchanged entry within one recovery generation; a failed pread is substrate I/O. | M1 Serving → Serving (reset, dark) | `core/storage/reset_v3.go` `WALStore.resetIncarnationV3`, `descriptorPublisherV3.resetIncarnationV3`, `halfResetV3`; `core/storage/descriptor_v3.go` `mergeDescriptorV3Mode`; `core/storage/walstore_v3.go` open and `recoverV3` | `TestResetV3RefusesWhileUncheckpointed`, `TestResetV3RefusesTheCurrentOrAZeroNonce`, `TestResetV3RetainedButCheckpointedBytesDoNotBlock`, `TestResetV3PublishesBothSlotsAndOnlyThenHasAFloor`, `TestResetV3CrashOutcomes`, `TestResetV3OrdinaryPublicationsCannotChangeTheNonce` (`core/storage/reset_v3_test.go`); `TestWALStoreV3ResetRefusesUncheckpointedOrUnacknowledgedData`, `TestWALStoreV3ResetPublishesBothSlotsAndWritesRecoverAcrossACrash`, `TestWALStoreV3ResetCrashOutcomes`, `TestWALStoreV3HalfResetRefusesWritesUntilRecover`, `TestWALStoreV3ReadParkedAcrossAResetAndOverwriteReturnsItsOwnBlock`, `TestWALStoreV3ReadMissRecheckParkedAcrossAResetReturnsItsOwnBlock`, `TestWALStoreV3ReadOfADamagedLiveRecordIsAnIntegrityFault`, `TestWALStoreV3ReadAcrossARecoveryThatReusesTheSamePositionAndLSNIsNotDamage`, `TestWALStoreV3ReadIOErrorsAreSubstrateIONotWALIntegrity` (`core/storage/reset_store_v3_test.go`) | `WALFormat` reset (claude05 r4.5, pending) | 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 | | `INV-FE-LINEAGE-GATE-001` | Every `Read`, `Write` and `Sync` re-checks `{volume, replica, epoch, endpoint version}` and health against the current projection; any drift returns `ErrStalePrimary`. The volume-ID comparison is code reading: no cited test varies the volume ID. | M3 Primary → Supporting \| Excluded (I/O side) | `core/frontend/durable/storage_adapter.go` `gate`, `lineageCheck` | `TestT3a_StorageBackend_FenceCheck_Epoch`, `TestT3a_StorageBackend_FenceCheck_EV`, `TestT3a_StorageBackend_FenceCheck_Replica`, `TestT3a_StorageBackend_FenceCheck_Healthy` (`core/frontend/durable/storage_adapter_test.go`); `TestG8A_SupersedeFact_FencesOldPrimaryDurableBackend` (`core/host/volume/g8a_stale_fence_test.go`) | — | ACTIVE |