diff --git a/seaweed-block/core/storage/chunk_frontier.go b/seaweed-block/core/storage/chunk_frontier.go index 863596a5f1..3e85578bcc 100644 --- a/seaweed-block/core/storage/chunk_frontier.go +++ b/seaweed-block/core/storage/chunk_frontier.go @@ -20,7 +20,7 @@ func (s *WALStore) SeedChunkFrontier(lsn uint64) error { if s.closed || s.chunk.Load() != nil { return errors.New("storage: seed frontier requires an open, unattached store") } - if err := s.stickyFsyncFault(); err != nil { + if err := s.stickyIOFault(); err != nil { return err } if lsn == ^uint64(0) || lsn < s.checkpointLSN || s.walHead > s.checkpointLSN || s.nextLSN > lsn+1 { diff --git a/seaweed-block/core/storage/chunk_layer_precopy_test.go b/seaweed-block/core/storage/chunk_layer_precopy_test.go index b5ac900287..d9d92f5a42 100644 --- a/seaweed-block/core/storage/chunk_layer_precopy_test.go +++ b/seaweed-block/core/storage/chunk_layer_precopy_test.go @@ -9,7 +9,6 @@ import ( "bytes" "context" "errors" - "io" "strings" "testing" "time" @@ -298,9 +297,9 @@ func TestChunkPrecopy_BarrierSyncFailureSettlesStagedIntents(t *testing.T) { assertNoIntentsLeft(t, f) } -// Recover republishes the dirty map outside the write path: a partial -// batch append leaves a complete newer record (and a torn one) that -// same-open Recover publishes. A chunk staged before it must not be reused: +// Recover republishes the dirty map outside the write path: a complete newer +// record past the head (what a failed append can leave) is published by a +// same-open Recover. A chunk staged before it must not be reused: // HEAD at the recovered H has the recovered bytes. func TestChunkPrecopy_RecoverAfterStagingInvalidatesTheStage(t *testing.T) { s, f, l, _ := precopyLayer(t, 1, 3) // chunk 0 staged in round 0; bound 1 @@ -310,23 +309,7 @@ func TestChunkPrecopy_RecoverAfterStagingInvalidatesTheStage(t *testing.T) { if round != 0 { return } - limit := walEntryHeaderSize + ctBlockSize + walEntryHeaderSize + 17 - s.wal.batchWriteAt = func(data []byte, off int64) (int, error) { - if len(data) <= limit { - return 0, errors.New("fixture needs two whole records") - } - n, err := s.fd.WriteAt(data[:limit], off) // a real partial pwrite - if err != nil { - return n, err - } - return n, io.ErrShortWrite - } - _, err := s.WriteBatch(0, [][]byte{want, makeBlock(ctBlockSize, 0xb8)}) - s.wal.batchWriteAt = nil - if !errors.Is(err, io.ErrShortWrite) { - t.Errorf("partial batch: %v", err) - return - } + plantRecordPastHead(t, s, 0, want) if _, err := s.Recover(); err != nil { // same open, before the barrier t.Errorf("same-open Recover: %v", err) return @@ -352,25 +335,26 @@ func TestChunkPrecopy_RecoverAfterStagingInvalidatesTheStage(t *testing.T) { } // partialBatchPrefix leaves a complete, CRC-valid record for want at the -// next LSN plus a torn second record through a real partial pwrite; the -// failed batch publishes neither (same-open Recover would). +// next LSN past the head, the bytes a failed append can leave behind, without +// failing an append (which latches the open store): same-open Recover +// republishes it. func partialBatchPrefix(t *testing.T, s *WALStore, want []byte) { t.Helper() - limit := walEntryHeaderSize + ctBlockSize + walEntryHeaderSize + 17 - s.wal.batchWriteAt = func(data []byte, off int64) (int, error) { - if len(data) <= limit { - return 0, errors.New("fixture needs two whole records") - } - n, err := s.fd.WriteAt(data[:limit], off) - if err != nil { - return n, err - } - return n, io.ErrShortWrite + plantRecordPastHead(t, s, 0, want) +} + +// plantRecordPastHead writes a complete write record for lba at the next LSN +// at the WAL head, without publishing it. +func plantRecordPastHead(t *testing.T, s *WALStore, lba uint64, data []byte) { + t.Helper() + e := walEntry{LSN: s.NextLSN(), Type: walEntryWrite, LBA: lba, Length: uint32(len(data)), Data: data} + buf, err := e.encode() + if err != nil { + t.Fatal(err) } - _, err := s.WriteBatch(0, [][]byte{want, makeBlock(ctBlockSize, 0xb8)}) - s.wal.batchWriteAt = nil - if !errors.Is(err, io.ErrShortWrite) { - t.Fatalf("partial batch: %v", err) + off := int64(s.sb.WALOffset + s.wal.physicalPos(s.wal.logicalHeadValue())) + if _, err := s.fd.WriteAt(buf, off); err != nil { + t.Fatal(err) } } diff --git a/seaweed-block/core/storage/flusher.go b/seaweed-block/core/storage/flusher.go index 7796b33d91..f5a7ad6fd0 100644 --- a/seaweed-block/core/storage/flusher.go +++ b/seaweed-block/core/storage/flusher.go @@ -155,7 +155,7 @@ func (f *flusher) flushOnceAllowClosed() error { func (f *flusher) flushOnceInternal(allowClosed bool) (err error) { cycleStart := time.Now() store := f.store - if err := store.stickyFsyncFault(); err != nil { + if err := store.stickyIOFault(); err != nil { return err // no checkpoint advance after a failed fsync } store.mu.RLock() diff --git a/seaweed-block/core/storage/recovery_contract.go b/seaweed-block/core/storage/recovery_contract.go index 94335c65f3..7569d7f5ab 100644 --- a/seaweed-block/core/storage/recovery_contract.go +++ b/seaweed-block/core/storage/recovery_contract.go @@ -192,7 +192,13 @@ func NewWALRecycledFailure(cause error, detail string) *RecoveryFailure { // SubstrateIO RecoveryFailure, so hosts report it as io_error. var ErrFsyncFailed = errors.New("storage: fsync failed earlier on this open store; reopen to recover") -// ErrAppendFailed: declared for the RED test; nothing returns it yet. +// ErrAppendFailed is the sticky fault of an open store after a WAL append +// failed while writing: its records may be on disk although nextLSN and the +// head did not move, so a later append would reuse their LSNs (and a crash +// would then let recovery replay the failed records over an acknowledged +// write). The store refuses further appends and Syncs until it is reopened; +// recovery of the reopen may replay the failed, never-acknowledged records. +// It comes wrapped in a SubstrateIO RecoveryFailure (io_error). var ErrAppendFailed = errors.New("storage: a WAL append failed earlier on this open store; reopen to recover") func NewSubstrateIOFailure(cause error, detail string) *RecoveryFailure { diff --git a/seaweed-block/core/storage/wal_writer.go b/seaweed-block/core/storage/wal_writer.go index e322daae8c..409212ef90 100644 --- a/seaweed-block/core/storage/wal_writer.go +++ b/seaweed-block/core/storage/wal_writer.go @@ -17,6 +17,10 @@ var ( errWALFull = errors.New("storage: WAL region full") ) +// errWALPwrite marks an append that failed while writing to the file: +// part or all of its bytes may be on disk (see WALStore.noteAppendFailure). +var errWALPwrite = errors.New("storage: WAL pwrite failed") + // walWriter appends entries to the circular WAL region of a store // file. It tracks position with monotonically-increasing logical // counters so head==tail unambiguously means empty (used = head-tail). @@ -106,7 +110,7 @@ func (w *walWriter) append(entry *walEntry) (walRelOffset uint64, err error) { return 0, errWALFull } if err := w.writePadding(remaining, physHead); err != nil { - return 0, fmt.Errorf("walWriter.append: padding: %w", err) + return 0, fmt.Errorf("%w: walWriter.append: padding: %w", errWALPwrite, err) } if w.instr != nil { w.instr.recordWALAppendWrap(remaining) @@ -120,7 +124,7 @@ func (w *walWriter) append(entry *walEntry) (walRelOffset uint64, err error) { absOffset := int64(w.walOffset + physHead) writeStart := time.Now() if _, err := w.fd.WriteAt(buf, absOffset); err != nil { - return 0, fmt.Errorf("walWriter.append: pwrite at %d: %w", absOffset, err) + return 0, fmt.Errorf("%w: walWriter.append: pwrite at %d: %w", errWALPwrite, absOffset, err) } if w.instr != nil { w.instr.recordWALAppend(len(buf), time.Since(writeStart)) @@ -175,7 +179,7 @@ func (w *walWriter) appendBatch(entries []walEntry) ([]uint64, error) { writeAt = w.batchWriteAt } if _, err := writeAt(pending, int64(w.walOffset+pendingStart)); err != nil { - return fmt.Errorf("walWriter.appendBatch: pwrite at %d: %w", w.walOffset+pendingStart, err) + return fmt.Errorf("%w: walWriter.appendBatch: pwrite at %d: %w", errWALPwrite, w.walOffset+pendingStart, err) } if w.instr != nil { w.instr.recordWALAppend(len(pending), time.Since(writeStart)) diff --git a/seaweed-block/core/storage/walstore.go b/seaweed-block/core/storage/walstore.go index 8fd8d298be..a04cfa6699 100644 --- a/seaweed-block/core/storage/walstore.go +++ b/seaweed-block/core/storage/walstore.go @@ -141,8 +141,9 @@ type WALStore struct { // syncExtentFile is the flusher's fsync after extent writes (the same // file as the WAL); a seam for fault injection. syncExtentFile func() error - // fsyncFault latches the first fsync failure of the file (ErrFsyncFailed). - fsyncFault atomic.Pointer[RecoveryFailure] + // ioFault latches the first fsync failure of the file (ErrFsyncFailed) + // or the first failed WAL append (ErrAppendFailed). + ioFault atomic.Pointer[RecoveryFailure] // Generations cover completed append attempts and recovery publication. walMutation atomic.Uint64 durableMutation atomic.Uint64 @@ -543,7 +544,7 @@ func (s *WALStore) Recover() (uint64, error) { if s.closed { return 0, errors.New("storage: Recover after Close") } - if err := s.stickyFsyncFault(); err != nil { + if err := s.stickyIOFault(); err != nil { return 0, err } @@ -621,7 +622,7 @@ func (s *WALStore) Write(lba uint32, data []byte) (uint64, error) { defer s.captureMu.RUnlock() s.lifecycleMu.RLock() defer s.lifecycleMu.RUnlock() - if err := s.stickyFsyncFault(); err != nil { + if err := s.stickyIOFault(); err != nil { return 0, err } if uint64(lba) >= uint64(s.sb.VolumeSize/uint64(s.sb.BlockSize)) { @@ -664,6 +665,7 @@ func (s *WALStore) Write(lba uint32, data []byte) (uint64, error) { // A failed pwrite may still leave complete records or padding in the file. s.walMutation.Add(1) if err != nil { + s.noteAppendFailure(err) s.mu.Unlock() return 0, fmt.Errorf("storage: WAL append: %w", err) } @@ -688,7 +690,7 @@ func (s *WALStore) WriteBatch(startLBA uint32, blocks [][]byte) ([]uint64, error defer s.captureMu.RUnlock() s.lifecycleMu.RLock() defer s.lifecycleMu.RUnlock() - if err := s.stickyFsyncFault(); err != nil { + if err := s.stickyIOFault(); err != nil { return nil, err } if len(blocks) == 0 { @@ -746,6 +748,7 @@ func (s *WALStore) WriteBatch(startLBA uint32, blocks [][]byte) ([]uint64, error // A failed pwrite may still leave complete records or padding in the file. s.walMutation.Add(1) if err != nil { + s.noteAppendFailure(err) s.mu.Unlock() return nil, fmt.Errorf("storage: WAL batch append: %w", err) } @@ -793,6 +796,7 @@ func (s *WALStore) writeBatchMultiBlockLocked(startLBA uint32, blocks [][]byte, // A failed pwrite may still leave complete records or padding in the file. s.walMutation.Add(1) if err != nil { + s.noteAppendFailure(err) return nil, fmt.Errorf("storage: WAL multiblock append: %w", err) } @@ -954,7 +958,7 @@ func (s *WALStore) Sync() (uint64, error) { s.mu.RUnlock() return 0, errors.New("storage: Sync after Close") } - if err := s.stickyFsyncFault(); err != nil { + if err := s.stickyIOFault(); err != nil { s.mu.RUnlock() return 0, err } @@ -1136,7 +1140,7 @@ func (s *WALStore) WriteExtentDirect(lba uint32, data []byte) error { defer s.captureMu.RUnlock() s.lifecycleMu.RLock() defer s.lifecycleMu.RUnlock() - if err := s.stickyFsyncFault(); err != nil { + if err := s.stickyIOFault(); err != nil { return err } maxLBA := uint32(s.sb.VolumeSize / uint64(s.sb.BlockSize)) @@ -1193,7 +1197,7 @@ func (s *WALStore) ApplyEntry(lba uint32, data []byte, lsn uint64) error { defer s.captureMu.RUnlock() s.lifecycleMu.RLock() defer s.lifecycleMu.RUnlock() - if err := s.stickyFsyncFault(); err != nil { + if err := s.stickyIOFault(); err != nil { return err } maxLBA := uint32(s.sb.VolumeSize / uint64(s.sb.BlockSize)) @@ -1225,6 +1229,7 @@ func (s *WALStore) ApplyEntry(lba uint32, data []byte, lsn uint64) error { // A failed pwrite may still leave complete records or padding in the file. s.walMutation.Add(1) if err != nil { + s.noteAppendFailure(err) return fmt.Errorf("storage: WAL append (apply): %w", err) } s.dm.put(uint64(lba), walRelOff, lsn, uint32(len(dataCopy))) @@ -1359,10 +1364,10 @@ func (s *WALStore) Close() error { if flushErr != nil { closeErrors = append(closeErrors, fmt.Errorf("storage: final flush: %w", flushErr)) } - if fault := s.stickyFsyncFault(); fault != nil { + if fault := s.stickyIOFault(); fault != nil { closeErrors = append(closeErrors, fault) } - if s.fd != nil && s.stickyFsyncFault() == nil { + if s.fd != nil && s.stickyIOFault() == nil { // Persist current head/tail back into the superblock so a // subsequent OpenWALStore can find the WAL bounds without // relying solely on the defensive scan. @@ -1427,16 +1432,32 @@ func (s *WALStore) noteFsyncFailure(err error) error { if err == nil { return nil } - s.fsyncFault.CompareAndSwap(nil, NewSubstrateIOFailure( + s.ioFault.CompareAndSwap(nil, NewSubstrateIOFailure( fmt.Errorf("%w: %w", ErrFsyncFailed, err), "fsync failed; the open store refuses further Syncs, writes and checkpoints", )) return err } -// stickyFsyncFault reports the latched fsync fault, if any. -func (s *WALStore) stickyFsyncFault() error { - if f := s.fsyncFault.Load(); f != nil { +// noteAppendFailure latches a WAL append whose write failed as the sticky +// ErrAppendFailed fault and returns err unchanged. The failed records may be +// on disk without nextLSN or the head having moved; any further append on +// this open store would reuse their LSNs and offsets. Space and encoding +// refusals (no bytes written) do not latch. +func (s *WALStore) noteAppendFailure(err error) error { + if err == nil || !errors.Is(err, errWALPwrite) { + return err + } + s.ioFault.CompareAndSwap(nil, NewSubstrateIOFailure( + fmt.Errorf("%w: %w", ErrAppendFailed, err), + "WAL append failed; the open store refuses further appends and Syncs", + )) + return err +} + +// stickyIOFault reports the latched I/O fault (fsync or append), if any. +func (s *WALStore) stickyIOFault() error { + if f := s.ioFault.Load(); f != nil { return f } return nil diff --git a/seaweed-block/core/storage/walstore_sync_generation_test.go b/seaweed-block/core/storage/walstore_sync_generation_test.go index d7af2a9fca..a39e096a77 100644 --- a/seaweed-block/core/storage/walstore_sync_generation_test.go +++ b/seaweed-block/core/storage/walstore_sync_generation_test.go @@ -237,7 +237,9 @@ func TestWALGenerationBatchPublication(t *testing.T) { func TestWALGenerationPartialAppendRecoverySync(t *testing.T) { for _, recoverFirst := range []bool{false, true} { t.Run(map[bool]string{false: "failed append without recovery", true: "same-open recovery"}[recoverFirst], func(t *testing.T) { - s := newGenerationStore(t) + path := filepath.Join(t.TempDir(), "store.bin") + s := createWALStoreWithWALSizeForTest(t, path, 64, 4096, 1<<20) + s.DisableAutoFlushForRecoveryTest() if _, err := s.Sync(); err != nil { t.Fatal(err) } @@ -264,31 +266,38 @@ func TestWALGenerationPartialAppendRecoverySync(t *testing.T) { if got := s.wal.logicalHeadValue(); got != beforeHead { t.Fatalf("failed batch published head=%d want %d", got, beforeHead) } + // The failed append is sticky (ErrAppendFailed): no same-open + // recovery, and no Sync acknowledges anything, without an fsync. if recoverFirst { - if n, err := s.Recover(); err != nil || n != 1 { - t.Fatalf("same-open Recover=%d err=%v want1,nil", n, err) - } - if got, err := s.Read(0); err != nil || !bytes.Equal(got, want) { - t.Fatalf("valid prefix not recovered: err=%v", err) + if _, err := s.Recover(); !errors.Is(err, ErrAppendFailed) { + t.Fatalf("same-open Recover after a failed append: %v; want ErrAppendFailed", err) } } - realSync := s.syncWALFile - fault := errors.New("next physical sync failed") - attempts := 0 - s.syncWALFile = func() error { attempts++; return fault } - _, err = s.Sync() - s.syncWALFile = realSync - if !errors.Is(err, fault) || attempts != 1 { - t.Fatalf("next Sync skipped required physical I/O/error: err=%v attempts=%d", err, attempts) - } - // The failed fsync is sticky (ErrFsyncFailed): no retry ack and - // no further physical fsync on this open store. before := s.WALSyncCount() - if _, err := s.Sync(); !errors.Is(err, ErrFsyncFailed) { - t.Fatalf("retry after a failed fsync: %v; want ErrFsyncFailed", err) + if _, err := s.Sync(); !errors.Is(err, ErrAppendFailed) { + t.Fatalf("Sync after a failed append: %v; want ErrAppendFailed", err) } if n := s.WALSyncCount() - before; n != 0 { - t.Fatalf("a refused retry fsynced %d times", n) + t.Fatalf("a refused Sync fsynced %d times", n) + } + crashRecoveryHardeningStore(t, s) + + // A reopen may republish the failed batch's complete prefix (it + // was never acknowledged) and serves normally again. + r, err := OpenWALStore(path) + if err != nil { + t.Fatal(err) + } + r.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = r.Close() }) + if n, err := r.Recover(); err != nil || n != 1 { + t.Fatalf("reopen Recover=%d err=%v want 1,nil", n, err) + } + if got, err := r.Read(0); err != nil || !bytes.Equal(got, want) { + t.Fatalf("valid prefix not recovered: err=%v", err) + } + if _, err := r.Sync(); err != nil { + t.Fatalf("Sync after a reopen: %v", err) } }) } diff --git a/seaweed-block/core/storage/walstore_test.go b/seaweed-block/core/storage/walstore_test.go index bc4930bebf..06bdc2f72e 100644 --- a/seaweed-block/core/storage/walstore_test.go +++ b/seaweed-block/core/storage/walstore_test.go @@ -9,7 +9,8 @@ import ( ) func TestWALStore_FailedAppendDoesNotConsumeLSN(t *testing.T) { - s, err := CreateWALStore(filepath.Join(t.TempDir(), "store.bin"), 16, 4096) + path := filepath.Join(t.TempDir(), "store.bin") + s, err := CreateWALStore(path, 16, 4096) if err != nil { t.Fatal(err) } @@ -30,36 +31,37 @@ func TestWALStore_FailedAppendDoesNotConsumeLSN(t *testing.T) { t.Fatalf("NextLSN after failed append=%d want 1", got) } + // A failed append is sticky (ErrAppendFailed): no later write reuses + // its LSN on this open store, single or batch. s.wal.fd = s.fd - lsn, err := s.Write(0, makeBlock(4096, 0xA2)) + if _, err := s.Write(0, makeBlock(4096, 0xA2)); !errors.Is(err, ErrAppendFailed) { + t.Fatalf("Write after a failed append: %v; want ErrAppendFailed", err) + } + if _, err := s.WriteBatch(1, [][]byte{makeBlock(4096, 0xC1), makeBlock(4096, 0xC2)}); !errors.Is(err, ErrAppendFailed) { + t.Fatalf("WriteBatch after a failed append: %v; want ErrAppendFailed", err) + } + if got := s.NextLSN(); got != 1 { + t.Fatalf("NextLSN after refused appends=%d want 1", got) + } + _ = s.Close() + + // A reopen starts from what is on disk (nothing of the failed append): + // the first write gets LSN 1, the next batch LSNs 2 and 3. + r, err := OpenWALStore(path) if err != nil { t.Fatal(err) } - if lsn != 1 { - t.Fatalf("successful Write LSN=%d want reused LSN 1", lsn) - } - - s.wal.fd = bad - if _, err := s.WriteBatch(1, [][]byte{ - makeBlock(4096, 0xB1), - makeBlock(4096, 0xB2), - }); err == nil { - t.Fatal("WriteBatch with closed WAL fd succeeded") - } - if got := s.NextLSN(); got != 2 { - t.Fatalf("NextLSN after failed batch=%d want 2", got) - } - - s.wal.fd = s.fd - lsns, err := s.WriteBatch(1, [][]byte{ - makeBlock(4096, 0xC1), - makeBlock(4096, 0xC2), - }) - if err != nil { + t.Cleanup(func() { _ = r.Close() }) + if _, err := r.Recover(); err != nil { t.Fatal(err) } - if len(lsns) != 2 || lsns[0] != 2 || lsns[1] != 3 { - t.Fatalf("successful batch LSNs=%v want [2 3]", lsns) + lsn, err := r.Write(0, makeBlock(4096, 0xA2)) + if err != nil || lsn != 1 { + t.Fatalf("first write after a reopen LSN=%d err=%v want 1", lsn, err) + } + lsns, err := r.WriteBatch(1, [][]byte{makeBlock(4096, 0xC1), makeBlock(4096, 0xC2)}) + if err != nil || len(lsns) != 2 || lsns[0] != 2 || lsns[1] != 3 { + t.Fatalf("batch after a reopen LSNs=%v err=%v want [2 3]", lsns, err) } }