From d2a6a3b02c657d482b9a546637f096fefb24f719 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 22:29:41 -0800 Subject: [PATCH 1/4] storage: RED controls for issue #51 (WAL holes) claude05's rulings (2026-11-16 06:10Z, 06:14Z). Controls with real corrupted WALs, failing against stubs that restore today's behaviour: walstore (interim: a power loss must never become an outage): - (a) a corrupted mid-history synced entry: recovery succeeds to the prefix, but no wal_hole_suspected warning, no count (TestWALStoreRecoverWarnsOnMidHistoryHole); - (c) the newer batch wrapped to offset 0 is replayed past a corrupted older entry (TestWALStoreRecoverNoReplayPastAHoleAcrossWrappedRanges); - the durable status and /status carry no warning (TestDurableStartup_Issue51_WALStoreHoleIsAWarningNotAnOutage, TestStatusServer_StatusCarriesRecoveryWarningsWithoutChangingHealth). - controls that pass either way: (b) an out-of-order unsynced tail recovers, a torn tail recovers. smartwal (fail closed on a mid-history hole): - a corrupted committed slot with later valid records starts Ready (TestDurableStartup_Issue51_SmartWALMidHistoryHoleIsWALCorrupt); - controls: the issue's exact mutation is wal_corrupt (ea1faf6a), a torn tail recovers. Co-Authored-By: Claude Opus 5.5 --- .../durable_startup_slotcrc_test.go | 190 +++++++++++ .../core/frontend/durable/provider.go | 5 + .../core/frontend/durable/storage_adapter.go | 10 + .../core/host/volume/status_server.go | 12 + .../core/host/volume/status_warnings_test.go | 46 +++ seaweed-block/core/storage/recovery.go | 294 ++++++++++++++---- .../core/storage/smartwal/recovery.go | 32 +- seaweed-block/core/storage/smartwal/ring.go | 15 +- seaweed-block/core/storage/walstore.go | 36 +++ .../storage/walstore_midhistory_hole_test.go | 188 +++++++++++ 10 files changed, 763 insertions(+), 65 deletions(-) create mode 100644 seaweed-block/cmd/blockvolume/durable_startup_slotcrc_test.go create mode 100644 seaweed-block/core/host/volume/status_warnings_test.go create mode 100644 seaweed-block/core/storage/walstore_midhistory_hole_test.go diff --git a/seaweed-block/cmd/blockvolume/durable_startup_slotcrc_test.go b/seaweed-block/cmd/blockvolume/durable_startup_slotcrc_test.go new file mode 100644 index 0000000000..df0760aea1 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/durable_startup_slotcrc_test.go @@ -0,0 +1,190 @@ +package main + +import ( + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/host/volume" + "github.com/seaweedfs/seaweed-block/core/storage" + "github.com/seaweedfs/seaweed-block/core/storage/smartwal" +) + +// Issue #51: a real SmartWAL WAL-slot corruption (the issue's mutation: +// the last byte of a committed record's 32-byte slot, i.e. its record CRC) +// must not let the volume start Ready. + +// writeSmartWAL writes the given LBAs in order through the real provider, +// syncs and closes it, and returns the store's path. +func writeSmartWAL(t *testing.T, cfg durable.ProviderConfig, lbas []uint32) string { + t.Helper() + dp, err := durable.NewDurableProvider(cfg, healthyView{}) + if err != nil { + t.Fatal(err) + } + st, err := dp.EnsureStorage("v1") + if err != nil { + t.Fatal(err) + } + for i, lba := range lbas { + data := make([]byte, 4096) + data[0], data[1] = byte(0xA0+i), byte(lba) + if _, err := st.Write(lba, data); err != nil { + t.Fatal(err) + } + } + if _, err := st.Sync(); err != nil { + t.Fatal(err) + } + if err := dp.Close(); err != nil { + t.Fatal(err) + } + return filepath.Join(cfg.StorageRoot, "v1.bin") +} + +// corruptSlotCRC flips the last byte (the record CRC) of the newest slot +// recorded for lba, as the issue's QA mutation did (target_record_offset +// +31). +func corruptSlotCRC(t *testing.T, path string, lba uint32) { + t.Helper() + _, records, err := smartwal.InspectRecords(path) + if err != nil { + t.Fatal(err) + } + var off int64 = -1 + var lsn uint64 + for _, r := range records { + if r.LBA == lba && r.LSN >= lsn { + off, lsn = r.Offset, r.LSN + } + } + if off < 0 { + t.Fatalf("no record for LBA %d", lba) + } + f, err := os.OpenFile(path, os.O_RDWR, 0) + if err != nil { + t.Fatal(err) + } + defer f.Close() + b := make([]byte, 1) + if _, err := f.ReadAt(b, off+31); err != nil { + t.Fatal(err) + } + b[0] ^= 0xFF + if _, err := f.WriteAt(b, off+31); err != nil { + t.Fatal(err) + } +} + +func startAfterCorruption(t *testing.T, cfg durable.ProviderConfig) (durableStartupOutcome, *spyHost) { + t.Helper() + dp, err := durable.NewDurableProvider(cfg, healthyView{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = dp.Close() }) + h := &spyHost{} + outcome, evidence, err := openAndRecoverDurable(dp, h, "v1", 5*time.Second) + t.Logf("outcome=%v reported=%v evidence=%q err=%v", outcome, h.reported, evidence, err) + return outcome, h +} + +// The issue's schedule: LBA 0 was written twice; the newer record's slot +// is corrupted, so recovery drops it as torn and falls back to the older +// record, whose CRC no longer matches the extent. Current main fails +// closed (85d93753): wal_corrupt, readiness blocked. +func TestDurableStartup_Issue51_CorruptNewerSlotIsWALCorrupt(t *testing.T) { + cfg := durable.ProviderConfig{Impl: durable.ImplSmartWAL, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: 16} + path := writeSmartWAL(t, cfg, []uint32{0, 1, 2, 0}) + corruptSlotCRC(t, path, 0) + outcome, h := startAfterCorruption(t, cfg) + if outcome != durableStartupFaulted || len(h.reported) != 1 || h.reported[0] != volume.UnhealthyWALCorrupt || len(h.blocked) == 0 { + t.Fatalf("corrupt newer slot: outcome=%v reported=%v blocked=%v; want faulted, wal_corrupt, readiness blocked", outcome, h.reported, h.blocked) + } +} + +// claude05's ruling (1) for smartwal: a corrupted committed record with a +// later valid record after it (a mid-history hole) fails closed: +// wal_corrupt, readiness blocked. +func TestDurableStartup_Issue51_SmartWALMidHistoryHoleIsWALCorrupt(t *testing.T) { + cfg := durable.ProviderConfig{Impl: durable.ImplSmartWAL, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: 16} + path := writeSmartWAL(t, cfg, []uint32{0, 1, 2, 3}) + corruptSlotCRC(t, path, 1) // LSN 2; LSN 3 and 4 stay valid + outcome, h := startAfterCorruption(t, cfg) + if outcome != durableStartupFaulted || len(h.reported) != 1 || h.reported[0] != volume.UnhealthyWALCorrupt || len(h.blocked) == 0 { + t.Fatalf("mid-history hole: outcome=%v reported=%v blocked=%v; want faulted, wal_corrupt, readiness blocked", outcome, h.reported, h.blocked) + } +} + +// Control: a torn tail (the newest slot bad, nothing valid after it) +// still recovers: a power loss is not an outage. +func TestDurableStartup_Issue51_SmartWALTornTailRecovers(t *testing.T) { + cfg := durable.ProviderConfig{Impl: durable.ImplSmartWAL, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: 16} + path := writeSmartWAL(t, cfg, []uint32{0, 1, 2}) + corruptSlotCRC(t, path, 2) // LSN 3, the newest + outcome, h := startAfterCorruption(t, cfg) + if outcome != durableStartupReady || len(h.reported) != 0 { + t.Fatalf("torn tail: outcome=%v reported=%v; want ready", outcome, h.reported) + } +} + +// walstore interim (claude05's ruling 06:14Z): the same mid-history +// corruption on a walstore volume does not become an outage: startup is +// ready, and the durable status carries the typed warning. +func TestDurableStartup_Issue51_WALStoreHoleIsAWarningNotAnOutage(t *testing.T) { + root := t.TempDir() + cfg := durable.ProviderConfig{Impl: durable.ImplWALStore, StorageRoot: root, BlockSize: 4096, NumBlocks: 16} + path := filepath.Join(root, "v1.bin") + // A crashed walstore: entries synced, nothing checkpointed (the file + // as it is right after Sync; a clean close would checkpoint). + s, err := storage.CreateWALStore(path, 16, 4096) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + for i := uint32(0); i < 4; i++ { + data := make([]byte, 4096) + data[0] = byte(0xD0 + i) + if _, err := s.Write(i, data); err != nil { + t.Fatal(err) + } + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + crashed, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + _ = s.Close() + // Corrupt a payload byte of the second entry (walstore's WAL starts at + // 4096; a one-block entry is 38+4096 bytes). + crashed[4096+(38+4096)+38+100] ^= 0xFF + if err := os.WriteFile(path, crashed, 0o644); err != nil { + t.Fatal(err) + } + dp, err := durable.NewDurableProvider(cfg, healthyView{}) + if err != nil { + t.Fatal(err) + } + defer dp.Close() + h := &spyHost{} + outcome, evidence, err := openAndRecoverDurable(dp, h, "v1", 5*time.Second) + if outcome != durableStartupReady || len(h.reported) != 0 { + t.Fatalf("walstore hole: outcome=%v reported=%v evidence=%q err=%v; want ready (no outage)", outcome, h.reported, evidence, err) + } + warned := false + for _, st := range dp.DurableStatuses() { + for _, w := range st.Warnings { + if strings.HasPrefix(w, storage.WarningWALHoleSuspected+":") { + warned = st.HolesSuspected == 1 + } + } + } + if !warned { + t.Fatalf("durable statuses %+v; want the %s warning, counted once", dp.DurableStatuses(), storage.WarningWALHoleSuspected) + } +} diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index 9b0322268c..fb1ee57db7 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -228,6 +228,11 @@ type VolumeStatus struct { // Chunk is the chunk layer's state and cut counters; walstore-chunk // volumes only. Chunk *ChunkStatus + // Warnings are the store's typed recovery warnings (e.g. + // wal_hole_suspected, issue #51); they do not change readiness. + // HolesSuspected counts the recoveries that found a WAL hole. + Warnings []string `json:",omitempty"` + HolesSuspected uint64 `json:",omitempty"` } // ChunkStatus is one walstore-chunk volume's chunk layer (B9 7.2-7.3). diff --git a/seaweed-block/core/frontend/durable/storage_adapter.go b/seaweed-block/core/frontend/durable/storage_adapter.go index d24a3f50e3..480f6b5172 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter.go +++ b/seaweed-block/core/frontend/durable/storage_adapter.go @@ -275,6 +275,14 @@ func (b *StorageBackend) durableStatus(volumeID, path, impl string) VolumeStatus b.mu.Unlock() durableLSN, retainedLSN, headLSN := b.storage.Boundaries() evidence, _ := b.opEvidence.Load().(string) + var warnings []string + var holes uint64 + if w, ok := b.storage.(storage.RecoveryWarner); ok && false { // RED: warnings not reported + warnings = w.RecoveryWarnings() + } + if c, ok := b.storage.(interface{ HolesSuspected() uint64 }); ok { + holes = c.HolesSuspected() + } writeProfile := b.profile.snapshot() if instrumented, ok := b.storage.(storage.WriteInstrumented); ok { storageProfile := instrumented.WriteInstrumentation() @@ -303,6 +311,8 @@ func (b *StorageBackend) durableStatus(volumeID, path, impl string) VolumeStatus writeProfile.DirtyMapUpdateDurationNanos = storageProfile.DirtyMapUpdateDurationNanos } return VolumeStatus{ + Warnings: warnings, + HolesSuspected: holes, VolumeID: volumeID, Path: path, Impl: impl, diff --git a/seaweed-block/core/host/volume/status_server.go b/seaweed-block/core/host/volume/status_server.go index 0815ee30ea..3ba4a0eebf 100644 --- a/seaweed-block/core/host/volume/status_server.go +++ b/seaweed-block/core/host/volume/status_server.go @@ -196,6 +196,10 @@ type StatusProjection struct { // CatchUp shows a supporting replica's catch-up progress while it is // not yet replica_ready; it is visible without being an alert. CatchUp *CatchUpStatus `json:",omitempty"` + // Warnings are the durable store's typed recovery warnings (e.g. + // wal_hole_suspected, issue #51). Visible, not an alert: they do not + // change Healthy or the frontend's readiness. + Warnings []string `json:",omitempty"` } // CatchUpStatus is a supporting replica's catch-up state. @@ -477,7 +481,15 @@ func (s *StatusServer) statusProjection() StatusProjection { s.mu.Lock() p.Healthy = p.Healthy && !s.nvmePending p.FrontendPrimaryReady = p.FrontendPrimaryReady && !s.nvmePending + src := s.durableSource s.mu.Unlock() + if src != nil && false { // RED: /status carries no warnings + for _, st := range src.DurableStatuses() { + if st.VolumeID == p.VolumeID { + p.Warnings = append(p.Warnings, st.Warnings...) + } + } + } return p } diff --git a/seaweed-block/core/host/volume/status_warnings_test.go b/seaweed-block/core/host/volume/status_warnings_test.go new file mode 100644 index 0000000000..7cf43c77a2 --- /dev/null +++ b/seaweed-block/core/host/volume/status_warnings_test.go @@ -0,0 +1,46 @@ +package volume + +import ( + "context" + "encoding/json" + "net/http" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/durable" +) + +// Issue #51 (walstore interim): the durable store's typed recovery warning +// is visible on /status and does not change Healthy or readiness. +func TestStatusServer_StatusCarriesRecoveryWarningsWithoutChangingHealth(t *testing.T) { + s := NewStatusServer(NewAdapterProjectionView(stubProjector{}, "v1", "r1", nil)) + addr, err := s.Start("127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer func() { _ = s.Close(context.Background()) }() + get := func() StatusProjection { + t.Helper() + resp, err := http.Get("http://" + addr + "/status?volume=v1") + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + var p StatusProjection + if err := json.NewDecoder(resp.Body).Decode(&p); err != nil { + t.Fatal(err) + } + return p + } + before := get() + s.SetDurableStatusSource(stubDurableStatusSource{vols: []durable.VolumeStatus{{ + VolumeID: "v1", Impl: "walstore", Warnings: []string{"wal_hole_suspected: WAL entry at offset=4134 fails its check"}, HolesSuspected: 1, + }}}) + after := get() + if len(after.Warnings) != 1 || after.Warnings[0][:18] != "wal_hole_suspected" { + t.Fatalf("/status warnings %v; want the wal_hole_suspected warning", after.Warnings) + } + if after.Healthy != before.Healthy || after.FrontendPrimaryReady != before.FrontendPrimaryReady { + t.Fatalf("a warning changed health: before healthy=%t ready=%t, after healthy=%t ready=%t", + before.Healthy, before.FrontendPrimaryReady, after.Healthy, after.FrontendPrimaryReady) + } +} diff --git a/seaweed-block/core/storage/recovery.go b/seaweed-block/core/storage/recovery.go index 3b0f6d12e1..a712a3dc66 100644 --- a/seaweed-block/core/storage/recovery.go +++ b/seaweed-block/core/storage/recovery.go @@ -10,6 +10,10 @@ import ( // recoveryResult summarizes what RecoverWAL did on one open. type recoveryResult struct { + // HoleSuspected: a bad entry was followed by a valid later one (issue + // #51); replay stopped before it. HoleDetail says where. + HoleSuspected bool + HoleDetail string EntriesReplayed int // valid entries past checkpoint that were replayed HighestLSN uint64 // highest LSN observed across the whole scan WALHead uint64 // reconstructed logical byte head of retained WAL @@ -50,9 +54,7 @@ func recoverWAL(fd *os.File, sb *superblock, dm *dirtyMap) (recoveryResult, erro walSize := sb.WALSize checkpointLSN := sb.WALCheckpointLSN - type scanRange struct { - start, end uint64 // physical positions within WAL - } + type scanRange = recoveryScanRange var ranges []scanRange if logicalHead == logicalTail { @@ -93,7 +95,27 @@ func recoverWAL(fd *os.File, sb *superblock, dm *dirtyMap) (recoveryResult, erro } } - for _, r := range ranges { + // Pass 1 decodes every range and collects the entries; nothing is + // replayed yet. Replay order is by LSN, not by scan order: a persisted + // head/tail can predate a wrap, so a range read first may hold newer + // entries than one read later (issue #51). + type scanned struct { + entry walEntry + start, end uint64 + lowLSN uint64 // first LSN above the checkpoint + highLSN uint64 + padding bool + } + var items []scanned + byEnd := map[uint64]int{} // end offset -> index in items + type badEntry struct { + ri int + pos uint64 + cause error + resyncTo uint64 + } + var bad []badEntry + for ri, r := range ranges { pos := r.start for pos < r.end { remaining := r.end - pos @@ -109,7 +131,10 @@ func recoverWAL(fd *os.File, sb *superblock, dm *dirtyMap) (recoveryResult, erro lengthField := parseLengthFromHeader(headerBuf) if entryType == walEntryPadding { - pos += uint64(walEntryHeaderSize) + uint64(lengthField) + end := pos + uint64(walEntryHeaderSize) + uint64(lengthField) + items = append(items, scanned{start: pos, end: end, padding: true}) + byEnd[end] = len(items) - 1 + pos = end continue } var payloadLen uint64 @@ -117,18 +142,25 @@ func recoverWAL(fd *os.File, sb *superblock, dm *dirtyMap) (recoveryResult, erro payloadLen = uint64(lengthField) } entrySize := uint64(walEntryHeaderSize) + payloadLen + var entry walEntry + var derr error if entrySize > remaining { - result.TornEntries++ - break + derr = errEntryTruncated + } else { + fullBuf := make([]byte, entrySize) + if _, err := fd.ReadAt(fullBuf, absOff); err != nil { + return result, fmt.Errorf("storage: recovery read entry at %d: %w", pos, err) + } + entry, derr = decodeWALEntry(fullBuf) } - fullBuf := make([]byte, entrySize) - if _, err := fd.ReadAt(fullBuf, absOff); err != nil { - return result, fmt.Errorf("storage: recovery read entry at %d: %w", pos, err) - } - entry, err := decodeWALEntry(fullBuf) - if err != nil { - // Torn write or trailing zeros — stop scanning this range. + if derr != nil { + // Torn write, corruption, or trailing zeros: this range + // ends here. A non-zero bad entry is a possible hole, + // decided after the scan. result.TornEntries++ + if !allZeroBytes(headerBuf) { + bad = append(bad, badEntry{ri: ri, pos: pos, cause: derr}) + } break } highestEntryLSN := entry.LSN @@ -148,61 +180,123 @@ func recoverWAL(fd *os.File, sb *superblock, dm *dirtyMap) (recoveryResult, erro } highestEntryLSN = entry.LSN + entry.Reserved - 1 } - if highestEntryLSN <= checkpointLSN { - pos += entrySize + entry.Data = nil // replay reads the WAL at its offset, never this copy + lowLSN := entry.LSN + if lowLSN <= checkpointLSN { + lowLSN = checkpointLSN + 1 + } + items = append(items, scanned{entry: entry, start: pos, end: pos + entrySize, lowLSN: lowLSN, highLSN: highestEntryLSN}) + byEnd[pos+entrySize] = len(items) - 1 + pos += entrySize + } + } + + // The earliest hole: a bad entry was appended after the entry that + // ends where it starts (its circular predecessor, padding skipped), so + // its LSN is above that entry's. Nothing at or above that bound is + // replayed; any valid entry there makes it a mid-history hole. + holeLSN := ^uint64(0) + var holeAt uint64 + var holeCause error + for _, b := range bad { + pred := checkpointLSN + cur := b.pos + for guard := 0; guard <= len(items); guard++ { + i, ok := byEnd[cur] + if !ok && cur == 0 { + i, ok = byEnd[walSize] + } + if !ok { + break + } + if items[i].padding { + cur = items[i].start continue } - firstRetainedLSN := entry.LSN - if firstRetainedLSN <= checkpointLSN { - firstRetainedLSN = checkpointLSN + 1 + pred = max(pred, items[i].highLSN) + break + } + if pred+1 < holeLSN { + holeLSN, holeAt, holeCause = pred+1, b.pos, b.cause + } + } + hole := false + if len(bad) > 0 { + for _, it := range items { + if !it.padding && it.highLSN > checkpointLSN && it.highLSN >= holeLSN { + hole = true + break } - retainedRecords = append(retainedRecords, retainedRecord{ - firstLSN: firstRetainedLSN, - start: pos, - end: pos + entrySize, - }) - switch entry.Type { - case walEntryWrite: - blocks := entry.Length / sb.BlockSize - for i := uint32(0); i < blocks; i++ { - dm.putAt( - entry.LBA+uint64(i), pos, i*sb.BlockSize, - entry.LSN, sb.BlockSize, - ) + } + if !hole { + // Valid entries the scan did not reach (after the bad one in + // its range) count too. + for _, b := range bad { + found, _, err := laterValidEntry(fd, walOffset, ranges, b.ri, b.pos+1, holeLSN-1, sb.BlockSize) + if err != nil { + return result, err } - result.EntriesReplayed++ - case walEntryWriteBatch: - blocks := uint32(entry.Reserved) - for i := uint32(0); i < blocks; i++ { - lsn := entry.LSN + uint64(i) - if lsn <= checkpointLSN { - continue - } - dm.putAt( - entry.LBA+uint64(i), pos, i*sb.BlockSize, - lsn, sb.BlockSize, - ) + if found { + hole = true + break } - result.EntriesReplayed++ - case walEntryTrim: - blocks := entry.Length / sb.BlockSize - if blocks == 0 { - blocks = 1 - } - for i := uint32(0); i < blocks; i++ { - dm.putAt( - entry.LBA+uint64(i), pos, i*sb.BlockSize, - entry.LSN, sb.BlockSize, - ) - } - result.EntriesReplayed++ - case walEntryBarrier: - // no data; skip } - if highestEntryLSN > result.HighestLSN { - result.HighestLSN = highestEntryLSN + } + } + if red := true; red { // RED: no hole bound, no warning + hole, holeLSN = false, ^uint64(0) + } + if hole { + result.HoleSuspected = true + result.HoleDetail = fmt.Sprintf("WAL entry at offset=%d fails its check and valid entries from LSN %d on follow it; recovered the entries below LSN %d", holeAt, holeLSN, holeLSN) + if holeCause != nil { + result.HoleDetail += " (" + holeCause.Error() + ")" + } + log.Printf("storage: recovery %s: %s", WarningWALHoleSuspected, result.HoleDetail) + } + + // Pass 2: replay every entry above the checkpoint and below the hole. + for _, it := range items { + if it.padding || it.highLSN <= checkpointLSN || it.highLSN >= holeLSN { + continue + } + entry, pos := it.entry, it.start + retainedRecords = append(retainedRecords, retainedRecord{ + firstLSN: it.lowLSN, + start: it.start, + end: it.end, + }) + switch entry.Type { + case walEntryWrite: + blocks := entry.Length / sb.BlockSize + for i := uint32(0); i < blocks; i++ { + dm.putAt(entry.LBA+uint64(i), pos, i*sb.BlockSize, entry.LSN, sb.BlockSize) } - pos += entrySize + result.EntriesReplayed++ + case walEntryWriteBatch: + blocks := uint32(entry.Reserved) + for i := uint32(0); i < blocks; i++ { + lsn := entry.LSN + uint64(i) + if lsn <= checkpointLSN { + continue + } + dm.putAt(entry.LBA+uint64(i), pos, i*sb.BlockSize, lsn, sb.BlockSize) + } + result.EntriesReplayed++ + case walEntryTrim: + blocks := entry.Length / sb.BlockSize + if blocks == 0 { + blocks = 1 + } + for i := uint32(0); i < blocks; i++ { + dm.putAt(entry.LBA+uint64(i), pos, i*sb.BlockSize, entry.LSN, sb.BlockSize) + } + result.EntriesReplayed++ + case walEntryBarrier: + // no data; skip + } + if it.highLSN > result.HighestLSN { + result.HighestLSN = it.highLSN } } @@ -323,3 +417,79 @@ func previousValidWALRecord( return 0, walEntry{}, false } } + +// recoveryScanRange is a physical [start, end) span of the WAL region. +type recoveryScanRange struct { + start, end uint64 +} + +func allZeroBytes(b []byte) bool { + for _, c := range b { + if c != 0 { + return false + } + } + return true +} + +// laterValidEntry looks, from pos in ranges[ri] through the later ranges, +// for an offset holding a valid WAL entry (it decodes, CRC included) whose +// LSN is above minLSN. It runs only after a bad entry, so a linear resync +// over the remaining WAL is acceptable; a cheap header prefilter keeps the +// full decodes to plausible candidates. +func laterValidEntry(fd *os.File, walOffset uint64, ranges []recoveryScanRange, ri int, pos, minLSN uint64, blockSize uint32) (bool, uint64, error) { + const window = 1 << 20 + hdr := uint64(walEntryHeaderSize) + for i := ri; i < len(ranges); i++ { + start, end := ranges[i].start, ranges[i].end + if i == ri { + start = pos + } + for p := start; p+hdr <= end; p += window { + n := min(window+hdr, end-p) + buf := make([]byte, n) + if _, err := fd.ReadAt(buf, int64(walOffset+p)); err != nil { + return false, 0, fmt.Errorf("storage: recovery resync read at %d: %w", p, err) + } + for q := uint64(0); q+hdr <= n && q < window; q++ { + size, ok := plausibleEntryHeader(buf[q:q+hdr], minLSN, end-(p+q), blockSize) + if !ok { + continue + } + full := make([]byte, size) + if _, err := fd.ReadAt(full, int64(walOffset+p+q)); err != nil { + return false, 0, fmt.Errorf("storage: recovery resync read entry at %d: %w", p+q, err) + } + if _, err := decodeWALEntry(full); err == nil { + return true, p + q, nil + } + } + } + } + return false, 0, nil +} + +// plausibleEntryHeader is the resync prefilter: a known record type, an +// LSN above minLSN, and a length that fits in what remains. +func plausibleEntryHeader(h []byte, minLSN, remaining uint64, blockSize uint32) (uint64, bool) { + lsn := binary.LittleEndian.Uint64(h[0:8]) + if lsn <= minLSN { + return 0, false + } + length := uint64(parseLengthFromHeader(h)) + size := uint64(walEntryHeaderSize) + switch h[16] { + case walEntryWrite, walEntryWriteBatch: + if length == 0 || blockSize == 0 || length%uint64(blockSize) != 0 { + return 0, false + } + size += length + case walEntryTrim, walEntryBarrier: + default: + return 0, false + } + if size > remaining { + return 0, false + } + return size, true +} diff --git a/seaweed-block/core/storage/smartwal/recovery.go b/seaweed-block/core/storage/smartwal/recovery.go index 8558abb010..92ecae2206 100644 --- a/seaweed-block/core/storage/smartwal/recovery.go +++ b/seaweed-block/core/storage/smartwal/recovery.go @@ -37,7 +37,7 @@ import ( // - per-block CRC stored alongside extent (extent stays raw blocks) // - cross-checking against any external snapshot func runRecovery(r *ring, fd *os.File, extentBase int64, blockSize int) (uint64, error) { - records, err := r.scanValid() + records, bad, err := r.scanSlots() if err != nil { return 0, fmt.Errorf("smartwal: recovery scan: %w", err) } @@ -45,6 +45,9 @@ func runRecovery(r *ring, fd *os.File, extentBase int64, blockSize int) (uint64, log.Printf("smartwal: recovery: ring empty; nothing to verify") return 0, nil } + if err := midHistoryHole(bad, records[len(records)-1].LSN, r.capacity); err != nil { + return 0, err + } // Last-writer-wins map. Records arrive sorted by LSN ascending, // so the final value in the map is naturally the highest LSN. @@ -101,3 +104,30 @@ func runRecovery(r *ring, fd *os.File, extentBase int64, blockSize int) (uint64, recovered, highestVerifiedLSN) return highestVerifiedLSN, nil } + +// midHistoryHole fails closed on a corrupted committed slot (issue #51; +// claude05's ruling 2026-11-16 06:10Z/06:14Z). Slot i holds LSN i mod +// capacity, so with H the highest valid LSN a bad slot at distance d +// (1 <= d < capacity-1) behind H's slot implies LSN H-d: a record a later +// valid record (H) follows, i.e. a mid-history hole. The slot right after +// H's (d = capacity-1) is where LSN H+1 goes: a torn tail, which still +// recovers; so is a slot whose implied LSN was never written. +func midHistoryHole(bad []uint64, highest, capacity uint64) error { + if red := true; red { // RED: a bad slot is always a torn slot + return nil + } + if capacity < 2 { + return nil + } + hs := highest % capacity + for _, i := range bad { + d := (hs + capacity - i) % capacity + if d == 0 || d == capacity-1 || d >= highest { + continue // H's own slot (impossible), the torn-tail position, or never written + } + detail := fmt.Sprintf("corrupted record in slot %d (implied LSN %d) below the valid LSN %d: mid-history hole", i, highest-d, highest) + log.Printf("smartwal: recovery %s — failing closed", detail) + return storage.NewWALIntegrityFailure(nil, detail) + } + return nil +} diff --git a/seaweed-block/core/storage/smartwal/ring.go b/seaweed-block/core/storage/smartwal/ring.go index c08bab89cd..0c71f5de90 100644 --- a/seaweed-block/core/storage/smartwal/ring.go +++ b/seaweed-block/core/storage/smartwal/ring.go @@ -60,23 +60,34 @@ func (r *ring) appendAt(lsn uint64, rec record) error { // // Used during recovery to rebuild the in-memory view. func (r *ring) scanValid() ([]record, error) { + records, _, err := r.scanSlots() + return records, err +} + +// scanSlots is scanValid that also returns the indexes of populated slots +// (magic present) whose record CRC fails: torn or corrupted. +func (r *ring) scanSlots() ([]record, []uint64, error) { totalSize := r.capacity * recordSize buf := make([]byte, totalSize) r.mu.Lock() _, err := r.fd.ReadAt(buf, r.base) r.mu.Unlock() if err != nil { - return nil, fmt.Errorf("smartwal: ring scan read: %w", err) + return nil, nil, fmt.Errorf("smartwal: ring scan read: %w", err) } var out []record + var bad []uint64 for i := uint64(0); i < r.capacity; i++ { off := i * recordSize rec, ok := decode(buf[off : off+recordSize]) if !ok { + if buf[off] == recordMagic { + bad = append(bad, i) + } continue } out = append(out, rec) } sort.Slice(out, func(i, j int) bool { return out[i].LSN < out[j].LSN }) - return out, nil + return out, bad, nil } diff --git a/seaweed-block/core/storage/walstore.go b/seaweed-block/core/storage/walstore.go index 19a1d3eb7c..1c9b0199d9 100644 --- a/seaweed-block/core/storage/walstore.go +++ b/seaweed-block/core/storage/walstore.go @@ -43,6 +43,11 @@ import ( // - Online resize // - Compaction (the WAL is bounded but periodic checkpoints free space) type WALStore struct { + // recoveryWarnings and holesSuspected: the last Recover's typed + // warnings, and how many recoveries found a WAL hole (issue #51). + recoveryWarnings []string + holesSuspected uint64 + metadata BlockMetadata // immutable before publication path string @@ -456,6 +461,32 @@ func (s *WALStore) FlusherInstrumentation() FlusherInstrumentationStatus { return s.flusher.instr.snapshot() } +// WarningWALHoleSuspected is the typed recovery warning for a WAL hole +// followed by valid records (issue #51): reported on /status, it does not +// change readiness. +const WarningWALHoleSuspected = "wal_hole_suspected" + +// RecoveryWarner is a store that reports warnings from its last Recover. +type RecoveryWarner interface { + RecoveryWarnings() []string +} + +// RecoveryWarnings returns the warnings of the last Recover (nil when it +// found nothing to warn about). +func (s *WALStore) RecoveryWarnings() []string { + s.mu.Lock() + defer s.mu.Unlock() + return append([]string(nil), s.recoveryWarnings...) +} + +// HolesSuspected counts the recoveries of this store that found a WAL hole +// followed by valid records. +func (s *WALStore) HolesSuspected() uint64 { + s.mu.Lock() + defer s.mu.Unlock() + return s.holesSuspected +} + // Recover replays WAL entries past the last checkpoint into the dirty // map. After Recover, the in-memory state matches what an aborted // process would have left durably on disk. @@ -497,6 +528,11 @@ func (s *WALStore) Recover() (uint64, error) { } s.sb.WALHead = res.WALHead s.sb.WALTail = res.WALTail + s.recoveryWarnings = nil + if res.HoleSuspected { + s.holesSuspected++ + s.recoveryWarnings = []string{WarningWALHoleSuspected + ": " + res.HoleDetail} + } recoveredHead := s.checkpointLSN if res.HighestLSN > recoveredHead { recoveredHead = res.HighestLSN diff --git a/seaweed-block/core/storage/walstore_midhistory_hole_test.go b/seaweed-block/core/storage/walstore_midhistory_hole_test.go new file mode 100644 index 0000000000..da21ca4f24 --- /dev/null +++ b/seaweed-block/core/storage/walstore_midhistory_hole_test.go @@ -0,0 +1,188 @@ +package storage + +import ( + "path/filepath" + "strings" + "testing" +) + +// Issue #51, walstore interim (claude05's ruling 2026-11-16 06:14Z): a +// plain power loss must never become an outage, so a WAL hole followed by +// valid records does not fail recovery. It is detected, logged, counted and +// reported as the typed warning wal_hole_suspected, and nothing after the +// hole is replayed in any range. + +// writeSyncedEntries writes one block to each of lbas (in order), syncs, +// and returns the store with auto-flush off (nothing checkpointed) and +// each LBA's WAL offset. +func writeSyncedEntries(t *testing.T, lbas []uint32) (*WALStore, string, map[uint64]uint64) { + t.Helper() + const blockSize = 4096 + path := filepath.Join(t.TempDir(), "store.bin") + s, err := CreateWALStore(path, 16, blockSize) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + for i, lba := range lbas { + if _, err := s.Write(lba, makeBlock(blockSize, byte(0xB0+i))); err != nil { + t.Fatal(err) + } + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + return s, path, walOffsetsByLBA(s) +} + +func walOffsetsByLBA(s *WALStore) map[uint64]uint64 { + offs := map[uint64]uint64{} + for _, e := range s.dm.snapshot() { + offs[e.LBA] = e.WALOffset + } + return offs +} + +// flipDataByte corrupts one payload byte of the entry at walOffset without +// fixing its CRC. +func flipDataByte(t *testing.T, s *WALStore, walOffset uint64) { + t.Helper() + off := int64(s.sb.WALOffset+walOffset) + int64(walEntryHeaderSize) + 100 + b := make([]byte, 1) + if _, err := s.fd.ReadAt(b, off); err != nil { + t.Fatal(err) + } + b[0] ^= 0xFF + if _, err := s.fd.WriteAt(b, off); err != nil { + t.Fatal(err) + } +} + +func reopenAfterCrash(t *testing.T, s *WALStore, path string) (*WALStore, uint64, error) { + t.Helper() + crashRecoveryHardeningStore(t, s) + r, err := OpenWALStore(path) + if err != nil { + t.Fatal(err) + } + r.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = r.Close() }) + lsn, rerr := r.Recover() + return r, lsn, rerr +} + +func holeWarning(s *WALStore) bool { + for _, w := range s.RecoveryWarnings() { + if strings.HasPrefix(w, WarningWALHoleSuspected+":") { + return true + } + } + return false +} + +// (a) A corrupted mid-history synced record: recovery succeeds to the +// prefix before it, warns (typed, counted), and replays nothing after it. +func TestWALStoreRecoverWarnsOnMidHistoryHole(t *testing.T) { + s, path, offs := writeSyncedEntries(t, []uint32{0, 1, 2, 3}) + flipDataByte(t, s, offs[1]) + r, lsn, err := reopenAfterCrash(t, s, path) + if err != nil || lsn != 1 { + t.Fatalf("Recover after a mid-history hole = %d, %v; want 1, nil (no outage)", lsn, err) + } + if !holeWarning(r) || r.HolesSuspected() != 1 { + t.Fatalf("warnings %v holes %d; want %s, counted once", r.RecoveryWarnings(), r.HolesSuspected(), WarningWALHoleSuspected) + } + if got := r.dm.len(); got != 1 { + t.Fatalf("dirty entries replayed = %d; want 1 (nothing after the hole)", got) + } + assertRecoveryHardeningBlock(t, r, 0, makeBlock(4096, 0xB0)) +} + +// (b) A power loss with an unsynced, out-of-order tail: an earlier +// unsynced record torn, a later one written back. No outage: recovery +// succeeds with the synced prefix intact. +func TestWALStoreRecoverSurvivesAnOutOfOrderUnsyncedTail(t *testing.T) { + s, path, _ := writeSyncedEntries(t, []uint32{0, 1}) // synced + for i, lba := range []uint32{2, 3} { // unsynced + if _, err := s.Write(lba, makeBlock(4096, byte(0xC0+i))); err != nil { + t.Fatal(err) + } + } + offs := walOffsetsByLBA(s) + flipDataByte(t, s, offs[2]) // LBA 2 torn, LBA 3 reached the disk + r, lsn, err := reopenAfterCrash(t, s, path) + if err != nil || lsn != 2 { + t.Fatalf("Recover after an out-of-order unsynced tail = %d, %v; want 2, nil", lsn, err) + } + for i, lba := range []uint32{0, 1} { + assertRecoveryHardeningBlock(t, r, lba, makeBlock(4096, byte(0xB0+i))) + } +} + +// A torn tail (nothing valid after it) recovers without a warning. +func TestWALStoreRecoverKeepsATornTail(t *testing.T) { + s, path, offs := writeSyncedEntries(t, []uint32{0, 1, 2, 3}) + flipDataByte(t, s, offs[3]) + r, lsn, err := reopenAfterCrash(t, s, path) + if err != nil || lsn != 3 || holeWarning(r) { + t.Fatalf("Recover with a torn tail = %d, %v, warnings %v; want 3, nil, none", lsn, err, r.RecoveryWarnings()) + } + for i, lba := range []uint32{0, 1, 2} { + assertRecoveryHardeningBlock(t, r, lba, makeBlock(4096, byte(0xB0+i))) + } +} + +// (c) No replay past a hole across wrapped ranges: the older record at the +// high end of the WAL is corrupted; the newer batch that wrapped to offset +// 0 must not be replayed. +func TestWALStoreRecoverNoReplayPastAHoleAcrossWrappedRanges(t *testing.T) { + const ( + blockSize = 4096 + walSize = 24 * 1024 + ) + path := filepath.Join(t.TempDir(), "store.bin") + s := createWALStoreWithWALSizeForTest(t, path, 64, blockSize, walSize) + s.DisableAutoFlushForRecoveryTest() + for lba := uint32(0); lba < 3; lba++ { + if _, err := s.Write(lba, makeBlock(blockSize, byte(0x10+lba))); err != nil { + t.Fatal(err) + } + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + if _, err := s.Write(20, makeBlock(blockSize, 0xA4)); err != nil { // high end + t.Fatal(err) + } + s.enableMultiBlockRecordsForTest(true) + if _, err := s.WriteBatch(24, [][]byte{makeBlock(blockSize, 0xB5), makeBlock(blockSize, 0xB6)}); err != nil { // wraps to 0 + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + offs := walOffsetsByLBA(s) + if offs[24] != 0 || offs[20] == 0 { + t.Fatalf("offsets high=%d low=%d; want the batch wrapped to 0", offs[20], offs[24]) + } + flipDataByte(t, s, offs[20]) + r, _, err := reopenAfterCrash(t, s, path) + if err != nil { + t.Fatalf("Recover: %v; want no outage", err) + } + if !holeWarning(r) { + t.Fatalf("warnings %v; want %s", r.RecoveryWarnings(), WarningWALHoleSuspected) + } + for _, lba := range []uint32{24, 25} { + got, err := r.Read(lba) + if err != nil { + t.Fatal(err) + } + if got[0] == 0xB5 || got[0] == 0xB6 { + t.Fatalf("LBA %d replayed from past the hole (byte %02x)", lba, got[0]) + } + } +} From f8d43653a77a165b7309e916418b65114165e197 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 22:29:48 -0800 Subject: [PATCH 2/4] storage: detect WAL holes; walstore warns, smartwal fails closed Issue #51, claude05's rulings (2026-11-16 06:10Z, 06:14Z). walstore (interim; no fail-closed: a plain power loss must never become an outage): - recovery decodes every range first and replays by LSN, not by scan order (a persisted head/tail can predate a wrap). A non-zero bad entry bounds the replay: its LSN is above its circular predecessor's, so nothing at or above that bound is replayed in any range. - a bad entry followed by any valid later entry is a suspected hole: logged, counted (HolesSuspected) and reported as the typed warning wal_hole_suspected (WALStore.RecoveryWarnings), surfaced in the durable status and on /status without changing Healthy or readiness. - trailing zeros still just end a range; a torn tail recovers silently. smartwal: a corrupted committed slot (magic present, record CRC bad) behind the highest valid LSN's slot is a mid-history hole: WAL integrity failure (wal_corrupt). The slot right after it is the torn- tail position and still recovers. The durable synced watermark that tells a corrupted synced record from an unsynced torn one is the post-M4 format change, not this. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/frontend/durable/storage_adapter.go | 2 +- seaweed-block/core/host/volume/status_server.go | 2 +- seaweed-block/core/storage/recovery.go | 3 --- seaweed-block/core/storage/smartwal/recovery.go | 3 --- 4 files changed, 2 insertions(+), 8 deletions(-) diff --git a/seaweed-block/core/frontend/durable/storage_adapter.go b/seaweed-block/core/frontend/durable/storage_adapter.go index 480f6b5172..6998f46ed3 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter.go +++ b/seaweed-block/core/frontend/durable/storage_adapter.go @@ -277,7 +277,7 @@ func (b *StorageBackend) durableStatus(volumeID, path, impl string) VolumeStatus evidence, _ := b.opEvidence.Load().(string) var warnings []string var holes uint64 - if w, ok := b.storage.(storage.RecoveryWarner); ok && false { // RED: warnings not reported + if w, ok := b.storage.(storage.RecoveryWarner); ok { warnings = w.RecoveryWarnings() } if c, ok := b.storage.(interface{ HolesSuspected() uint64 }); ok { diff --git a/seaweed-block/core/host/volume/status_server.go b/seaweed-block/core/host/volume/status_server.go index 3ba4a0eebf..3c500b032e 100644 --- a/seaweed-block/core/host/volume/status_server.go +++ b/seaweed-block/core/host/volume/status_server.go @@ -483,7 +483,7 @@ func (s *StatusServer) statusProjection() StatusProjection { p.FrontendPrimaryReady = p.FrontendPrimaryReady && !s.nvmePending src := s.durableSource s.mu.Unlock() - if src != nil && false { // RED: /status carries no warnings + if src != nil { // outside s.mu: the provider takes its own lock for _, st := range src.DurableStatuses() { if st.VolumeID == p.VolumeID { p.Warnings = append(p.Warnings, st.Warnings...) diff --git a/seaweed-block/core/storage/recovery.go b/seaweed-block/core/storage/recovery.go index a712a3dc66..d14f4c58c5 100644 --- a/seaweed-block/core/storage/recovery.go +++ b/seaweed-block/core/storage/recovery.go @@ -243,9 +243,6 @@ func recoverWAL(fd *os.File, sb *superblock, dm *dirtyMap) (recoveryResult, erro } } } - if red := true; red { // RED: no hole bound, no warning - hole, holeLSN = false, ^uint64(0) - } if hole { result.HoleSuspected = true result.HoleDetail = fmt.Sprintf("WAL entry at offset=%d fails its check and valid entries from LSN %d on follow it; recovered the entries below LSN %d", holeAt, holeLSN, holeLSN) diff --git a/seaweed-block/core/storage/smartwal/recovery.go b/seaweed-block/core/storage/smartwal/recovery.go index 92ecae2206..d6baa17212 100644 --- a/seaweed-block/core/storage/smartwal/recovery.go +++ b/seaweed-block/core/storage/smartwal/recovery.go @@ -113,9 +113,6 @@ func runRecovery(r *ring, fd *os.File, extentBase int64, blockSize int) (uint64, // H's (d = capacity-1) is where LSN H+1 goes: a torn tail, which still // recovers; so is a slot whose implied LSN was never written. func midHistoryHole(bad []uint64, highest, capacity uint64) error { - if red := true; red { // RED: a bad slot is always a torn slot - return nil - } if capacity < 2 { return nil } From e910449f70863234c3d735e002e3d9e4e24ee037 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 23:04:18 -0800 Subject: [PATCH 3/4] storage: RED controls for the #155 review (detection only) codex01's review of f8d43653 (V:/share/rdma/codex01-block155-review- 20261116T0644Z/REVIEW.md) and claude05's ruling (A), 06:47Z. Against the reviewed production code (its replay cutoff and positional smartwal fail-closed; smartwal warning accessors stubbed so the tests build): - a damaged STALE record in a released range drops retained, synced LSN 3 (TestWALStoreRecoverStaleReleasedGarbageKeepsRetainedData); - a torn smartwal slot accepted by one recovery becomes wal_corrupt after a frontier jump and a new sync (TestSmartWALTornSlotSurvivesAFrontierJump); - a smartwal mid-history hole is an outage instead of a warning (TestDurableStartup_Issue51_SmartWALHoleIsAWarningNotAnOutage); - plus codex01's advisory: a healthy primary stays healthy with a warning (TestStatusServer_StatusCarriesRecoveryWarnings..., which passes either way: the plumbing never forced health). Co-Authored-By: Claude Opus 5.5 --- .../durable_startup_slotcrc_test.go | 31 +++-- .../core/host/volume/status_warnings_test.go | 17 ++- .../smartwal/smartwal_hole_detection_test.go | 106 ++++++++++++++++++ seaweed-block/core/storage/smartwal/store.go | 6 + .../storage/walstore_midhistory_hole_test.go | 78 ++++++++----- 5 files changed, 201 insertions(+), 37 deletions(-) create mode 100644 seaweed-block/core/storage/smartwal/smartwal_hole_detection_test.go diff --git a/seaweed-block/cmd/blockvolume/durable_startup_slotcrc_test.go b/seaweed-block/cmd/blockvolume/durable_startup_slotcrc_test.go index df0760aea1..8c99a5b2cf 100644 --- a/seaweed-block/cmd/blockvolume/durable_startup_slotcrc_test.go +++ b/seaweed-block/cmd/blockvolume/durable_startup_slotcrc_test.go @@ -106,16 +106,33 @@ func TestDurableStartup_Issue51_CorruptNewerSlotIsWALCorrupt(t *testing.T) { } } -// claude05's ruling (1) for smartwal: a corrupted committed record with a -// later valid record after it (a mid-history hole) fails closed: -// wal_corrupt, readiness blocked. -func TestDurableStartup_Issue51_SmartWALMidHistoryHoleIsWALCorrupt(t *testing.T) { +// claude05's ruling (A), 06:47Z: detection only for smartwal too. A +// corrupted committed slot with later valid records starts as before +// (ready), and the durable status carries the counted warning. +func TestDurableStartup_Issue51_SmartWALHoleIsAWarningNotAnOutage(t *testing.T) { cfg := durable.ProviderConfig{Impl: durable.ImplSmartWAL, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: 16} path := writeSmartWAL(t, cfg, []uint32{0, 1, 2, 3}) corruptSlotCRC(t, path, 1) // LSN 2; LSN 3 and 4 stay valid - outcome, h := startAfterCorruption(t, cfg) - if outcome != durableStartupFaulted || len(h.reported) != 1 || h.reported[0] != volume.UnhealthyWALCorrupt || len(h.blocked) == 0 { - t.Fatalf("mid-history hole: outcome=%v reported=%v blocked=%v; want faulted, wal_corrupt, readiness blocked", outcome, h.reported, h.blocked) + dp, err := durable.NewDurableProvider(cfg, healthyView{}) + if err != nil { + t.Fatal(err) + } + defer dp.Close() + h := &spyHost{} + outcome, evidence, err := openAndRecoverDurable(dp, h, "v1", 5*time.Second) + if outcome != durableStartupReady || len(h.reported) != 0 { + t.Fatalf("smartwal hole: outcome=%v reported=%v evidence=%q err=%v; want ready", outcome, h.reported, evidence, err) + } + warned := false + for _, st := range dp.DurableStatuses() { + for _, w := range st.Warnings { + if strings.HasPrefix(w, storage.WarningWALHoleSuspected+":") && st.HolesSuspected == 1 { + warned = true + } + } + } + if !warned { + t.Fatalf("durable statuses %+v; want the counted %s warning", dp.DurableStatuses(), storage.WarningWALHoleSuspected) } } diff --git a/seaweed-block/core/host/volume/status_warnings_test.go b/seaweed-block/core/host/volume/status_warnings_test.go index 7cf43c77a2..879ab1826c 100644 --- a/seaweed-block/core/host/volume/status_warnings_test.go +++ b/seaweed-block/core/host/volume/status_warnings_test.go @@ -6,13 +6,25 @@ import ( "net/http" "testing" + "github.com/seaweedfs/seaweed-block/core/engine" "github.com/seaweedfs/seaweed-block/core/frontend/durable" ) // Issue #51 (walstore interim): the durable store's typed recovery warning // is visible on /status and does not change Healthy or readiness. func TestStatusServer_StatusCarriesRecoveryWarningsWithoutChangingHealth(t *testing.T) { - s := NewStatusServer(NewAdapterProjectionView(stubProjector{}, "v1", "r1", nil)) + t.Run("not-ready replica", func(t *testing.T) { + statusWarningsCase(t, NewAdapterProjectionView(stubProjector{}, "v1", "r1", nil), false) + }) + t.Run("healthy primary", func(t *testing.T) { + // codex01's advisory: a healthy primary stays healthy with a warning. + p := stubProjector{p: engine.ReplicaProjection{Mode: engine.ModeHealthy, Epoch: 1, EndpointVersion: 1}} + statusWarningsCase(t, NewAdapterProjectionView(p, "v1", "r1", stubProbe{yes: false}), true) + }) +} + +func statusWarningsCase(t *testing.T, view *AdapterProjectionView, wantHealthy bool) { + s := NewStatusServer(view) addr, err := s.Start("127.0.0.1:0") if err != nil { t.Fatal(err) @@ -32,6 +44,9 @@ func TestStatusServer_StatusCarriesRecoveryWarningsWithoutChangingHealth(t *test return p } before := get() + if before.Healthy != wantHealthy || before.FrontendPrimaryReady != wantHealthy { + t.Fatalf("before the warning: healthy=%t ready=%t; want %t", before.Healthy, before.FrontendPrimaryReady, wantHealthy) + } s.SetDurableStatusSource(stubDurableStatusSource{vols: []durable.VolumeStatus{{ VolumeID: "v1", Impl: "walstore", Warnings: []string{"wal_hole_suspected: WAL entry at offset=4134 fails its check"}, HolesSuspected: 1, }}}) diff --git a/seaweed-block/core/storage/smartwal/smartwal_hole_detection_test.go b/seaweed-block/core/storage/smartwal/smartwal_hole_detection_test.go new file mode 100644 index 0000000000..74463615f4 --- /dev/null +++ b/seaweed-block/core/storage/smartwal/smartwal_hole_detection_test.go @@ -0,0 +1,106 @@ +package smartwal + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +func flipSlotCRC(t *testing.T, path string, lsn uint64) { + t.Helper() + _, records, err := InspectRecords(path) + if err != nil { + t.Fatal(err) + } + for _, r := range records { + if r.LSN != lsn { + continue + } + f, err := os.OpenFile(path, os.O_RDWR, 0) + if err != nil { + t.Fatal(err) + } + defer f.Close() + b := make([]byte, 1) + if _, err := f.ReadAt(b, r.Offset+31); err != nil { + t.Fatal(err) + } + b[0] ^= 0xFF + if _, err := f.WriteAt(b, r.Offset+31); err != nil { + t.Fatal(err) + } + return + } + t.Fatalf("no record LSN %d", lsn) +} + +func warnsHole(s *Store) bool { + for _, w := range s.RecoveryWarnings() { + if strings.HasPrefix(w, storage.WarningWALHoleSuspected+":") { + return true + } + } + return false +} + +// codex01's r1 P1, under claude05's 06:47Z ruling (detection only): a torn +// slot accepted by one recovery stays a recoverable warning after a +// frontier jump and a new synced write; nothing infers its generation from +// its position in the ring. +func TestSmartWALTornSlotSurvivesAFrontierJump(t *testing.T) { + path := filepath.Join(t.TempDir(), "s.sw") + s, err := CreateStore(path, 16, 4096) + if err != nil { + t.Fatal(err) + } + for i, lba := range []uint32{0, 1} { // LSN 1, 2 + data := make([]byte, 4096) + data[0] = byte(0xE0 + i) + if _, err := s.Write(lba, data); err != nil { + t.Fatal(err) + } + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if err := s.Close(); err != nil { + t.Fatal(err) + } + flipSlotCRC(t, path, 2) // LSN 2 torn + + s, err = OpenStore(path) + if err != nil { + t.Fatal(err) + } + if _, err := s.Recover(); err != nil { + t.Fatalf("first recovery: %v; want the torn tail accepted", err) + } + firstWarned, firstHoles := warnsHole(s), s.HolesSuspected() + s.AdvanceFrontier(4) + data := make([]byte, 4096) + data[0] = 0xEF + if _, err := s.Write(2, data); err != nil { // LSN 5 + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if err := s.Close(); err != nil { + t.Fatal(err) + } + + s, err = OpenStore(path) + if err != nil { + t.Fatal(err) + } + defer s.Close() + if _, err := s.Recover(); err != nil { + t.Fatalf("second recovery after the frontier jump: %v; want recovered (the old torn slot is not corruption)", err) + } + if !firstWarned || firstHoles != 1 || !warnsHole(s) { + t.Fatalf("warnings: first %t (%d), second %v; want the counted %s both times", firstWarned, firstHoles, s.RecoveryWarnings(), storage.WarningWALHoleSuspected) + } +} diff --git a/seaweed-block/core/storage/smartwal/store.go b/seaweed-block/core/storage/smartwal/store.go index e94b150285..8913f4d38b 100644 --- a/seaweed-block/core/storage/smartwal/store.go +++ b/seaweed-block/core/storage/smartwal/store.go @@ -528,3 +528,9 @@ func (s *Store) SyncCount() uint64 { return s.syncs.Load() } // Compile-time assertion: Store satisfies the LogicalStorage contract. var _ storage.LogicalStorage = (*Store)(nil) + +// RecoveryWarnings: RED stub (the reviewed head reports none). +func (s *Store) RecoveryWarnings() []string { return nil } + +// HolesSuspected: RED stub. +func (s *Store) HolesSuspected() uint64 { return 0 } diff --git a/seaweed-block/core/storage/walstore_midhistory_hole_test.go b/seaweed-block/core/storage/walstore_midhistory_hole_test.go index da21ca4f24..b5b37fc802 100644 --- a/seaweed-block/core/storage/walstore_midhistory_hole_test.go +++ b/seaweed-block/core/storage/walstore_midhistory_hole_test.go @@ -6,11 +6,10 @@ import ( "testing" ) -// Issue #51, walstore interim (claude05's ruling 2026-11-16 06:14Z): a -// plain power loss must never become an outage, so a WAL hole followed by -// valid records does not fail recovery. It is detected, logged, counted and -// reported as the typed warning wal_hole_suspected, and nothing after the -// hole is replayed in any range. +// Issue #51, walstore (claude05's ruling 2026-11-16 06:47Z): pure +// detection. A WAL hole followed by valid records is logged, counted and +// reported as the typed warning wal_hole_suspected; nothing about what is +// replayed, where replay stops, or whether the volume opens changes. // writeSyncedEntries writes one block to each of lbas (in order), syncs, // and returns the store with auto-flush off (nothing checkpointed) and @@ -80,8 +79,8 @@ func holeWarning(s *WALStore) bool { return false } -// (a) A corrupted mid-history synced record: recovery succeeds to the -// prefix before it, warns (typed, counted), and replays nothing after it. +// (a) A corrupted mid-history synced record: recovery opens as before +// (this range stops at it), and warns (typed, counted). func TestWALStoreRecoverWarnsOnMidHistoryHole(t *testing.T) { s, path, offs := writeSyncedEntries(t, []uint32{0, 1, 2, 3}) flipDataByte(t, s, offs[1]) @@ -132,10 +131,13 @@ func TestWALStoreRecoverKeepsATornTail(t *testing.T) { } } -// (c) No replay past a hole across wrapped ranges: the older record at the -// high end of the WAL is corrupted; the newer batch that wrapped to offset -// 0 must not be replayed. -func TestWALStoreRecoverNoReplayPastAHoleAcrossWrappedRanges(t *testing.T) { +// (c) A hole across wrapped ranges (the older record at the high end +// corrupted, the newer batch wrapped to offset 0) is no outage. Detection +// here is per range: when the newer entries were scanned first there is +// nothing "later" left to find, and telling generations apart across +// ranges (like not replaying past such a hole) is the post-M4 watermark +// work. +func TestWALStoreRecoverWrappedHoleIsNoOutage(t *testing.T) { const ( blockSize = 4096 walSize = 24 * 1024 @@ -154,35 +156,53 @@ func TestWALStoreRecoverNoReplayPastAHoleAcrossWrappedRanges(t *testing.T) { if err := s.flusher.flushOnce(); err != nil { t.Fatal(err) } - if _, err := s.Write(20, makeBlock(blockSize, 0xA4)); err != nil { // high end + if _, err := s.Write(20, makeBlock(blockSize, 0xA4)); err != nil { t.Fatal(err) } s.enableMultiBlockRecordsForTest(true) - if _, err := s.WriteBatch(24, [][]byte{makeBlock(blockSize, 0xB5), makeBlock(blockSize, 0xB6)}); err != nil { // wraps to 0 + if _, err := s.WriteBatch(24, [][]byte{makeBlock(blockSize, 0xB5), makeBlock(blockSize, 0xB6)}); err != nil { t.Fatal(err) } if _, err := s.Sync(); err != nil { t.Fatal(err) } offs := walOffsetsByLBA(s) - if offs[24] != 0 || offs[20] == 0 { - t.Fatalf("offsets high=%d low=%d; want the batch wrapped to 0", offs[20], offs[24]) - } flipDataByte(t, s, offs[20]) r, _, err := reopenAfterCrash(t, s, path) if err != nil { - t.Fatalf("Recover: %v; want no outage", err) - } - if !holeWarning(r) { - t.Fatalf("warnings %v; want %s", r.RecoveryWarnings(), WarningWALHoleSuspected) - } - for _, lba := range []uint32{24, 25} { - got, err := r.Read(lba) - if err != nil { - t.Fatal(err) - } - if got[0] == 0xB5 || got[0] == 0xB6 { - t.Fatalf("LBA %d replayed from past the hole (byte %02x)", lba, got[0]) - } + t.Fatalf("Recover = %v; want no outage", err) } + _ = r +} + +// codex01's r1 P1: a damaged STALE record in a released range (below the +// checkpoint, outside the retained window) must not cost retained data. +// Layout: checkpoint 2, persisted tail at S, head at 3S; LSN 1 (released) +// at 0 damaged, LSN 2 checkpointed at S, LSN 3 synced and unflushed at 2S. +// LSN 3 must be replayed with its exact bytes. +func TestWALStoreRecoverStaleReleasedGarbageKeepsRetainedData(t *testing.T) { + const blockSize = 4096 + s, path, offs := writeSyncedEntries(t, []uint32{0, 1, 2}) + S := uint64(walEntryHeaderSize + blockSize) + if offs[0] != 0 || offs[1] != S || offs[2] != 2*S { + t.Fatalf("offsets %v; want 0, S, 2S", offs) + } + sb := *s.sb + sb.WALCheckpointLSN, sb.WALTail, sb.WALHead = 2, S, 3*S + buf := newSimpleByteBuf() + if _, err := sb.writeTo(buf); err != nil { + t.Fatal(err) + } + if _, err := s.fd.WriteAt(buf.bytes(), 0); err != nil { + t.Fatal(err) + } + if err := s.fd.Sync(); err != nil { + t.Fatal(err) + } + flipDataByte(t, s, offs[0]) // the released LSN 1 + r, _, err := reopenAfterCrash(t, s, path) + if err != nil { + t.Fatalf("Recover: %v", err) + } + assertRecoveryHardeningBlock(t, r, 2, makeBlock(blockSize, 0xB2)) // LSN 3, exact bytes } From d87c49d9d42930ad2d4b916beb8caf7de7a8fbaa Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 23:04:21 -0800 Subject: [PATCH 4/4] storage: WAL holes are detection only (#51, ruling A) claude05's ruling (A), 2026-11-16 06:47Z: nothing about which records replay, where replay stops, or whether the volume opens changes. - walstore: recovery.go is main's replay again; the checkpoint+1 cutoff and the cross-range stop are gone. At a non-zero bad entry a look-ahead finds whether a valid later entry (LSN above the highest decoded so far) follows in the rest of its range or a later one; if so the typed warning wal_hole_suspected is logged and counted. A look-ahead read error is logged and changes nothing. - smartwal: the positional mid-history fail-closed is gone (no generation guessing). Populated slots whose record CRC fails are skipped as before and reported as the counted warning (a torn tail or a corrupted record; not distinguishable without a watermark). ea1faf6a's data-CRC fail-closed stays as merged. - the warning still reaches the durable status and /status and never changes Healthy, readiness or promotion. Cross-range detection, no replay past a hole, and any new fail-closed move to the post-M4 watermark work. Last-writer-wins by LSN is #156. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/recovery.go | 253 +++++++----------- .../core/storage/smartwal/recovery.go | 49 ++-- seaweed-block/core/storage/smartwal/store.go | 39 ++- 3 files changed, 151 insertions(+), 190 deletions(-) diff --git a/seaweed-block/core/storage/recovery.go b/seaweed-block/core/storage/recovery.go index d14f4c58c5..0f79da6784 100644 --- a/seaweed-block/core/storage/recovery.go +++ b/seaweed-block/core/storage/recovery.go @@ -10,16 +10,17 @@ import ( // recoveryResult summarizes what RecoverWAL did on one open. type recoveryResult struct { - // HoleSuspected: a bad entry was followed by a valid later one (issue - // #51); replay stopped before it. HoleDetail says where. - HoleSuspected bool - HoleDetail string EntriesReplayed int // valid entries past checkpoint that were replayed HighestLSN uint64 // highest LSN observed across the whole scan WALHead uint64 // reconstructed logical byte head of retained WAL WALTail uint64 // reconstructed logical byte tail of retained WAL TornEntries int // entries discarded due to CRC failure or truncation DefensiveScan bool // true when the superblock was empty and we scanned the whole region + // HoleSuspected: a bad entry was followed by a valid later entry + // (issue #51). Detection only: it changes nothing about what is + // replayed. HoleDetail says where. + HoleSuspected bool + HoleDetail string } // recoverWAL scans the WAL region and replays any entries that have @@ -56,6 +57,8 @@ func recoverWAL(fd *os.File, sb *superblock, dm *dirtyMap) (recoveryResult, erro type scanRange = recoveryScanRange var ranges []scanRange + // lastLSN is the highest LSN decoded so far (detection only). + var lastLSN uint64 if logicalHead == logicalTail { // A pre-boundary-persistence crash can leave a wrapped retained @@ -95,26 +98,6 @@ func recoverWAL(fd *os.File, sb *superblock, dm *dirtyMap) (recoveryResult, erro } } - // Pass 1 decodes every range and collects the entries; nothing is - // replayed yet. Replay order is by LSN, not by scan order: a persisted - // head/tail can predate a wrap, so a range read first may hold newer - // entries than one read later (issue #51). - type scanned struct { - entry walEntry - start, end uint64 - lowLSN uint64 // first LSN above the checkpoint - highLSN uint64 - padding bool - } - var items []scanned - byEnd := map[uint64]int{} // end offset -> index in items - type badEntry struct { - ri int - pos uint64 - cause error - resyncTo uint64 - } - var bad []badEntry for ri, r := range ranges { pos := r.start for pos < r.end { @@ -131,10 +114,7 @@ func recoverWAL(fd *os.File, sb *superblock, dm *dirtyMap) (recoveryResult, erro lengthField := parseLengthFromHeader(headerBuf) if entryType == walEntryPadding { - end := pos + uint64(walEntryHeaderSize) + uint64(lengthField) - items = append(items, scanned{start: pos, end: end, padding: true}) - byEnd[end] = len(items) - 1 - pos = end + pos += uint64(walEntryHeaderSize) + uint64(lengthField) continue } var payloadLen uint64 @@ -142,24 +122,23 @@ func recoverWAL(fd *os.File, sb *superblock, dm *dirtyMap) (recoveryResult, erro payloadLen = uint64(lengthField) } entrySize := uint64(walEntryHeaderSize) + payloadLen - var entry walEntry - var derr error if entrySize > remaining { - derr = errEntryTruncated - } else { - fullBuf := make([]byte, entrySize) - if _, err := fd.ReadAt(fullBuf, absOff); err != nil { - return result, fmt.Errorf("storage: recovery read entry at %d: %w", pos, err) - } - entry, derr = decodeWALEntry(fullBuf) - } - if derr != nil { - // Torn write, corruption, or trailing zeros: this range - // ends here. A non-zero bad entry is a possible hole, - // decided after the scan. result.TornEntries++ - if !allZeroBytes(headerBuf) { - bad = append(bad, badEntry{ri: ri, pos: pos, cause: derr}) + if err := detectHole(&result, fd, walOffset, ranges, ri, pos, headerBuf, max(lastLSN, checkpointLSN), sb.BlockSize, nil); err != nil { + return result, err + } + break + } + fullBuf := make([]byte, entrySize) + if _, err := fd.ReadAt(fullBuf, absOff); err != nil { + return result, fmt.Errorf("storage: recovery read entry at %d: %w", pos, err) + } + entry, err := decodeWALEntry(fullBuf) + if err != nil { + // Torn write or trailing zeros — stop scanning this range. + result.TornEntries++ + if herr := detectHole(&result, fd, walOffset, ranges, ri, pos, headerBuf, max(lastLSN, checkpointLSN), sb.BlockSize, err); herr != nil { + return result, herr } break } @@ -180,120 +159,64 @@ func recoverWAL(fd *os.File, sb *superblock, dm *dirtyMap) (recoveryResult, erro } highestEntryLSN = entry.LSN + entry.Reserved - 1 } - entry.Data = nil // replay reads the WAL at its offset, never this copy - lowLSN := entry.LSN - if lowLSN <= checkpointLSN { - lowLSN = checkpointLSN + 1 + if highestEntryLSN > lastLSN { + lastLSN = highestEntryLSN } - items = append(items, scanned{entry: entry, start: pos, end: pos + entrySize, lowLSN: lowLSN, highLSN: highestEntryLSN}) - byEnd[pos+entrySize] = len(items) - 1 - pos += entrySize - } - } - - // The earliest hole: a bad entry was appended after the entry that - // ends where it starts (its circular predecessor, padding skipped), so - // its LSN is above that entry's. Nothing at or above that bound is - // replayed; any valid entry there makes it a mid-history hole. - holeLSN := ^uint64(0) - var holeAt uint64 - var holeCause error - for _, b := range bad { - pred := checkpointLSN - cur := b.pos - for guard := 0; guard <= len(items); guard++ { - i, ok := byEnd[cur] - if !ok && cur == 0 { - i, ok = byEnd[walSize] - } - if !ok { - break - } - if items[i].padding { - cur = items[i].start + if highestEntryLSN <= checkpointLSN { + pos += entrySize continue } - pred = max(pred, items[i].highLSN) - break - } - if pred+1 < holeLSN { - holeLSN, holeAt, holeCause = pred+1, b.pos, b.cause - } - } - hole := false - if len(bad) > 0 { - for _, it := range items { - if !it.padding && it.highLSN > checkpointLSN && it.highLSN >= holeLSN { - hole = true - break + firstRetainedLSN := entry.LSN + if firstRetainedLSN <= checkpointLSN { + firstRetainedLSN = checkpointLSN + 1 } - } - if !hole { - // Valid entries the scan did not reach (after the bad one in - // its range) count too. - for _, b := range bad { - found, _, err := laterValidEntry(fd, walOffset, ranges, b.ri, b.pos+1, holeLSN-1, sb.BlockSize) - if err != nil { - return result, err + retainedRecords = append(retainedRecords, retainedRecord{ + firstLSN: firstRetainedLSN, + start: pos, + end: pos + entrySize, + }) + switch entry.Type { + case walEntryWrite: + blocks := entry.Length / sb.BlockSize + for i := uint32(0); i < blocks; i++ { + dm.putAt( + entry.LBA+uint64(i), pos, i*sb.BlockSize, + entry.LSN, sb.BlockSize, + ) } - if found { - hole = true - break + result.EntriesReplayed++ + case walEntryWriteBatch: + blocks := uint32(entry.Reserved) + for i := uint32(0); i < blocks; i++ { + lsn := entry.LSN + uint64(i) + if lsn <= checkpointLSN { + continue + } + dm.putAt( + entry.LBA+uint64(i), pos, i*sb.BlockSize, + lsn, sb.BlockSize, + ) } - } - } - } - if hole { - result.HoleSuspected = true - result.HoleDetail = fmt.Sprintf("WAL entry at offset=%d fails its check and valid entries from LSN %d on follow it; recovered the entries below LSN %d", holeAt, holeLSN, holeLSN) - if holeCause != nil { - result.HoleDetail += " (" + holeCause.Error() + ")" - } - log.Printf("storage: recovery %s: %s", WarningWALHoleSuspected, result.HoleDetail) - } - - // Pass 2: replay every entry above the checkpoint and below the hole. - for _, it := range items { - if it.padding || it.highLSN <= checkpointLSN || it.highLSN >= holeLSN { - continue - } - entry, pos := it.entry, it.start - retainedRecords = append(retainedRecords, retainedRecord{ - firstLSN: it.lowLSN, - start: it.start, - end: it.end, - }) - switch entry.Type { - case walEntryWrite: - blocks := entry.Length / sb.BlockSize - for i := uint32(0); i < blocks; i++ { - dm.putAt(entry.LBA+uint64(i), pos, i*sb.BlockSize, entry.LSN, sb.BlockSize) - } - result.EntriesReplayed++ - case walEntryWriteBatch: - blocks := uint32(entry.Reserved) - for i := uint32(0); i < blocks; i++ { - lsn := entry.LSN + uint64(i) - if lsn <= checkpointLSN { - continue + result.EntriesReplayed++ + case walEntryTrim: + blocks := entry.Length / sb.BlockSize + if blocks == 0 { + blocks = 1 } - dm.putAt(entry.LBA+uint64(i), pos, i*sb.BlockSize, lsn, sb.BlockSize) + for i := uint32(0); i < blocks; i++ { + dm.putAt( + entry.LBA+uint64(i), pos, i*sb.BlockSize, + entry.LSN, sb.BlockSize, + ) + } + result.EntriesReplayed++ + case walEntryBarrier: + // no data; skip } - result.EntriesReplayed++ - case walEntryTrim: - blocks := entry.Length / sb.BlockSize - if blocks == 0 { - blocks = 1 + if highestEntryLSN > result.HighestLSN { + result.HighestLSN = highestEntryLSN } - for i := uint32(0); i < blocks; i++ { - dm.putAt(entry.LBA+uint64(i), pos, i*sb.BlockSize, entry.LSN, sb.BlockSize) - } - result.EntriesReplayed++ - case walEntryBarrier: - // no data; skip - } - if it.highLSN > result.HighestLSN { - result.HighestLSN = it.highLSN + pos += entrySize } } @@ -490,3 +413,35 @@ func plausibleEntryHeader(h []byte, minLSN, remaining uint64, blockSize uint32) } return size, true } + +// detectHole notes a suspected WAL hole at a bad entry (issue #51; +// claude05's ruling 2026-11-16 06:47Z: detection only). An all-zero +// header is just the end of what was written. Otherwise, if a valid entry +// with an LSN above minLSN (the highest decoded so far, or the checkpoint) +// follows it, the hole is recorded as the typed warning +// WarningWALHoleSuspected and logged. Nothing about the replay changes: +// the caller stops this range exactly as before. A torn tail and a +// corrupted record cannot be told apart without a synced watermark, hence +// "suspected". +func detectHole(result *recoveryResult, fd *os.File, walOffset uint64, ranges []recoveryScanRange, ri int, pos uint64, header []byte, minLSN uint64, blockSize uint32, cause error) error { + if allZeroBytes(header) || result.HoleSuspected { + return nil + } + found, at, err := laterValidEntry(fd, walOffset, ranges, ri, pos+1, minLSN, blockSize) + if err != nil { + // Detection never changes the outcome: a failed look-ahead read + // is logged, and recovery goes on exactly as before. + log.Printf("storage: recovery hole detection at offset=%d skipped: %v", pos, err) + return nil + } + if !found { + return nil + } + result.HoleSuspected = true + result.HoleDetail = fmt.Sprintf("WAL entry at offset=%d fails its check and a valid later entry (LSN > %d) follows at offset=%d", pos, minLSN, at) + if cause != nil { + result.HoleDetail += " (" + cause.Error() + ")" + } + log.Printf("storage: recovery %s: %s", WarningWALHoleSuspected, result.HoleDetail) + return nil +} diff --git a/seaweed-block/core/storage/smartwal/recovery.go b/seaweed-block/core/storage/smartwal/recovery.go index d6baa17212..310fa8cf41 100644 --- a/seaweed-block/core/storage/smartwal/recovery.go +++ b/seaweed-block/core/storage/smartwal/recovery.go @@ -37,16 +37,21 @@ import ( // - per-block CRC stored alongside extent (extent stays raw blocks) // - cross-checking against any external snapshot func runRecovery(r *ring, fd *os.File, extentBase int64, blockSize int) (uint64, error) { + frontier, _, err := runRecoveryCounting(r, fd, extentBase, blockSize) + return frontier, err +} + +// runRecoveryCounting is runRecovery that also reports how many populated +// slots fail their record CRC (issue #51, detection only: they are +// skipped exactly as before; see Store.Recover's warning). +func runRecoveryCounting(r *ring, fd *os.File, extentBase int64, blockSize int) (uint64, int, error) { records, bad, err := r.scanSlots() if err != nil { - return 0, fmt.Errorf("smartwal: recovery scan: %w", err) + return 0, 0, fmt.Errorf("smartwal: recovery scan: %w", err) } if len(records) == 0 { log.Printf("smartwal: recovery: ring empty; nothing to verify") - return 0, nil - } - if err := midHistoryHole(bad, records[len(records)-1].LSN, r.capacity); err != nil { - return 0, err + return 0, len(bad), nil } // Last-writer-wins map. Records arrive sorted by LSN ascending, @@ -68,12 +73,12 @@ func runRecovery(r *ring, fd *os.File, extentBase int64, blockSize int) (uint64, data := make([]byte, blockSize) off := extentBase + int64(rec.LBA)*int64(blockSize) if _, err := fd.ReadAt(data, off); err != nil { - return 0, fmt.Errorf("smartwal: recovery read trim LBA %d: %w", rec.LBA, err) + return 0, 0, fmt.Errorf("smartwal: recovery read trim LBA %d: %w", rec.LBA, err) } if crc32.ChecksumIEEE(data) != rec.DataCRC32 { detail := fmt.Sprintf("trim CRC mismatch LSN=%d LBA=%d", rec.LSN, rec.LBA) log.Printf("smartwal: recovery %s — failing closed", detail) - return 0, storage.NewWALIntegrityFailure(nil, detail) + return 0, 0, storage.NewWALIntegrityFailure(nil, detail) } recovered++ if rec.LSN > highestVerifiedLSN { @@ -85,14 +90,14 @@ func runRecovery(r *ring, fd *os.File, extentBase int64, blockSize int) (uint64, data := make([]byte, blockSize) off := extentBase + int64(rec.LBA)*int64(blockSize) if _, err := fd.ReadAt(data, off); err != nil { - return 0, fmt.Errorf("smartwal: recovery read LBA %d: %w", rec.LBA, err) + return 0, 0, fmt.Errorf("smartwal: recovery read LBA %d: %w", rec.LBA, err) } actual := crc32.ChecksumIEEE(data) if actual != rec.DataCRC32 { detail := fmt.Sprintf("CRC mismatch LSN=%d LBA=%d expected=%08x actual=%08x", rec.LSN, rec.LBA, rec.DataCRC32, actual) log.Printf("smartwal: recovery %s — failing closed", detail) - return 0, storage.NewWALIntegrityFailure(nil, detail) + return 0, 0, storage.NewWALIntegrityFailure(nil, detail) } recovered++ if rec.LSN > highestVerifiedLSN { @@ -102,29 +107,5 @@ func runRecovery(r *ring, fd *os.File, extentBase int64, blockSize int) (uint64, log.Printf("smartwal: recovery: %d LBAs verified, frontier=%d", recovered, highestVerifiedLSN) - return highestVerifiedLSN, nil -} - -// midHistoryHole fails closed on a corrupted committed slot (issue #51; -// claude05's ruling 2026-11-16 06:10Z/06:14Z). Slot i holds LSN i mod -// capacity, so with H the highest valid LSN a bad slot at distance d -// (1 <= d < capacity-1) behind H's slot implies LSN H-d: a record a later -// valid record (H) follows, i.e. a mid-history hole. The slot right after -// H's (d = capacity-1) is where LSN H+1 goes: a torn tail, which still -// recovers; so is a slot whose implied LSN was never written. -func midHistoryHole(bad []uint64, highest, capacity uint64) error { - if capacity < 2 { - return nil - } - hs := highest % capacity - for _, i := range bad { - d := (hs + capacity - i) % capacity - if d == 0 || d == capacity-1 || d >= highest { - continue // H's own slot (impossible), the torn-tail position, or never written - } - detail := fmt.Sprintf("corrupted record in slot %d (implied LSN %d) below the valid LSN %d: mid-history hole", i, highest-d, highest) - log.Printf("smartwal: recovery %s — failing closed", detail) - return storage.NewWALIntegrityFailure(nil, detail) - } - return nil + return highestVerifiedLSN, len(bad), nil } diff --git a/seaweed-block/core/storage/smartwal/store.go b/seaweed-block/core/storage/smartwal/store.go index 8913f4d38b..56673d9993 100644 --- a/seaweed-block/core/storage/smartwal/store.go +++ b/seaweed-block/core/storage/smartwal/store.go @@ -4,6 +4,7 @@ import ( "errors" "fmt" "hash/crc32" + "log" "os" "path/filepath" "sync" @@ -52,6 +53,11 @@ const defaultWALSlots = 65536 // the same LBA from different goroutines are NOT serialized at this // layer — callers must order their own per-LBA writes. type Store struct { + // recoveryWarnings and holesSuspected: the last Recover's typed + // warnings, and how many recoveries saw bad slots (issue #51). + recoveryWarnings []string + holesSuspected uint64 + path string fd *os.File hdr *header @@ -176,16 +182,41 @@ func openInitialized(path string, f *os.File, hdr *header) (*Store, error) { // Recover rebuilds the in-memory LSN counter from the ring buffer. // Idempotent: calling twice on the same on-disk state yields the // same result. +// RecoveryWarnings returns the last Recover's typed warnings. +func (s *Store) RecoveryWarnings() []string { + s.mu.RLock() + defer s.mu.RUnlock() + return append([]string(nil), s.recoveryWarnings...) +} + +// HolesSuspected counts the recoveries that saw populated slots failing +// their record CRC. +func (s *Store) HolesSuspected() uint64 { + s.mu.RLock() + defer s.mu.RUnlock() + return s.holesSuspected +} + func (s *Store) Recover() (uint64, error) { s.mu.Lock() defer s.mu.Unlock() if s.closed { return 0, errors.New("smartwal: Recover after Close") } - frontier, err := runRecovery(s.ring, s.fd, s.extentBase, int(s.hdr.BlockSize)) + frontier, bad, err := runRecoveryCounting(s.ring, s.fd, s.extentBase, int(s.hdr.BlockSize)) if err != nil { return 0, err } + // Detection only (issue #51): populated slots whose record CRC fails + // were skipped as before. Without a synced watermark a torn tail and + // a corrupted committed record cannot be told apart, so this is a + // "suspected" warning that changes nothing else. + s.recoveryWarnings = nil + if bad > 0 { + s.holesSuspected++ + s.recoveryWarnings = []string{fmt.Sprintf("%s: %d populated WAL slot(s) fail their record CRC (a torn tail or a corrupted record; not distinguishable without a synced watermark)", storage.WarningWALHoleSuspected, bad)} + log.Printf("smartwal: recovery %s", s.recoveryWarnings[0]) + } if frontier >= s.nextLSN { s.nextLSN = frontier + 1 } @@ -528,9 +559,3 @@ func (s *Store) SyncCount() uint64 { return s.syncs.Load() } // Compile-time assertion: Store satisfies the LogicalStorage contract. var _ storage.LogicalStorage = (*Store)(nil) - -// RecoveryWarnings: RED stub (the reviewed head reports none). -func (s *Store) RecoveryWarnings() []string { return nil } - -// HolesSuspected: RED stub. -func (s *Store) HolesSuspected() uint64 { return 0 }