From d2a6a3b02c657d482b9a546637f096fefb24f719 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 22:29:41 -0800 Subject: [PATCH 01/16] 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 02/16] 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 67998e5df66adc7a90e26d4776ced18d2aeac9f4 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 22:49:45 -0800 Subject: [PATCH 03/16] storage: RED control: walstore recovery replays an older version over a newer one claude05's ruling (B), 2026-11-16 06:47Z. On main, recovery applies entries to the dirty map in physical range-scan order and putAt replaces unconditionally. When the persisted head/tail predate a wrap, the range scanned first can hold the newer version of an LBA and a later range the older one: the older version wins, silently. TestWALStoreRecoverLastWriterWinsAcrossScanOrder: LBA 20 written at the high end (LSN 4), then rewritten by a batch that wraps to offset 0 (LSN 5); after recovery LBA 20 reads the LSN 4 bytes. Co-Authored-By: Claude Opus 5.5 --- .../storage/walstore_recovery_lww_test.go | 64 +++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 seaweed-block/core/storage/walstore_recovery_lww_test.go diff --git a/seaweed-block/core/storage/walstore_recovery_lww_test.go b/seaweed-block/core/storage/walstore_recovery_lww_test.go new file mode 100644 index 0000000000..1f319e574a --- /dev/null +++ b/seaweed-block/core/storage/walstore_recovery_lww_test.go @@ -0,0 +1,64 @@ +package storage + +import ( + "path/filepath" + "testing" +) + +// Recovery is last-writer-wins by LSN (claude05's ruling (B), 2026-11-16 +// 06:47Z). Two valid versions of one LBA survive in the WAL; the persisted +// head/tail predate the wrap, so the range scanned first holds the newer +// version (wrapped to offset 0) and the range scanned later the older one. +// Recovery must still serve the newer bytes. +func TestWALStoreRecoverLastWriterWinsAcrossScanOrder(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 { // checkpoint 3: head/tail persisted here + t.Fatal(err) + } + older := makeBlock(blockSize, 0xA4) + if _, err := s.Write(20, older); err != nil { // LSN 4, at the high end + t.Fatal(err) + } + newer := makeBlock(blockSize, 0xB5) + s.enableMultiBlockRecordsForTest(true) + if _, err := s.WriteBatch(20, [][]byte{newer, makeBlock(blockSize, 0xB6)}); err != nil { // LSN 5-6, wraps to 0 + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if e := recoverySnapshotEntriesByLBA(s.dm.snapshot())[20]; e.WALOffset != 0 || e.LSN != 5 { + t.Fatalf("newest LBA 20 entry at offset %d LSN %d; want the wrapped batch at 0, LSN 5", e.WALOffset, e.LSN) + } + crashRecoveryHardeningStore(t, s) + r, err := OpenWALStore(path) + if err != nil { + t.Fatal(err) + } + r.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = r.Close() }) + if _, err := r.Recover(); err != nil { + t.Fatal(err) + } + got, err := r.Read(20) + if err != nil { + t.Fatal(err) + } + if got[0] != newer[0] { + t.Fatalf("LBA 20 after recovery = %02x; want the newer version %02x (LSN 5), not the older %02x (LSN 4)", got[0], newer[0], older[0]) + } +} From ca42d7681226ef7907829e8bff065ec33b12529b Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 22:55:13 -0800 Subject: [PATCH 04/16] storage: walstore recovery is last-writer-wins by LSN claude05's ruling (B), 2026-11-16 06:47Z. Recovery replay now uses dirtyMap.putAtIfNewer: an entry replaces an LBA's dirty-map entry only when its LSN is higher. Range scan order is physical, and a persisted head/tail can predate a wrap, so a newer version can be scanned before an older one. This changes only the order in which the replayed entries take effect, never which entries are replayed; the runtime write paths keep putAt. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/dirty_map.go | 22 ++++++++++++++++++++++ seaweed-block/core/storage/recovery.go | 6 +++--- 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/seaweed-block/core/storage/dirty_map.go b/seaweed-block/core/storage/dirty_map.go index 89a6ff72b6..99f9723598 100644 --- a/seaweed-block/core/storage/dirty_map.go +++ b/seaweed-block/core/storage/dirty_map.go @@ -50,6 +50,28 @@ func (d *dirtyMap) put(lba, walOffset, lsn uint64, length uint32) { d.putAt(lba, walOffset, 0, lsn, length) } +// putAtIfNewer is putAt for recovery replay: last writer wins by LSN, so +// an older version of an LBA scanned after a newer one (range scan order +// is physical, not LSN order) never replaces it. +func (d *dirtyMap) putAtIfNewer( + lba, walOffset uint64, + dataOffset uint32, + lsn uint64, + length uint32, +) { + s := d.shard(lba) + s.mu.Lock() + if cur, ok := s.m[lba]; !ok || cur.lsn < lsn { + s.m[lba] = dirtyEntry{ + walOffset: walOffset, + dataOffset: dataOffset, + lsn: lsn, + length: length, + } + } + s.mu.Unlock() +} + func (d *dirtyMap) putAt( lba, walOffset uint64, dataOffset uint32, diff --git a/seaweed-block/core/storage/recovery.go b/seaweed-block/core/storage/recovery.go index 3b0f6d12e1..43ca18107c 100644 --- a/seaweed-block/core/storage/recovery.go +++ b/seaweed-block/core/storage/recovery.go @@ -165,7 +165,7 @@ func recoverWAL(fd *os.File, sb *superblock, dm *dirtyMap) (recoveryResult, erro case walEntryWrite: blocks := entry.Length / sb.BlockSize for i := uint32(0); i < blocks; i++ { - dm.putAt( + dm.putAtIfNewer( entry.LBA+uint64(i), pos, i*sb.BlockSize, entry.LSN, sb.BlockSize, ) @@ -178,7 +178,7 @@ func recoverWAL(fd *os.File, sb *superblock, dm *dirtyMap) (recoveryResult, erro if lsn <= checkpointLSN { continue } - dm.putAt( + dm.putAtIfNewer( entry.LBA+uint64(i), pos, i*sb.BlockSize, lsn, sb.BlockSize, ) @@ -190,7 +190,7 @@ func recoverWAL(fd *os.File, sb *superblock, dm *dirtyMap) (recoveryResult, erro blocks = 1 } for i := uint32(0); i < blocks; i++ { - dm.putAt( + dm.putAtIfNewer( entry.LBA+uint64(i), pos, i*sb.BlockSize, entry.LSN, sb.BlockSize, ) From e910449f70863234c3d735e002e3d9e4e24ee037 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 23:04:18 -0800 Subject: [PATCH 05/16] 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 06/16] 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 } From 342dc3529a685639346005dd02039e0d06984371 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 23:30:05 -0800 Subject: [PATCH 07/16] fix: separate workspace lease expiry with a clock skew margin --- seaweed-block/cmd/blockmaster/main.go | 6 + .../cmd/blockmaster/workspace_skew_test.go | 25 ++++ seaweed-block/core/authority/authority.go | 1 + seaweed-block/core/authority/workspace.go | 44 +++++-- .../core/authority/workspace_skew_test.go | 47 ++++++++ .../core/authority/workspace_test.go | 4 + .../core/host/bootstrap/bootstrap.go | 31 ++--- seaweed-block/core/host/master/host.go | 14 ++- .../host/master/workspace_binding_test.go | 4 +- .../master/workspace_move_integration_test.go | 4 +- .../core/host/master/workspace_service.go | 8 +- .../core/host/master/workspace_skew_test.go | 112 ++++++++++++++++++ .../core/host/volume/workspace_lease.go | 2 + seaweed-block/docs/workspace-lease.md | 13 ++ 14 files changed, 282 insertions(+), 33 deletions(-) create mode 100644 seaweed-block/cmd/blockmaster/workspace_skew_test.go create mode 100644 seaweed-block/core/authority/workspace_skew_test.go create mode 100644 seaweed-block/core/host/master/workspace_skew_test.go diff --git a/seaweed-block/cmd/blockmaster/main.go b/seaweed-block/cmd/blockmaster/main.go index 9a49dbb074..a39bd4e63e 100644 --- a/seaweed-block/cmd/blockmaster/main.go +++ b/seaweed-block/cmd/blockmaster/main.go @@ -55,6 +55,7 @@ type flags struct { launcherCHAPUserKey string launcherCHAPSecretKey string failbackRuntimeRPC bool + workspaceMaxClockSkew time.Duration workspaceRPC bool workspaceHEADBase string frontendPublicationRuntimeHTTP bool @@ -104,6 +105,7 @@ func parseFlags(args []string) (flags, error) { fs.StringVar(&f.launcherCHAPUserKey, "launcher-iscsi-chap-username-key", "chapUsername", "Kubernetes Secret key for generated blockvolume iSCSI CHAP username") fs.StringVar(&f.launcherCHAPSecretKey, "launcher-iscsi-chap-secret-key", "chapSecret", "Kubernetes Secret key for generated blockvolume iSCSI CHAP secret") fs.BoolVar(&f.failbackRuntimeRPC, "failback-runtime-rpc", false, "enable disabled-by-default authority failback RPC; requires expected-current and terminal evidence") + fs.DurationVar(&f.workspaceMaxClockSkew, "workspace-max-clock-skew", 20*time.Second, "maximum workspace clock skew; host lease shortens by half, forced moves wait the full bound") fs.BoolVar(&f.workspaceRPC, "workspace-rpc", false, "enable RF1 workspace lease/revocation/move RPCs") fs.StringVar(&f.workspaceHEADBase, "workspace-head-base-url", "", "filer HTTP directory containing per-volume HEAD files; required with --workspace-rpc") fs.BoolVar(&f.frontendPublicationRuntimeHTTP, "frontend-publication-runtime-http", false, "enable disabled-by-default frontend publication HTTP runtime; confirms post-failback authority publication only") @@ -123,6 +125,9 @@ func parseFlags(args []string) (flags, error) { if err := nvme.ValidateMaxH2CDataLength(uint32(f.launcherNVMeMaxH2CDataLength)); err != nil { return flags{}, fmt.Errorf("--launcher-nvme-max-h2c-data-length=%d invalid: %w", f.launcherNVMeMaxH2CDataLength, err) } + if f.workspaceMaxClockSkew <= 0 || f.workspaceMaxClockSkew >= 60*time.Second { + return flags{}, fmt.Errorf("--workspace-max-clock-skew must be positive and less than 60s") + } if f.authorityStore == "" { return flags{}, fmt.Errorf("--authority-store is required") } @@ -173,6 +178,7 @@ func run(f flags) int { Topology: topo, Freshness: authority.FreshnessConfig{FreshnessWindow: f.freshnessWindow, PendingGrace: f.pendingGrace}, ControllerConfig: authority.TopologyControllerConfig{ExpectedSlotsPerVolume: f.expectedSlotsPerVol}, + WorkspaceMaxClockSkew: f.workspaceMaxClockSkew, FailbackRuntimeRPC: f.failbackRuntimeRPC, FrontendPublicationRuntimeHTTP: f.frontendPublicationRuntimeHTTP, FrontendPublicationRuntimeListen: f.frontendPublicationRuntimeListen, diff --git a/seaweed-block/cmd/blockmaster/workspace_skew_test.go b/seaweed-block/cmd/blockmaster/workspace_skew_test.go new file mode 100644 index 0000000000..10a48483ae --- /dev/null +++ b/seaweed-block/cmd/blockmaster/workspace_skew_test.go @@ -0,0 +1,25 @@ +package main + +import ( + "testing" + "time" +) + +func TestWorkspaceClockSkewFlag(t *testing.T) { + for _, v := range []string{"0s", "-1s", "60s", "90s"} { + if _, err := parseFlags([]string{"--authority-store", "unused", "--workspace-max-clock-skew", v}); err == nil { + t.Errorf("accepted %s", v) + } + } + for _, v := range []string{"1s", "20s", "59s"} { + f, err := parseFlags([]string{"--authority-store", "unused", "--workspace-max-clock-skew", v}) + want, _ := time.ParseDuration(v) + if err != nil || f.workspaceMaxClockSkew != want { + t.Fatal(v, f.workspaceMaxClockSkew, err) + } + } + f, err := parseFlags([]string{"--authority-store", "unused"}) + if err != nil || f.workspaceMaxClockSkew != 20*time.Second { + t.Fatal("default", err) + } +} diff --git a/seaweed-block/core/authority/authority.go b/seaweed-block/core/authority/authority.go index f14d05376b..88e5a2c2b4 100644 --- a/seaweed-block/core/authority/authority.go +++ b/seaweed-block/core/authority/authority.go @@ -161,6 +161,7 @@ type Publisher struct { workspaceUncertain map[string]bool workspaceNow func() time.Time workspaceTTL time.Duration + workspaceMaxClockSkew time.Duration workspaceLeaseDeadline map[string]time.Time } diff --git a/seaweed-block/core/authority/workspace.go b/seaweed-block/core/authority/workspace.go index 09980dd1cd..ea4f05b7fa 100644 --- a/seaweed-block/core/authority/workspace.go +++ b/seaweed-block/core/authority/workspace.go @@ -15,10 +15,11 @@ type WorkspaceHead struct { } type WorkspaceLease struct { - ReplicaID string - Epoch uint64 - ExpiresAtNS int64 - Revoking bool + ReplicaID string + Epoch uint64 + ExpiresAtNS int64 + MaxClockSkewNS int64 `json:",omitempty"` + Revoking bool } type WorkspaceRevokeAck struct { @@ -70,6 +71,27 @@ func WithWorkspaceLeaseConfig(ttl time.Duration, now func() time.Time) Publisher } } +// WithWorkspaceMaxClockSkew configures the bound between clocks. Zero keeps +// the default: two nominal TTL/3 renewal intervals. Existing grants retain +// their persisted bound when configuration is reduced after a restart. +func WithWorkspaceMaxClockSkew(skew time.Duration) PublisherOption { + return func(p *Publisher) { + if skew > 0 { + p.workspaceMaxClockSkew = skew + } + } +} +func (p *Publisher) workspaceSkew(lease *WorkspaceLease) time.Duration { + skew := p.workspaceMaxClockSkew + if skew <= 0 { + skew = p.workspaceTTL / 3 * 2 + } + if lease != nil && time.Duration(lease.MaxClockSkewNS) > skew { + skew = time.Duration(lease.MaxClockSkewNS) + } + return skew +} + func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder string, epoch uint64) (WorkspaceLease, error) { if err := ctx.Err(); err != nil { return WorkspaceLease{}, err @@ -96,7 +118,7 @@ func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder stri return WorkspaceLease{}, fmt.Errorf("workspace lease expired or revoking") } } - lease := WorkspaceLease{ReplicaID: holder, Epoch: epoch, ExpiresAtNS: now.Add(p.workspaceTTL).UnixNano()} + lease := WorkspaceLease{ReplicaID: holder, Epoch: epoch, ExpiresAtNS: now.Add(p.workspaceTTL).UnixNano(), MaxClockSkewNS: int64(p.workspaceSkew(s.Lease))} s.Lease = &lease if err := p.persistWorkspaceLocked(volume, s); err != nil { return WorkspaceLease{}, err @@ -291,6 +313,13 @@ func (p *Publisher) prepareWorkspaceMoveLocked(ask AssignmentAsk, g workspaceGra if !ok || line.info.Epoch != q.ExpectedEpoch || line.info.ReplicaID != q.ExpectedReplicaID || s == nil || s.Lease == nil { return nil, 0, fmt.Errorf("workspace move: missing or changed authority/lease") } + if q.Kind == "forced" { + now := p.workspaceNow() + skew := p.workspaceSkew(s.Lease) + if now.Before(time.Unix(0, s.Lease.ExpiresAtNS).Add(skew)) || now.Before(p.workspaceLeaseDeadline[q.VolumeID].Add(skew)) { + return nil, 0, fmt.Errorf("workspace forced move lease expiry plus clock-skew margin has not elapsed") + } + } // A restart may resume the identical durable reservation; it never grants // a different request the reserved epoch. for idx, r := range s.Moves { @@ -311,11 +340,6 @@ func (p *Publisher) prepareWorkspaceMoveLocked(ask AssignmentAsk, g workspaceGra if !h.Detached || !s.Lease.Revoking || s.Ack == nil || s.Ack.ReplicaID != q.ExpectedReplicaID || s.Ack.Epoch != q.ExpectedEpoch || s.Ack.HeadGen != h.Gen { return nil, 0, fmt.Errorf("workspace clean move needs detached HEAD and matching revocation ACK") } - } else { - now := p.workspaceNow() - if now.UnixNano() < s.Lease.ExpiresAtNS || now.Before(p.workspaceLeaseDeadline[q.VolumeID]) { - return nil, 0, fmt.Errorf("workspace forced move lease has not expired") - } } max := maxPublishedEpochForVolume(p.state, q.VolumeID) for _, r := range s.Moves { diff --git a/seaweed-block/core/authority/workspace_skew_test.go b/seaweed-block/core/authority/workspace_skew_test.go new file mode 100644 index 0000000000..320d43eba8 --- /dev/null +++ b/seaweed-block/core/authority/workspace_skew_test.go @@ -0,0 +1,47 @@ +package authority + +import ( + "context" + "testing" + "time" +) + +func TestWorkspaceClockSkewPersistsAndProtectsRestart(t *testing.T) { + for _, restart := range []bool{false, true} { + t.Run(map[bool]string{false: "live", true: "restart-smaller-config"}[restart], func(t *testing.T) { + disk, _ := newTempStore(t) + now := time.Unix(1000, 0) + start := now + p := NewPublisher(nil, WithStore(disk), WithWorkspaceLeaseConfig(6*time.Second, func() time.Time { return now }), WithWorkspaceMaxClockSkew(4*time.Second)) + if err := p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "r", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil { + t.Fatal(err) + } + lease, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1) + if err != nil { + t.Fatal(err) + } + if lease.MaxClockSkewNS != int64(4*time.Second) { + t.Fatal("configured margin not in durable grant", lease) + } + boundary := start.Add(10 * time.Second) + if restart { + now = start.Add(7 * time.Second) + p = NewPublisher(nil, WithStore(disk), WithWorkspaceLeaseConfig(6*time.Second, func() time.Time { return now }), WithWorkspaceMaxClockSkew(time.Second)) + boundary = now.Add(6*time.Second + 4*time.Second) + } + q := WorkspaceMoveRequest{RequestID: "m", VolumeID: "v", ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "old", TargetHost: "new", ExpectedEpoch: 1, TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "forced", Force: true} + head := WorkspaceHead{Gen: 7, Epoch: 1, Holder: "old/r"} + now = boundary.Add(-time.Nanosecond) + if _, err := p.MoveWorkspace(context.Background(), q, head); err == nil { + t.Fatal("forced before skew boundary") + } + if len(p.WorkspaceState("v").Moves) != 0 { + t.Fatal("early move wrote journal") + } + now = boundary + if _, err := p.MoveWorkspace(context.Background(), q, head); err != nil { + t.Fatal("margin elapsed", err) + } + }) + } +} diff --git a/seaweed-block/core/authority/workspace_test.go b/seaweed-block/core/authority/workspace_test.go index 680cb68526..4873446164 100644 --- a/seaweed-block/core/authority/workspace_test.go +++ b/seaweed-block/core/authority/workspace_test.go @@ -70,6 +70,10 @@ func TestWorkspaceCrashAfterJournalBeforeEpochResumesSameGrant(t *testing.T) { if len(state.Moves) != 1 || state.Moves[0].Issued || state.Moves[0].NewEpoch != 2 { t.Fatalf("grant not durable before epoch: %+v", state) } + if _, err := loaded.MoveWorkspace(context.Background(), req, head); err == nil { + t.Fatal("restart resumed forced reservation before conservative skew barrier") + } + now = now.Add(2 * time.Second) r, err := loaded.MoveWorkspace(context.Background(), req, head) if err != nil { t.Fatal(err) diff --git a/seaweed-block/core/host/bootstrap/bootstrap.go b/seaweed-block/core/host/bootstrap/bootstrap.go index 19e6a32dcb..251941722b 100644 --- a/seaweed-block/core/host/bootstrap/bootstrap.go +++ b/seaweed-block/core/host/bootstrap/bootstrap.go @@ -3,6 +3,7 @@ package bootstrap import ( "fmt" "log" + "time" "github.com/seaweedfs/seaweed-block/core/authority" ) @@ -14,14 +15,14 @@ import ( // reload capability existed only in unit tests. // // Startup order matches sketch §7: -// 1. acquire the single-owner store lock (refuse to start if held) -// 2. open the file-per-volume store under the same directory -// 3. construct the Publisher with WithStore(store), which runs -// reload synchronously — surviving records populate -// Publisher state, corrupt records go to LoadErrors() -// 4. log any LoadErrors() at startup so operators see -// reload-corruption events rather than having them stranded -// inside the Publisher +// 1. acquire the single-owner store lock (refuse to start if held) +// 2. open the file-per-volume store under the same directory +// 3. construct the Publisher with WithStore(store), which runs +// reload synchronously — surviving records populate +// Publisher state, corrupt records go to LoadErrors() +// 4. log any LoadErrors() at startup so operators see +// reload-corruption events rather than having them stranded +// inside the Publisher // // The caller owns lifecycle: invoke Close() on process exit (or // via defer) to release the lock and close the store cleanly. @@ -43,8 +44,9 @@ type DurableAuthorityBootstrap struct { // Options customizes durable-authority bootstrap wiring. type Options struct { - PublishObserver authority.PublishObserver - PublicationAdmission authority.PublicationAdmission + WorkspaceMaxClockSkew time.Duration + PublishObserver authority.PublishObserver + PublicationAdmission authority.PublicationAdmission } // Bootstrap performs the durable-authority startup sequence and @@ -53,9 +55,10 @@ type Options struct { // acquired or the store directory cannot be enumerated. // // Startup logs: -// "durable authority lock acquired" -// "durable authority reload: N records" -// "durable authority reload skip: %v" (one per skip) +// +// "durable authority lock acquired" +// "durable authority reload: N records" +// "durable authority reload skip: %v" (one per skip) // // The logs are the promised operator/startup visibility of // LoadErrors() — architect round-5 finding #3. @@ -117,7 +120,7 @@ func bootstrapFromStoreLocked(storeDir string, lock *authority.StoreLock, store if opts.PublishObserver != nil { pubOpts = append(pubOpts, authority.WithPublishObserver(opts.PublishObserver)) } - pubOpts = append(pubOpts, authority.WithPublicationAdmission(opts.PublicationAdmission)) + pubOpts = append(pubOpts, authority.WithPublicationAdmission(opts.PublicationAdmission), authority.WithWorkspaceMaxClockSkew(opts.WorkspaceMaxClockSkew)) pub := authority.NewPublisher(directive, pubOpts...) // Publisher's LoadErrors is the canonical source; prefer it diff --git a/seaweed-block/core/host/master/host.go b/seaweed-block/core/host/master/host.go index 077d3bd3c9..f74dbfae99 100644 --- a/seaweed-block/core/host/master/host.go +++ b/seaweed-block/core/host/master/host.go @@ -24,6 +24,7 @@ import ( "path/filepath" "sync" "sync/atomic" + "time" "github.com/seaweedfs/seaweed-block/core/authority" "github.com/seaweedfs/seaweed-block/core/host/bootstrap" @@ -67,8 +68,9 @@ type Config struct { // WorkspaceRPC enables the RF1 lease/revoke/move surface. HEAD must be // obtained from the configured remote source, never from operator flags. - WorkspaceRPC bool - WorkspaceHeadReader func(context.Context, string) (authority.WorkspaceHead, error) + WorkspaceMaxClockSkew time.Duration + WorkspaceRPC bool + WorkspaceHeadReader func(context.Context, string) (authority.WorkspaceHead, error) // FrontendPublicationRuntimeHTTP enables the frontend publication runtime // HTTP surface. It is disabled by default and only confirms a post-failback @@ -170,6 +172,9 @@ func (h *publisherHolder) VolumeAuthorityLine(vid string) (authority.AuthorityBa // // Live loops (publisher.Run, host.Start, grpc.Serve) run in Start. func New(cfg Config) (*Host, error) { + if cfg.WorkspaceMaxClockSkew < 0 || cfg.WorkspaceMaxClockSkew >= 60*time.Second { + return nil, fmt.Errorf("master.New: workspace max clock skew must be positive and less than 60s (zero selects default)") + } if cfg.WorkspaceRPC && (cfg.WorkspaceHeadReader == nil || cfg.LifecycleStoreDir == "") { return nil, fmt.Errorf("master.New: workspace RPC requires HEAD reader and lifecycle store") } @@ -208,8 +213,9 @@ func New(cfg Config) (*Host, error) { } boot, err := bootstrap.BootstrapWithOptions(cfg.AuthorityStoreDir, ctrl, bootstrap.Options{ - PublishObserver: h.recordAuthorityPublishedEvent, - PublicationAdmission: h.admitWorkspacePublication, + WorkspaceMaxClockSkew: cfg.WorkspaceMaxClockSkew, + PublishObserver: h.recordAuthorityPublishedEvent, + PublicationAdmission: h.admitWorkspacePublication, }) if err != nil { return nil, fmt.Errorf("master.New: Bootstrap: %w", err) diff --git a/seaweed-block/core/host/master/workspace_binding_test.go b/seaweed-block/core/host/master/workspace_binding_test.go index 18bf59ba89..87f73e1b1d 100644 --- a/seaweed-block/core/host/master/workspace_binding_test.go +++ b/seaweed-block/core/host/master/workspace_binding_test.go @@ -73,7 +73,7 @@ func TestWorkspaceBindingsForcedRetiresOnlyAfterIssue(t *testing.T) { } func workspaceBindingsMove(t *testing.T, forced bool) { - cfg := Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) { + cfg := Config{WorkspaceMaxClockSkew: 100 * time.Millisecond, Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) { return authority.WorkspaceHead{Gen: 9, Epoch: 1, Holder: "node-a/r1", RemoteLSN: 42, Detached: true}, nil }} h, err := New(cfg) @@ -127,7 +127,7 @@ func workspaceBindingsMove(t *testing.T, forced bool) { } if forced { select { - case <-time.After(time.Until(time.Unix(0, lease.ExpiresAtNs)) + 20*time.Millisecond): + case <-time.After(time.Until(time.Unix(0, lease.ExpiresAtNs)) + 100*time.Millisecond + 20*time.Millisecond): case <-ctx.Done(): t.Fatal(ctx.Err()) } diff --git a/seaweed-block/core/host/master/workspace_move_integration_test.go b/seaweed-block/core/host/master/workspace_move_integration_test.go index b6d1dfa5dd..63bb0a3a32 100644 --- a/seaweed-block/core/host/master/workspace_move_integration_test.go +++ b/seaweed-block/core/host/master/workspace_move_integration_test.go @@ -57,7 +57,7 @@ func TestIntegrationWorkspaceProductionDetachAndForcedMove(t *testing.T) { if err != nil { t.Fatal(err) } - h, err := New(Config{AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), Listen: "127.0.0.1:0", WorkspaceRPC: true, WorkspaceHeadReader: reader}) + h, err := New(Config{WorkspaceMaxClockSkew: 100 * time.Millisecond, AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), Listen: "127.0.0.1:0", WorkspaceRPC: true, WorkspaceHeadReader: reader}) if err != nil { t.Fatal(err) } @@ -169,7 +169,7 @@ func TestIntegrationWorkspaceProductionDetachAndForcedMove(t *testing.T) { } } else { // Actual master lease expiry, no test clock and no revocation ACK. - timer := time.NewTimer(time.Until(time.Unix(0, lease.ExpiresAtNs)) + 20*time.Millisecond) + timer := time.NewTimer(time.Until(time.Unix(0, lease.ExpiresAtNs)) + 100*time.Millisecond + 20*time.Millisecond) defer timer.Stop() select { case <-timer.C: diff --git a/seaweed-block/core/host/master/workspace_service.go b/seaweed-block/core/host/master/workspace_service.go index f1e17f69a3..0a4da5644a 100644 --- a/seaweed-block/core/host/master/workspace_service.go +++ b/seaweed-block/core/host/master/workspace_service.go @@ -43,8 +43,14 @@ func workspaceError(err error) error { func leaseFact(volume string, l authority.WorkspaceLease) *control.WorkspaceLeaseFact { // Client anchors this duration to its request START, not response arrival. + // The host fences half a skew bound before the stored master expiry. // Never grant more than the server's configured 30s TTL after a restart. - remaining := time.Until(time.Unix(0, l.ExpiresAtNS)) + skew := time.Duration(l.MaxClockSkewNS) + // Older persisted leases predate the bound; use the production default. + if skew <= 0 { + skew = 20 * time.Second + } + remaining := time.Until(time.Unix(0, l.ExpiresAtNS).Add(-skew / 2)) if remaining > 30*time.Second { remaining = 30 * time.Second } diff --git a/seaweed-block/core/host/master/workspace_skew_test.go b/seaweed-block/core/host/master/workspace_skew_test.go new file mode 100644 index 0000000000..5bb525ae6e --- /dev/null +++ b/seaweed-block/core/host/master/workspace_skew_test.go @@ -0,0 +1,112 @@ +package master + +import ( + "context" + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/host/volume" + "github.com/seaweedfs/seaweed-block/core/lifecycle" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" + "testing" + "time" +) + +type skewLeaseClient struct{ p *authority.Publisher } + +func (c skewLeaseClient) RenewWorkspaceLease(ctx context.Context, id *control.WorkspaceIdentity, _ ...grpc.CallOption) (*control.WorkspaceLeaseFact, error) { + l, err := c.p.RenewWorkspaceLease(ctx, id.VolumeId, id.ReplicaId, id.Epoch) + if err != nil { + return nil, err + } + return leaseFact(id.VolumeId, l), nil +} +func (skewLeaseClient) AckWorkspaceRevoked(context.Context, *control.WorkspaceRevocationAck, ...grpc.CallOption) (*control.WorkspaceEmpty, error) { + panic("expiry must not ACK clean") +} + +func TestWorkspaceSkewSeparatesOldServingFromForcedGrant(t *testing.T) { + for _, check := range []string{"master-margin", "host-early-fence"} { + t.Run(check, func(t *testing.T) { + store, err := authority.NewFileAuthorityStore(t.TempDir()) + if err != nil { + t.Fatal(err) + } + defer store.Close() + if err := store.Put(authority.DurableRecord{VolumeID: "v", ReplicaID: "r", Epoch: 1, EndpointVersion: 1, DataAddr: "d", CtrlAddr: "c", WriteSeq: 1}); err != nil { + t.Fatal(err) + } + start := time.Now() + masterNow, hostNow := start, start + p := authority.NewPublisher(nil, authority.WithStore(store), authority.WithWorkspaceLeaseConfig(3*time.Second, func() time.Time { return masterNow })) + g, err := volume.NewWorkspaceLeaseGuard(workspaceRPCView{frontend.Projection{VolumeID: "v", ReplicaID: "r", Epoch: 1, Healthy: true}}, skewLeaseClient{p}, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 1}, func(context.Context) (uint64, error) { return 7, nil }, func() time.Time { return hostNow }) + if err != nil { + t.Fatal(err) + } + if err := g.Refresh(context.Background()); err != nil { + t.Fatal(err) + } + lease := p.WorkspaceState("v").Lease + q := authority.WorkspaceMoveRequest{RequestID: "forced", VolumeID: "v", ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "old", TargetHost: "new", ExpectedEpoch: 1, TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "forced", Force: true} + head := authority.WorkspaceHead{Gen: 7, Epoch: 1, Holder: "old/r", RemoteLSN: 42} + if check == "host-early-fence" { + // Default skew is two nominal TTL/3 renewal intervals; host stops half that early. + hostNow = start.Add(2 * time.Second) + if g.Projection().Healthy { + t.Fatal("old host serves past expiry minus half-skew") + } + } else { + // Master advanced one tick farther than the old host since renewal. + masterNow = time.Unix(0, lease.ExpiresAtNS) + hostNow = start.Add(2900 * time.Millisecond) + if _, err := p.MoveWorkspace(context.Background(), q, head); err == nil { + t.Fatalf("forced grant before skew margin; old serving=%v", g.Projection().Healthy) + } + line, _ := p.VolumeAuthorityLine("v") + if line.Epoch != 1 || len(p.WorkspaceState("v").Moves) != 0 { + t.Fatal("early refusal changed authority/journal") + } + } + masterNow = time.Unix(0, lease.ExpiresAtNS).Add(2 * time.Second) + hostNow = start.Add(4 * time.Second) + grant, err := p.MoveWorkspace(context.Background(), q, head) + if err != nil { + t.Fatal(err) + } + if !grant.Issued || grant.NewEpoch <= 1 || g.Projection().Healthy { + t.Fatal("overlapping old serving at new grant", grant) + } + }) + } +} + +func TestWorkspaceClockSkewConfigReachesLeaseReply(t *testing.T) { + dir := t.TempDir() + store, err := authority.NewFileAuthorityStore(dir) + if err != nil { + t.Fatal(err) + } + if err := store.Put(authority.DurableRecord{VolumeID: "v", ReplicaID: "r", Epoch: 1, EndpointVersion: 1, DataAddr: "d", CtrlAddr: "c", WriteSeq: 1}); err != nil { + t.Fatal(err) + } + if err := store.Close(); err != nil { + t.Fatal(err) + } + h, err := New(Config{AuthorityStoreDir: dir, LifecycleStoreDir: t.TempDir(), Listen: "127.0.0.1:0", WorkspaceRPC: true, WorkspaceMaxClockSkew: 4 * time.Second, WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) { return authority.WorkspaceHead{}, nil }}) + if err != nil { + t.Fatal(err) + } + h.Start() + defer closeTestMaster(t, h) + if _, err := h.Lifecycle().Volumes.CreateVolume(lifecycle.VolumeSpec{VolumeID: "v", SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil { + t.Fatal(err) + } + reply, err := (&services{host: h}).RenewWorkspaceLease(context.Background(), &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 1}) + if err != nil { + t.Fatal(err) + } + lease := h.Publisher().WorkspaceState("v").Lease + if lease.MaxClockSkewNS != int64(4*time.Second) || reply.ValidForNs <= 0 || reply.ValidForNs > int64(28*time.Second) { + t.Fatal("configuration not applied to host validity", lease, reply) + } +} diff --git a/seaweed-block/core/host/volume/workspace_lease.go b/seaweed-block/core/host/volume/workspace_lease.go index abd44e93c7..dad21b65fb 100644 --- a/seaweed-block/core/host/volume/workspace_lease.go +++ b/seaweed-block/core/host/volume/workspace_lease.go @@ -65,6 +65,8 @@ func (g *WorkspaceLeaseGuard) permits(p frontend.Projection) bool { // Refresh anchors validity to the request START. Reply latency can only shorten // the client's usable lease, never extend it past the master's grant window. +// ValidForNs already excludes half the master-configured clock-skew margin; +// until is the early self-fence deadline, not the raw ExpiresAtNs wall clock. func (g *WorkspaceLeaseGuard) Refresh(ctx context.Context) error { g.operation.Lock() defer g.operation.Unlock() diff --git a/seaweed-block/docs/workspace-lease.md b/seaweed-block/docs/workspace-lease.md index 9bff856787..e310ecbda9 100644 --- a/seaweed-block/docs/workspace-lease.md +++ b/seaweed-block/docs/workspace-lease.md @@ -28,3 +28,16 @@ for its result before ACK. Host shutdown fences admission synchronously. The host installation mutex latches this terminal fence even before a guard exists; a later-installed guard is born fenced. Its lock order is installation mutex then guard state mutex. Canceled renewal replies cannot publish a grant. + +## Clock skew + +`blockmaster --workspace-max-clock-skew` defaults to 20s (two nominal 10s +renewal intervals for the 30s lease). Set a positive bound below 60s that +covers the deployment's clock drift. The bound is persisted with each lease; +a restart or smaller setting cannot shorten an outstanding grant's bound. +The master grants a FORCED move only after both the stored expiry and its +conservative restart deadline plus the full bound. `ValidForNs` in lease +replies excludes half the bound. Hosts anchor that shortened duration to +request start, self-fencing early without comparing remote wall-clock times. +Delayed replies cannot extend admission. The bound is an operational clock +assumption; arbitrarily stopped or unbounded clocks are not covered. From dae0bb90723af0a1b15e9226df35b2f71c325534 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 23:32:51 -0800 Subject: [PATCH 08/16] test: seed skew controls through authority publication --- .../core/host/master/workspace_skew_test.go | 74 ++++++++++++++----- 1 file changed, 54 insertions(+), 20 deletions(-) diff --git a/seaweed-block/core/host/master/workspace_skew_test.go b/seaweed-block/core/host/master/workspace_skew_test.go index 5bb525ae6e..530294eeea 100644 --- a/seaweed-block/core/host/master/workspace_skew_test.go +++ b/seaweed-block/core/host/master/workspace_skew_test.go @@ -32,13 +32,17 @@ func TestWorkspaceSkewSeparatesOldServingFromForcedGrant(t *testing.T) { if err != nil { t.Fatal(err) } - defer store.Close() - if err := store.Put(authority.DurableRecord{VolumeID: "v", ReplicaID: "r", Epoch: 1, EndpointVersion: 1, DataAddr: "d", CtrlAddr: "c", WriteSeq: 1}); err != nil { - t.Fatal(err) - } + t.Cleanup(func() { + if err := store.Close(); err != nil { + t.Error(err) + } + }) + start := time.Now() masterNow, hostNow := start, start - p := authority.NewPublisher(nil, authority.WithStore(store), authority.WithWorkspaceLeaseConfig(3*time.Second, func() time.Time { return masterNow })) + dir := &skewDirective{asks: make(chan authority.AssignmentAsk, 1)} + p := authority.NewPublisher(dir, authority.WithStore(store), authority.WithWorkspaceLeaseConfig(3*time.Second, func() time.Time { return masterNow })) + seedSkewPublisher(t, p, dir) g, err := volume.NewWorkspaceLeaseGuard(workspaceRPCView{frontend.Projection{VolumeID: "v", ReplicaID: "r", Epoch: 1, Healthy: true}}, skewLeaseClient{p}, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 1}, func(context.Context) (uint64, error) { return 7, nil }, func() time.Time { return hostNow }) if err != nil { t.Fatal(err) @@ -80,32 +84,62 @@ func TestWorkspaceSkewSeparatesOldServingFromForcedGrant(t *testing.T) { } } +type skewDirective struct{ asks chan authority.AssignmentAsk } + +func (d *skewDirective) Next(ctx context.Context) (authority.AssignmentAsk, error) { + select { + case a := <-d.asks: + return a, nil + case <-ctx.Done(): + return authority.AssignmentAsk{}, ctx.Err() + } +} +func seedSkewPublisher(t *testing.T, p *authority.Publisher, d *skewDirective) { + t.Helper() + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan error, 1) + go func() { done <- p.Run(ctx) }() + t.Cleanup(func() { + cancel() + select { + case <-done: + case <-time.After(3 * time.Second): + t.Error("publisher unsettled") + } + }) + ch, unsub := p.Subscribe("v", "r") + defer unsub() + d.asks <- authority.AssignmentAsk{VolumeID: "v", ReplicaID: "r", DataAddr: "d", CtrlAddr: "c", Intent: authority.IntentBind} + select { + case info := <-ch: + if info.Epoch != 1 { + t.Fatal(info) + } + case <-time.After(3 * time.Second): + t.Fatal("initial authority not published") + } +} + func TestWorkspaceClockSkewConfigReachesLeaseReply(t *testing.T) { - dir := t.TempDir() - store, err := authority.NewFileAuthorityStore(dir) - if err != nil { - t.Fatal(err) - } - if err := store.Put(authority.DurableRecord{VolumeID: "v", ReplicaID: "r", Epoch: 1, EndpointVersion: 1, DataAddr: "d", CtrlAddr: "c", WriteSeq: 1}); err != nil { - t.Fatal(err) - } - if err := store.Close(); err != nil { - t.Fatal(err) - } - h, err := New(Config{AuthorityStoreDir: dir, LifecycleStoreDir: t.TempDir(), Listen: "127.0.0.1:0", WorkspaceRPC: true, WorkspaceMaxClockSkew: 4 * time.Second, WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) { return authority.WorkspaceHead{}, nil }}) + h, err := New(Config{AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), Listen: "127.0.0.1:0", WorkspaceRPC: true, WorkspaceMaxClockSkew: 4 * time.Second, WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) { return authority.WorkspaceHead{}, nil }}) if err != nil { t.Fatal(err) } h.Start() defer closeTestMaster(t, h) - if _, err := h.Lifecycle().Volumes.CreateVolume(lifecycle.VolumeSpec{VolumeID: "v", SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil { + if _, err := h.Lifecycle().Volumes.CreateVolume(lifecycle.VolumeSpec{VolumeID: "vol-a", SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil { t.Fatal(err) } - reply, err := (&services{host: h}).RenewWorkspaceLease(context.Background(), &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 1}) + seedVerifiedExistingReplicaPlacement(t, h) + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatal(err) + } + line := waitAuthorityLine(t, h.Publisher(), "vol-a") + reply, err := (&services{host: h}).RenewWorkspaceLease(context.Background(), &control.WorkspaceIdentity{VolumeId: "vol-a", ReplicaId: line.ReplicaID, Epoch: line.Epoch}) if err != nil { t.Fatal(err) } - lease := h.Publisher().WorkspaceState("v").Lease + lease := h.Publisher().WorkspaceState("vol-a").Lease if lease.MaxClockSkewNS != int64(4*time.Second) || reply.ValidForNs <= 0 || reply.ValidForNs > int64(28*time.Second) { t.Fatal("configuration not applied to host validity", lease, reply) } From 99e281d153d0b1b236a650407bfd0c1664850d2e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 23:37:14 -0800 Subject: [PATCH 09/16] storage: RED: the WAL writer reuses bytes the persisted tail retains claude05's ruling on the S3 torn-wrap finding (2026-11-16 07:33Z): the writer may only overwrite bytes that the PERSISTED superblock tail has released. On main the flusher persists the pre-advance tail and the in-memory tail moves after it, and Recover moves the writer's bounds without persisting them, so a torn new record can land inside the persisted [tail, head) and hide a synced record behind it. - flusher.afterSnapshotForTest: a test-only hook in the window after the dirty-map snapshot (an append there is covered by the persisted head but not by the checkpoint). - TestWALStoreAppendDuringFlushThenTornWrapKeepsSyncedRecords: the S3 trace, deterministic; crash only; synced LSN 2 is lost on main. - TestWALStoreFlushPersistsTheReleasedTail, TestWALStoreRecoverPersists- TheRecoveredBounds: the on-disk tail lags the writer's. - TestWALWriterReuseIsBoundedByTheDurableTail: an in-memory release makes its bytes reusable at once. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/flusher.go | 8 + .../storage/walstore_persisted_tail_test.go | 206 ++++++++++++++++++ 2 files changed, 214 insertions(+) create mode 100644 seaweed-block/core/storage/walstore_persisted_tail_test.go diff --git a/seaweed-block/core/storage/flusher.go b/seaweed-block/core/storage/flusher.go index aa59bcc924..7935dc6371 100644 --- a/seaweed-block/core/storage/flusher.go +++ b/seaweed-block/core/storage/flusher.go @@ -51,6 +51,11 @@ type flusher struct { flushes atomic.Uint64 // diagnostic bytesOut atomic.Uint64 // diagnostic instr flusherInstrumentation + + // afterSnapshotForTest, when set, runs after the dirty-map snapshot is + // taken and the publication lock released: the window in which a + // concurrent append is not in this cycle's checkpoint. Tests only. + afterSnapshotForTest func() } type flusherConfig struct { @@ -164,6 +169,9 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) { if len(entries) == 0 { return nil } + if f.afterSnapshotForTest != nil { + f.afterSnapshotForTest() + } finishCycle := f.instr.recordCycle( cycleStart, time.Since(snapshotStart), entries, store.sb.BlockSize, ) diff --git a/seaweed-block/core/storage/walstore_persisted_tail_test.go b/seaweed-block/core/storage/walstore_persisted_tail_test.go new file mode 100644 index 0000000000..70838d2ca4 --- /dev/null +++ b/seaweed-block/core/storage/walstore_persisted_tail_test.go @@ -0,0 +1,206 @@ +package storage + +import ( + "errors" + "os" + "path/filepath" + "testing" +) + +// The WAL writer may only overwrite bytes that the PERSISTED superblock tail +// has released (claude05's ruling on the S3 torn-wrap finding, 2026-11-16 +// 07:33Z). Otherwise a torn new record can land inside the persisted +// [tail, head) and stop recovery's scan before a synced record behind it. + +func diskSuperblockForTest(t *testing.T, path string) superblock { + t.Helper() + f, err := os.Open(path) + if err != nil { + t.Fatal(err) + } + defer f.Close() + sb, err := readSuperblock(f) + if err != nil { + t.Fatal(err) + } + return sb +} + +// The S3 trace, deterministic: LSN 2 is appended (and synced) while the +// flush of LSN 1 runs, so the checkpoint covers LSN 1 and the persisted head +// covers LSN 2. Synced LSN 3..5 follow; an unsynced LSN 6 wraps to offset 0 +// over the released LSN 1. The crash leaves LSN 6 torn and its end padding +// not on disk (both unsynced pages: a plain crash, no corruption). Synced +// LSN 2..5 must all be recovered. +func TestWALStoreAppendDuringFlushThenTornWrapKeepsSyncedRecords(t *testing.T) { + const ( + blockSize = 4096 + walSize = 24 * 1024 + ) + S := uint64(walEntryHeaderSize + blockSize) + path := filepath.Join(t.TempDir(), "store.bin") + s := createWALStoreWithWALSizeForTest(t, path, 64, blockSize, walSize) + s.DisableAutoFlushForRecoveryTest() + if _, err := s.Write(0, makeBlock(blockSize, 0x10)); err != nil { // LSN 1 + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + s.flusher.afterSnapshotForTest = func() { + s.flusher.afterSnapshotForTest = nil + if _, err := s.Write(1, makeBlock(blockSize, 0x11)); err != nil { // LSN 2, not in this flush + t.Error(err) + } + if _, err := s.Sync(); err != nil { + t.Error(err) + } + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + if sb := diskSuperblockForTest(t, path); sb.WALCheckpointLSN != 1 || sb.WALHead != 2*S { + t.Fatalf("persisted ckpt=%d head=%d; want the flush of LSN 1 to cover LSN 2 in its head (2S=%d)", sb.WALCheckpointLSN, sb.WALHead, 2*S) + } + for lba := uint32(2); lba <= 4; lba++ { // LSN 3..5, synced + 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.Write(5, makeBlock(blockSize, 0x66)); err != nil { // LSN 6, unsynced, wraps + t.Fatal(err) + } + ents := recoverySnapshotEntriesByLBA(s.dm.snapshot()) + if ents[5].WALOffset != 0 || ents[1].WALOffset != S { + t.Fatalf("layout: LSN 6 at %d, LSN 2 at %d; want 0 and S", ents[5].WALOffset, ents[1].WALOffset) + } + walOff := s.sb.WALOffset + if _, err := s.fd.WriteAt(make([]byte, walSize-5*S), int64(walOff+5*S)); err != nil { // padding not on disk + t.Fatal(err) + } + if _, err := s.fd.WriteAt(make([]byte, blockSize/2), int64(walOff+S-blockSize/2)); err != nil { // LSN 6 torn + t.Fatal(err) + } + crashRecoveryHardeningStore(t, s) + r, err := OpenWALStore(path) + if err != nil { + t.Fatal(err) + } + r.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = r.Close() }) + if _, err := r.Recover(); err != nil { + t.Fatalf("Recover: %v", err) + } + for lba := uint32(1); lba <= 4; lba++ { + assertRecoveryHardeningBlock(t, r, lba, makeBlock(blockSize, byte(0x10+lba))) + } +} + +// A flush persists the tail it releases: the on-disk tail equals the +// writer's tail after every checkpoint, and head/tail come from one snapshot. +func TestWALStoreFlushPersistsTheReleasedTail(t *testing.T) { + const blockSize = 4096 + path := filepath.Join(t.TempDir(), "store.bin") + s := createWALStoreWithWALSizeForTest(t, path, 64, blockSize, 24*1024) + s.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = s.Close() }) + for round := 0; round < 3; round++ { + for lba := uint32(0); lba < 2; lba++ { + if _, err := s.Write(lba, makeBlock(blockSize, byte(0x20+round))); err != nil { + t.Fatal(err) + } + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + sb := diskSuperblockForTest(t, path) + if tail, head := s.wal.logicalTailValue(), s.wal.logicalHeadValue(); sb.WALTail != tail || sb.WALHead != head { + t.Fatalf("round %d: persisted tail=%d head=%d, writer tail=%d head=%d; the writer may reuse bytes the persisted tail still retains", round, sb.WALTail, sb.WALHead, tail, head) + } + } +} + +// Recovery that moves the writer's bounds persists them before any append, +// so the writer never reuses bytes the on-disk superblock still declares +// retained. +func TestWALStoreRecoverPersistsTheRecoveredBounds(t *testing.T) { + const blockSize = 4096 + path := filepath.Join(t.TempDir(), "store.bin") + s := createWALStoreWithWALSizeForTest(t, path, 64, blockSize, 24*1024) + s.DisableAutoFlushForRecoveryTest() + if _, err := s.Write(0, makeBlock(blockSize, 0x30)); err != nil { // LSN 1 + 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(1, makeBlock(blockSize, 0x31)); err != nil { // LSN 2, synced, unflushed + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + // the superblock as an older flush left it: ckpt 1, tail before LSN 1 + sb := *s.sb + sb.WALCheckpointLSN, sb.WALTail, sb.WALHead = 1, 0, uint64(walEntryHeaderSize+blockSize) + 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) + } + crashRecoveryHardeningStore(t, s) + r, err := OpenWALStore(path) + if err != nil { + t.Fatal(err) + } + r.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = r.Close() }) + if _, err := r.Recover(); err != nil { + t.Fatal(err) + } + disk := diskSuperblockForTest(t, path) + if tail, head := r.wal.logicalTailValue(), r.wal.logicalHeadValue(); disk.WALTail != tail || disk.WALHead != head { + t.Fatalf("after Recover: persisted tail=%d head=%d, writer tail=%d head=%d; want the recovered bounds persisted", disk.WALTail, disk.WALHead, tail, head) + } + assertRecoveryHardeningBlock(t, r, 1, makeBlock(blockSize, 0x31)) +} + +// The writer's space check uses the durable tail: an in-memory release that +// is not yet persisted does not make its bytes reusable. +func TestWALWriterReuseIsBoundedByTheDurableTail(t *testing.T) { + f, err := os.CreateTemp(t.TempDir(), "wal") + if err != nil { + t.Fatal(err) + } + defer f.Close() + const walSize = 4096 + entry := func() *walEntry { + return &walEntry{LSN: 1, Type: walEntryWrite, LBA: 0, Length: 64, Data: make([]byte, 64)} + } + size, err := entry().encodedSize() + if err != nil { + t.Fatal(err) + } + n := uint64(walSize) / uint64(size) + w := newWALWriter(f, 0, walSize, 0, 0, nil) + for i := uint64(0); i < n; i++ { + if _, err := w.append(entry()); err != nil { + t.Fatalf("append %d of %d: %v", i, n, err) + } + } + w.advanceTailPastEntry(0, uint64(size)) // released in memory only + if _, err := w.append(entry()); !errors.Is(err, errWALFull) { + t.Fatalf("append into bytes released only in memory: err=%v; want errWALFull until the tail is persisted", err) + } +} From 88fbb345b010aa39c83b43507452077172ab5d6d Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 23:39:27 -0800 Subject: [PATCH 10/16] storage: reuse only WAL bytes the persisted tail released claude05's ruling on the S3 torn-wrap finding (2026-11-16 07:33Z), root fix: the WAL writer may only overwrite bytes released by the PERSISTED superblock tail, so a torn new record can never land inside the persisted [tail, head) and hide a synced record behind it (crash only, no corruption). - walWriter.durableTail: the tail of the last fsynced superblock. The space checks (append, appendBatch planning, admission pressure) count from it; a release made only in memory frees nothing. Bounds rebuilt by recovery are not reusable until persisted. - The flusher's checkpoint persists the tail it releases (the old code persisted the pre-advance tail and advanced after), with head and tail taken from one writer snapshot. A flush whose checkpoint is already covered (direct frontier) still persists its tail release. - Recover persists the rebuilt head/tail before any append when they differ from the on-disk superblock. The replay-side defense (resync past a bad entry, replay by LSN up to the first gap) is #156. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/flusher.go | 5 +- seaweed-block/core/storage/wal_writer.go | 76 ++++++++++++++++++++-- seaweed-block/core/storage/walstore.go | 80 +++++++++++++++++++----- 3 files changed, 137 insertions(+), 24 deletions(-) diff --git a/seaweed-block/core/storage/flusher.go b/seaweed-block/core/storage/flusher.go index 7935dc6371..ea78ae918c 100644 --- a/seaweed-block/core/storage/flusher.go +++ b/seaweed-block/core/storage/flusher.go @@ -228,11 +228,12 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) { // with LSN <= maxLSN is in extent or superseded by a retained newer // WAL record. Concurrent writes remain dirty for the next cycle. if maxLSN > 0 { - if err := store.persistCheckpoint(maxLSN); err != nil { + // The released tail is persisted with the checkpoint, before the + // writer may reuse those bytes. + if err := store.persistCheckpointAndRelease(maxLSN, maxLSNPhys, maxLSNEntrySize); err != nil { return fmt.Errorf("flusher: persist checkpoint %d: %w", maxLSN, err) } if store.CheckpointLSN() >= maxLSN { - store.wal.advanceTailPastEntry(maxLSNPhys, maxLSNEntrySize) store.mu.Lock() if maxLSN+1 > store.walTail { store.walTail = maxLSN + 1 diff --git a/seaweed-block/core/storage/wal_writer.go b/seaweed-block/core/storage/wal_writer.go index 97ecdc2ef6..e322daae8c 100644 --- a/seaweed-block/core/storage/wal_writer.go +++ b/seaweed-block/core/storage/wal_writer.go @@ -31,7 +31,16 @@ type walWriter struct { walSize uint64 // size of the WAL region in bytes logicalHead uint64 // monotonic write position logicalTail uint64 // monotonic flush position - instr *writeInstrumentation + // durableTail is the tail in the last fsynced superblock. The writer + // overwrites only bytes released by it (claude05's S3 ruling, + // 2026-11-16): bytes the on-disk superblock still declares retained + // are never reused, so a torn new record cannot land inside the + // persisted [tail, head) and hide a record recovery needs. + // durablePending: the bounds were rebuilt by recovery and are not yet + // persisted; nothing is reusable until they are. + durableTail uint64 + durablePending bool + instr *writeInstrumentation // Optional batch pwrite fault seam; nil uses the real file. batchWriteAt func([]byte, int64) (int, error) @@ -47,6 +56,7 @@ func newWALWriter(fd *os.File, walOffset, walSize, head, tail uint64, instr *wri walSize: walSize, logicalHead: head, logicalTail: tail, + durableTail: tail, instr: instr, } } @@ -55,6 +65,15 @@ func (w *walWriter) physicalPos(logical uint64) uint64 { return logical % w.walS func (w *walWriter) used() uint64 { return w.logicalHead - w.logicalTail } +// spaceUsed is what the space checks count: everything from the durable +// tail on. Bytes released only in memory are not reusable yet. +func (w *walWriter) spaceUsed() uint64 { + if w.durablePending || w.durableTail > w.logicalHead { + return w.walSize + } + return w.logicalHead - w.durableTail +} + // append writes one entry and returns the WAL-relative offset where // it was placed. If the entry would straddle the end of the WAL // region, a padding entry is written first and the real entry starts @@ -83,7 +102,7 @@ func (w *walWriter) append(entry *walEntry) (walRelOffset uint64, err error) { remaining := w.walSize - physHead if remaining < entryLen { // Pad to end of region and wrap. - if w.used()+remaining+entryLen > w.walSize { + if w.spaceUsed()+remaining+entryLen > w.walSize { return 0, errWALFull } if err := w.writePadding(remaining, physHead); err != nil { @@ -95,7 +114,7 @@ func (w *walWriter) append(entry *walEntry) (walRelOffset uint64, err error) { w.logicalHead += remaining physHead = 0 } - if w.used()+entryLen > w.walSize { + if w.spaceUsed()+entryLen > w.walSize { return 0, errWALFull } absOffset := int64(w.walOffset + physHead) @@ -253,7 +272,12 @@ func boundedPendingCapacity(lengths []uint64) int { func (w *walWriter) planAppendBatchLengths(lengths []uint64) ([]uint64, uint64, error) { localHead := w.logicalHead offsets := make([]uint64, 0, len(lengths)) - used := func() uint64 { return localHead - w.logicalTail } + used := func() uint64 { + if w.durablePending || w.durableTail > localHead { + return w.walSize + } + return localHead - w.durableTail + } for _, entryLen := range lengths { physHead := w.physicalPos(localHead) remaining := w.walSize - physHead @@ -368,6 +392,8 @@ func (w *walWriter) reset() { defer w.mu.Unlock() w.logicalHead = 0 w.logicalTail = 0 + w.durableTail = 0 + w.durablePending = false } func (w *walWriter) restoreRecoveredBounds(head, tail uint64) error { @@ -381,9 +407,49 @@ func (w *walWriter) restoreRecoveredBounds(head, tail uint64) error { } w.logicalHead = head w.logicalTail = tail + w.durablePending = true // until the caller persists these bounds return nil } +// bounds returns head and tail from one snapshot. +func (w *walWriter) bounds() (head, tail uint64) { + w.mu.Lock() + defer w.mu.Unlock() + return w.logicalHead, w.logicalTail +} + +// tailPastEntry is the tail that advanceTailPastEntry would set, without +// moving it (the caller persists it first). +func (w *walWriter) tailPastEntry(entryPhys, entryLen uint64) uint64 { + w.mu.Lock() + defer w.mu.Unlock() + physTail := w.physicalPos(w.logicalTail) + var distanceToEntry uint64 + if entryPhys >= physTail { + distanceToEntry = entryPhys - physTail + } else { + distanceToEntry = w.walSize - physTail + entryPhys + } + advance := distanceToEntry + entryLen + if advance > w.used() { + return w.logicalTail + } + return w.logicalTail + advance +} + +// tailPersisted records that a superblock with WAL tail = tail is fsynced: +// the writer's tail moves there (never backward) and the bytes before it +// become reusable. +func (w *walWriter) tailPersisted(tail uint64) { + w.mu.Lock() + defer w.mu.Unlock() + if tail > w.logicalTail { + w.logicalTail = tail + } + w.durableTail = tail + w.durablePending = false +} + func (w *walWriter) head() uint64 { w.mu.Lock() defer w.mu.Unlock() @@ -420,5 +486,5 @@ func (w *walWriter) usedFraction() float64 { if w.walSize == 0 { return 0 } - return float64(w.used()) / float64(w.walSize) + return float64(w.spaceUsed()) / float64(w.walSize) } diff --git a/seaweed-block/core/storage/walstore.go b/seaweed-block/core/storage/walstore.go index 19a1d3eb7c..64c9065792 100644 --- a/seaweed-block/core/storage/walstore.go +++ b/seaweed-block/core/storage/walstore.go @@ -368,8 +368,21 @@ func (s *WALStore) writeExtentUnlocked(lba uint32, data []byte) error { // the in-memory checkpoint advances, because the caller may recycle // the corresponding WAL bytes immediately after this method returns. func (s *WALStore) persistCheckpoint(highestLSN uint64) error { + return s.persistCheckpointReleasing(highestLSN, 0, 0, false) +} + +// persistCheckpointAndRelease is persistCheckpoint that also releases the +// WAL bytes through the entry at entryPhys (entryLen bytes long) when the +// checkpoint reaches highestLSN. The released tail is persisted in the +// same superblock before the writer may reuse those bytes. +func (s *WALStore) persistCheckpointAndRelease(highestLSN, entryPhys, entryLen uint64) error { + return s.persistCheckpointReleasing(highestLSN, entryPhys, entryLen, true) +} + +func (s *WALStore) persistCheckpointReleasing(highestLSN, entryPhys, entryLen uint64, release bool) error { s.mu.Lock() defer s.mu.Unlock() + requested := highestLSN // Clamp the proposed checkpoint to the recycle floor reported // by an external coordinator (e.g., the recovery package's // PeerShipCoordinator). When a replica is in an active rebuild @@ -383,26 +396,39 @@ func (s *WALStore) persistCheckpoint(highestLSN uint64) error { } } } - if highestLSN <= s.checkpointLSN { + advance := highestLSN > s.checkpointLSN + checkpoint := s.checkpointLSN + if advance { + checkpoint = highestLSN + } + // One snapshot of head and tail; the tail this flush releases is + // persisted here, before the writer may reuse its bytes. + head, tail := s.wal.bounds() + if release && checkpoint >= requested { + tail = s.wal.tailPastEntry(entryPhys, entryLen) + } + if !advance && tail == s.sb.WALTail { return nil } - if s.metadata != nil { - if err := s.metadata.BeforeCheckpointAdvance(highestLSN); err != nil { - return fmt.Errorf("storage: block metadata before checkpoint %d: %w", highestLSN, err) + if advance { + if s.metadata != nil { + if err := s.metadata.BeforeCheckpointAdvance(highestLSN); err != nil { + return fmt.Errorf("storage: block metadata before checkpoint %d: %w", highestLSN, err) + } } - } - // The chunk layer's dirty bitmap must be durable before the checkpoint - // (and so the WAL tail) can pass the entries it covers. - if h := s.chunk.Load(); h != nil { - if err := h.sink.BeforeCheckpointAdvance(highestLSN); err != nil { - return fmt.Errorf("storage: chunk bitmap before checkpoint %d: %w", highestLSN, err) + // The chunk layer's dirty bitmap must be durable before the checkpoint + // (and so the WAL tail) can pass the entries it covers. + if h := s.chunk.Load(); h != nil { + if err := h.sink.BeforeCheckpointAdvance(highestLSN); err != nil { + return fmt.Errorf("storage: chunk bitmap before checkpoint %d: %w", highestLSN, err) + } } } sbCopy := *s.sb - sbCopy.WALCheckpointLSN = highestLSN - sbCopy.WALHead = s.wal.logicalHeadValue() - sbCopy.WALTail = s.wal.logicalTailValue() + sbCopy.WALCheckpointLSN = checkpoint + sbCopy.WALHead = head + sbCopy.WALTail = tail buf := newSimpleByteBuf() if _, err := sbCopy.writeTo(buf); err != nil { return fmt.Errorf("storage: encode superblock: %w", err) @@ -423,10 +449,11 @@ func (s *WALStore) persistCheckpoint(highestLSN uint64) error { if err != nil { return fmt.Errorf("storage: fsync checkpoint superblock: %w", err) } - s.checkpointLSN = highestLSN - s.sb.WALCheckpointLSN = highestLSN + s.checkpointLSN = checkpoint + s.sb.WALCheckpointLSN = checkpoint s.sb.WALHead = sbCopy.WALHead s.sb.WALTail = sbCopy.WALTail + s.wal.tailPersisted(sbCopy.WALTail) return nil } @@ -495,6 +522,26 @@ func (s *WALStore) Recover() (uint64, error) { s.dm.clear() return 0, NewWALIntegrityFailure(err, "restore walstore recovery bounds") } + if res.WALHead != s.sb.WALHead || res.WALTail != s.sb.WALTail { + // Persist the rebuilt bounds before any append: the writer never + // reuses bytes the on-disk superblock still declares retained. + sbCopy := *s.sb + sbCopy.WALHead, sbCopy.WALTail = res.WALHead, res.WALTail + buf := newSimpleByteBuf() + if _, err := sbCopy.writeTo(buf); err != nil { + s.dm.clear() + return 0, fmt.Errorf("storage: encode recovered superblock: %w", err) + } + if err := s.writeSuperblockMetadata(buf.bytes()); err != nil { + s.dm.clear() + return 0, fmt.Errorf("storage: pwrite recovered superblock: %w", err) + } + if err := s.syncSuperblockMetadata(); err != nil { + s.dm.clear() + return 0, fmt.Errorf("storage: fsync recovered superblock: %w", err) + } + } + s.wal.tailPersisted(res.WALTail) s.sb.WALHead = res.WALHead s.sb.WALTail = res.WALTail recoveredHead := s.checkpointLSN @@ -1243,8 +1290,7 @@ func (s *WALStore) Close() error { // Persist current head/tail back into the superblock so a // subsequent OpenWALStore can find the WAL bounds without // relying solely on the defensive scan. - s.sb.WALHead = s.wal.logicalHeadValue() - s.sb.WALTail = s.wal.logicalTailValue() + s.sb.WALHead, s.sb.WALTail = s.wal.bounds() buf := newSimpleByteBuf() if _, err := s.sb.writeTo(buf); err != nil { closeErrors = append(closeErrors, fmt.Errorf("storage: encode final superblock: %w", err)) From 46546f20d341d78cf6cab92a18e9d354c771d067 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 23:45:32 -0800 Subject: [PATCH 11/16] storage: RED: a full flush's head==tail sends recovery to offset 0 With the released tail persisted (88fbb345), a full flush persists head == tail. Sync does not persist the head, so synced appends follow it; recovery's head==tail path ignores the persisted position and scans from offset 0 when no high run is found, so a torn unsynced record wrapped to 0 hides every synced record after it (claude05's S3 trace shape). Co-Authored-By: Claude Opus 5.5 --- .../storage/walstore_persisted_tail_test.go | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/seaweed-block/core/storage/walstore_persisted_tail_test.go b/seaweed-block/core/storage/walstore_persisted_tail_test.go index 70838d2ca4..03ebebe2d5 100644 --- a/seaweed-block/core/storage/walstore_persisted_tail_test.go +++ b/seaweed-block/core/storage/walstore_persisted_tail_test.go @@ -204,3 +204,62 @@ func TestWALWriterReuseIsBoundedByTheDurableTail(t *testing.T) { t.Fatalf("append into bytes released only in memory: err=%v; want errWALFull until the tail is persisted", err) } } + +// A full flush persists head == tail (an empty WAL at that position). Sync +// does not persist the head, so synced appends follow it there; recovery must +// scan from the persisted position, not from offset 0 (claude05's S3 trace: +// a torn unsynced record wrapped to 0 must not hide the synced run). +func TestWALStoreFullFlushThenTornWrapKeepsSyncedRecords(t *testing.T) { + const ( + blockSize = 4096 + walSize = 24 * 1024 + ) + S := uint64(walEntryHeaderSize + blockSize) + path := filepath.Join(t.TempDir(), "store.bin") + s := createWALStoreWithWALSizeForTest(t, path, 64, blockSize, walSize) + s.DisableAutoFlushForRecoveryTest() + if _, err := s.Write(0, makeBlock(blockSize, 0x10)); err != nil { // LSN 1 + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + for lba := uint32(1); lba <= 4; lba++ { // LSN 2..5, synced + 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.Write(5, makeBlock(blockSize, 0x66)); err != nil { // LSN 6, unsynced, wraps + t.Fatal(err) + } + ents := recoverySnapshotEntriesByLBA(s.dm.snapshot()) + if ents[5].WALOffset != 0 || ents[1].WALOffset != S { + t.Fatalf("layout: LSN 6 at %d, LSN 2 at %d; want 0 and S", ents[5].WALOffset, ents[1].WALOffset) + } + walOff := s.sb.WALOffset + if _, err := s.fd.WriteAt(make([]byte, walSize-5*S), int64(walOff+5*S)); err != nil { // padding not on disk + t.Fatal(err) + } + if _, err := s.fd.WriteAt(make([]byte, blockSize/2), int64(walOff+S-blockSize/2)); err != nil { // LSN 6 torn + t.Fatal(err) + } + crashRecoveryHardeningStore(t, s) + r, err := OpenWALStore(path) + if err != nil { + t.Fatal(err) + } + r.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = r.Close() }) + if _, err := r.Recover(); err != nil { + t.Fatalf("Recover: %v", err) + } + for lba := uint32(1); lba <= 4; lba++ { + assertRecoveryHardeningBlock(t, r, lba, makeBlock(blockSize, byte(0x10+lba))) + } +} From 7184c0f2e3c277fd6e351de7c1d44e47a3c37ae0 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 23:48:02 -0800 Subject: [PATCH 12/16] storage: scan an empty superblock window from its position A full checkpoint persists head == tail (88fbb345 persists the released tail). Sync does not persist the head, so appends after it continue contiguously from that position; recovery now scans [pos, end) then [0, pos) from it. The footer high-run search stays only for the legacy (0, 0) superblock. Scanning from offset 0 let a torn unsynced record wrapped there hide every synced record after it. Model check (claude05's WALRecovery.tla, rule rootLww = this writer and scan plus #156's replay by LSN, K=4, 4 LSNs): crash-only I1 and I2 hold (247,395 distinct states). Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/recovery.go | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/seaweed-block/core/storage/recovery.go b/seaweed-block/core/storage/recovery.go index 3b0f6d12e1..46bded3ced 100644 --- a/seaweed-block/core/storage/recovery.go +++ b/seaweed-block/core/storage/recovery.go @@ -55,7 +55,18 @@ func recoverWAL(fd *os.File, sb *superblock, dm *dirtyMap) (recoveryResult, erro } var ranges []scanRange - if logicalHead == logicalTail { + if logicalHead == logicalTail && logicalHead%walSize != 0 { + // The superblock records an empty WAL at this position (a full + // checkpoint persists head == tail). Sync does not persist the + // head, so later appends continue contiguously from here: scan + // from it. Scanning from offset 0 would let a torn record wrapped + // there hide the synced run behind it. + start := logicalHead % walSize + ranges = append(ranges, scanRange{start, walSize}, scanRange{0, start}) + result.DefensiveScan = true + log.Printf("storage: recovery from an empty superblock window (head==tail=%d checkpoint=%d)", + logicalHead, checkpointLSN) + } else if logicalHead == logicalTail { // A pre-boundary-persistence crash can leave a wrapped retained // window while the superblock still says empty. Find the high // physical run from record footers, then scan high and low as From f99663a69aa1d3338966cfad92b3a244c94ecc6c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 23:53:02 -0800 Subject: [PATCH 13/16] fix: separate workspace lease expiry with a clock skew margin --- .../master/workspace_renewal_boundary_test.go | 156 ++++++++++++++++++ 1 file changed, 156 insertions(+) create mode 100644 seaweed-block/core/host/master/workspace_renewal_boundary_test.go diff --git a/seaweed-block/core/host/master/workspace_renewal_boundary_test.go b/seaweed-block/core/host/master/workspace_renewal_boundary_test.go new file mode 100644 index 0000000000..afab27803b --- /dev/null +++ b/seaweed-block/core/host/master/workspace_renewal_boundary_test.go @@ -0,0 +1,156 @@ +package master + +import ( + "context" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/host/volume" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" +) + +type heldSkewLeaseClient struct { + skewLeaseClient + calls atomic.Int32 + initial *control.WorkspaceLeaseFact + entered chan *control.WorkspaceLeaseFact + release chan struct{} +} + +func (c *heldSkewLeaseClient) RenewWorkspaceLease(ctx context.Context, id *control.WorkspaceIdentity, opts ...grpc.CallOption) (*control.WorkspaceLeaseFact, error) { + reply, err := c.skewLeaseClient.RenewWorkspaceLease(ctx, id, opts...) + if err != nil { + return nil, err + } + if c.calls.Add(1) == 1 { + c.initial = reply + return reply, nil + } + select { + case c.entered <- reply: + case <-ctx.Done(): + return nil, ctx.Err() + } + select { + case <-c.release: + return reply, nil + case <-ctx.Done(): + return nil, ctx.Err() + } +} + +func TestWorkspaceHeldRenewalBoundary(t *testing.T) { + for _, late := range []bool{false, true} { + t.Run(map[bool]string{false: "before-old-expiry", true: "after-old-expiry"}[late], func(t *testing.T) { + store, err := authority.NewFileAuthorityStore(t.TempDir()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if err := store.Close(); err != nil { + t.Error(err) + } + }) + // Current-time clocks keep the guard's real RPC deadline in the future. + start := time.Now() + var masterNS, hostNS atomic.Int64 + masterNS.Store(start.UnixNano()) + hostNS.Store(start.UnixNano()) + dir := &skewDirective{asks: make(chan authority.AssignmentAsk, 1)} + p := authority.NewPublisher(dir, authority.WithStore(store), authority.WithWorkspaceLeaseConfig(30*time.Second, func() time.Time { return time.Unix(0, masterNS.Load()) }), authority.WithWorkspaceMaxClockSkew(4*time.Second)) + seedSkewPublisher(t, p, dir) + client := &heldSkewLeaseClient{skewLeaseClient: skewLeaseClient{p}, entered: make(chan *control.WorkspaceLeaseFact, 1), release: make(chan struct{})} + g, err := volume.NewWorkspaceLeaseGuard(workspaceRPCView{frontend.Projection{VolumeID: "v", ReplicaID: "r", Epoch: 1, Healthy: true}}, client, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 1}, func(context.Context) (uint64, error) { return 7, nil }, func() time.Time { return time.Unix(0, hostNS.Load()) }) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + if err := g.Refresh(ctx); err != nil { + t.Fatal(err) + } + oldLease := *p.WorkspaceState("v").Lease + oldEarly := start.Add(time.Duration(client.initial.ValidForNs)) + requestStart := start.Add(time.Second) + hostNS.Store(requestStart.UnixNano()) + masterNS.Store(requestStart.UnixNano()) + done := make(chan struct{}) + var refreshErr error + var releaseOnce sync.Once + release := func() { releaseOnce.Do(func() { close(client.release) }) } + go func() { defer close(done); refreshErr = g.Refresh(ctx) }() + t.Cleanup(func() { + release() + cancel() + select { + case <-done: + case <-time.After(3 * time.Second): + t.Error("held renewal unsettled") + } + }) + var reply *control.WorkspaceLeaseFact + select { + case reply = <-client.entered: + case <-ctx.Done(): + t.Fatal("renewal did not enter", ctx.Err()) + } + renewed := *p.WorkspaceState("v").Lease + freshEarly := requestStart.Add(time.Duration(reply.ValidForNs)) + if freshEarly.Sub(oldEarly) < time.Second || renewed.ExpiresAtNS <= oldLease.ExpiresAtNS || renewed.MaxClockSkewNS != int64(4*time.Second) { + t.Fatal("fixture did not extend the real persisted grant", oldLease, renewed) + } + arrival := oldEarly.Add(-time.Second) + if late { + arrival = oldEarly.Add(freshEarly.Sub(oldEarly) / 2) + } + if !arrival.Before(freshEarly) || ctx.Err() != nil { + t.Fatal("new-grant or context expiry would mask old-boundary check") + } + // Do not call Projection here: it must not pre-latch the old expiry. + hostNS.Store(arrival.UnixNano()) + masterNS.Store(arrival.UnixNano()) + release() + select { + case <-done: + case <-ctx.Done(): + t.Fatal("held response did not settle", ctx.Err()) + } + if late { + if refreshErr == nil || g.Projection().Healthy { + t.Fatal("late renewal revived lease after OLD early expiry while NEW grant remained future") + } + } else { + if refreshErr != nil || !g.Projection().Healthy { + t.Fatal("timely renewal refused", refreshErr) + } + hostNS.Store(oldEarly.Add(freshEarly.Sub(oldEarly) / 2).UnixNano()) + if !g.Projection().Healthy { + t.Fatal("timely grant failed to extend old early expiry") + } + } + q := authority.WorkspaceMoveRequest{RequestID: "renewed-forced", VolumeID: "v", ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "old", TargetHost: "new", ExpectedEpoch: 1, TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "forced", Force: true} + head := authority.WorkspaceHead{Gen: 7, Epoch: 1, Holder: "old/r", RemoteLSN: 42} + boundary := time.Unix(0, renewed.ExpiresAtNS).Add(time.Duration(renewed.MaxClockSkewNS)) + for _, when := range []time.Time{time.Unix(0, oldLease.ExpiresAtNS).Add(4 * time.Second), boundary.Add(-time.Nanosecond)} { + masterNS.Store(when.UnixNano()) + if _, err := p.MoveWorkspace(ctx, q, head); err == nil { + t.Fatal("forced move ignored renewed expiry plus persisted margin") + } + if len(p.WorkspaceState("v").Moves) != 0 { + t.Fatal("refusal wrote journal") + } + } + masterNS.Store(boundary.UnixNano()) + hostNS.Store(boundary.Add(-time.Second).UnixNano()) + grant, err := p.MoveWorkspace(ctx, q, head) + if err != nil || !grant.Issued || grant.NewEpoch <= 1 || g.Projection().Healthy { + t.Fatal("renewed boundary grant overlaps old admission", grant, err) + } + }) + } +} From 980de2b94a24ceb712527c1f11bd791aecdff7ce Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 16 Nov 2026 00:09:55 -0800 Subject: [PATCH 14/16] storage: guard: recovery keeps synced entries above an unpersisted frontier jump claude05's condition (1) for any prefix-cut recovery rule (2026-11-16 07:33Z). A rebuild installs BASE by WriteExtentDirect (no LSN) and applies WAL-lane entries with their real LSNs by ApplyEntry; AdvanceFrontier runs only at MarkBaseComplete and is in memory until a Sync. So a store can hold synced LSN 101-102 with a persisted checkpoint of 0 and no LSN 1..100. Recovery keeps them; a rule replaying only the contiguous LSN prefix above the checkpoint would keep none. This pins that, so no such rule lands. Co-Authored-By: Claude Opus 5.5 --- .../walstore_recovery_frontier_gap_test.go | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 seaweed-block/core/storage/walstore_recovery_frontier_gap_test.go diff --git a/seaweed-block/core/storage/walstore_recovery_frontier_gap_test.go b/seaweed-block/core/storage/walstore_recovery_frontier_gap_test.go new file mode 100644 index 0000000000..ff0af66903 --- /dev/null +++ b/seaweed-block/core/storage/walstore_recovery_frontier_gap_test.go @@ -0,0 +1,65 @@ +package storage + +import ( + "path/filepath" + "testing" +) + +// claude05's condition (1) for any prefix-cut recovery rule (2026-11-16 +// 07:33Z): an intentional LSN gap must not drop synced entries above it. A +// rebuild installs BASE through WriteExtentDirect (no LSN) and applies +// WAL-lane entries with their real LSNs through ApplyEntry; the frontier +// jump (AdvanceFrontier at MarkBaseComplete) is not persisted before them. +// So a replica can hold a synced LSN 101 with a persisted checkpoint of 0 and +// no LSN 1..100 anywhere. Recovery must keep it (a rule that replays only the +// contiguous LSN prefix above the checkpoint keeps nothing here). +func TestWALStoreRecoverKeepsSyncedEntriesAboveAnUnpersistedFrontierJump(t *testing.T) { + const blockSize = 4096 + path := filepath.Join(t.TempDir(), "store.bin") + s := createWALStoreWithWALSizeForTest(t, path, 64, blockSize, 24*1024) + s.DisableAutoFlushForRecoveryTest() + if err := s.WriteExtentDirect(0, makeBlock(blockSize, 0xBA)); err != nil { // BASE, no LSN + t.Fatal(err) + } + live := makeBlock(blockSize, 0x65) + if err := s.ApplyEntry(3, live, 101); err != nil { // session-live entry above the BASE hint + t.Fatal(err) + } + if err := s.ApplyEntry(4, makeBlock(blockSize, 0x66), 102); err != nil { + t.Fatal(err) + } + synced, err := s.Sync() + if err != nil { + t.Fatal(err) + } + if synced < 102 { + t.Fatalf("Sync frontier %d; want 102 (the applied entries are synced)", synced) + } + crashRecoveryHardeningStore(t, s) + if sb := diskSuperblockForGapTest(t, path); sb.WALCheckpointLSN != 0 { + t.Fatalf("persisted checkpoint %d; want 0 (the frontier jump is not persisted)", sb.WALCheckpointLSN) + } + r, err := OpenWALStore(path) + if err != nil { + t.Fatal(err) + } + r.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = r.Close() }) + if _, err := r.Recover(); err != nil { + t.Fatalf("Recover: %v", err) + } + assertRecoveryHardeningBlock(t, r, 3, live) + assertRecoveryHardeningBlock(t, r, 4, makeBlock(blockSize, 0x66)) +} + +func diskSuperblockForGapTest(t *testing.T, path string) superblock { + t.Helper() + r, err := OpenWALStore(path) + if err != nil { + t.Fatal(err) + } + sb := *r.sb + r.committer.Stop() + _ = r.fd.Close() + return sb +} From 4ffa3c9a08caa4f1f1a3aa3404c8031730a1367c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 16 Nov 2026 00:17:08 -0800 Subject: [PATCH 15/16] storage: frontier-gap guard reads the superblock without opening a store codex01's AMEND on 980de2b9 (tests-only P2): the helper opened a full WALStore and only stopped its committer and closed its fd, leaving the flusher and ticker alive. Read the superblock with a scoped file read (readSuperblock), and register the original store's cleanup right after open so a Fatal before the crash step still closes it. Co-Authored-By: Claude Opus 5.5 --- .../walstore_recovery_frontier_gap_test.go | 20 +++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/seaweed-block/core/storage/walstore_recovery_frontier_gap_test.go b/seaweed-block/core/storage/walstore_recovery_frontier_gap_test.go index ff0af66903..c89d538294 100644 --- a/seaweed-block/core/storage/walstore_recovery_frontier_gap_test.go +++ b/seaweed-block/core/storage/walstore_recovery_frontier_gap_test.go @@ -1,6 +1,7 @@ package storage import ( + "os" "path/filepath" "testing" ) @@ -18,6 +19,12 @@ func TestWALStoreRecoverKeepsSyncedEntriesAboveAnUnpersistedFrontierJump(t *test path := filepath.Join(t.TempDir(), "store.bin") s := createWALStoreWithWALSizeForTest(t, path, 64, blockSize, 24*1024) s.DisableAutoFlushForRecoveryTest() + crashed := false + t.Cleanup(func() { + if !crashed { + _ = s.Close() + } + }) if err := s.WriteExtentDirect(0, makeBlock(blockSize, 0xBA)); err != nil { // BASE, no LSN t.Fatal(err) } @@ -36,6 +43,7 @@ func TestWALStoreRecoverKeepsSyncedEntriesAboveAnUnpersistedFrontierJump(t *test t.Fatalf("Sync frontier %d; want 102 (the applied entries are synced)", synced) } crashRecoveryHardeningStore(t, s) + crashed = true if sb := diskSuperblockForGapTest(t, path); sb.WALCheckpointLSN != 0 { t.Fatalf("persisted checkpoint %d; want 0 (the frontier jump is not persisted)", sb.WALCheckpointLSN) } @@ -52,14 +60,18 @@ func TestWALStoreRecoverKeepsSyncedEntriesAboveAnUnpersistedFrontierJump(t *test assertRecoveryHardeningBlock(t, r, 4, makeBlock(blockSize, 0x66)) } +// diskSuperblockForGapTest reads the on-disk superblock with a plain file +// read: no store, no flusher or committer. func diskSuperblockForGapTest(t *testing.T, path string) superblock { t.Helper() - r, err := OpenWALStore(path) + f, err := os.Open(path) + if err != nil { + t.Fatal(err) + } + defer f.Close() + sb, err := readSuperblock(f) if err != nil { t.Fatal(err) } - sb := *r.sb - r.committer.Stop() - _ = r.fd.Close() return sb } From c5f619c9dd8aab7dfab0c19b52830d65d1d6727f Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 16 Nov 2026 00:29:54 -0800 Subject: [PATCH 16/16] storage: #159 controls: batch reuse bound, Recover bounds persist failure codex01's #159 P2-S2 and P2-S3 (tests only): - TestWALWriterBatchReuseIsBoundedByTheDurableTail: the batch planner, with a padding wrap, is refused while a release is in memory only or the recovered bounds are pending (no head move, no padding written), and accepted once the tail is persisted. - TestWALStoreRecoverBoundsPersistFailureRefusesAppendsUntilRetry: a failing superblock write or fsync fails Recover and admits no Write; a same-instance Recover retry persists the bounds; a later Write, Sync and reopen keep the exact bytes. Mutation controls (WSL): reverting only the batch planner's durable-tail check fails the batch test alone; publishing the tail before Recover's persist, or dropping the pending flag, fails its own control. Co-Authored-By: Claude Opus 5.5 --- .../storage/walstore_persisted_tail_test.go | 195 ++++++++++++++++++ 1 file changed, 195 insertions(+) diff --git a/seaweed-block/core/storage/walstore_persisted_tail_test.go b/seaweed-block/core/storage/walstore_persisted_tail_test.go index 03ebebe2d5..42deed829d 100644 --- a/seaweed-block/core/storage/walstore_persisted_tail_test.go +++ b/seaweed-block/core/storage/walstore_persisted_tail_test.go @@ -1,10 +1,12 @@ package storage import ( + "bytes" "errors" "os" "path/filepath" "testing" + "time" ) // The WAL writer may only overwrite bytes that the PERSISTED superblock tail @@ -263,3 +265,196 @@ func TestWALStoreFullFlushThenTornWrapKeepsSyncedRecords(t *testing.T) { assertRecoveryHardeningBlock(t, r, lba, makeBlock(blockSize, byte(0x10+lba))) } } + +// codex01 #159 P2-S2: the batch planner (with a padding wrap) counts from the +// durable tail too: refused while the release is only in memory or the +// bounds are recovery-pending, accepted once the tail is persisted. +func TestWALWriterBatchReuseIsBoundedByTheDurableTail(t *testing.T) { + const walSize = 4096 + mk := func(lsn uint64) walEntry { + return walEntry{LSN: lsn, Type: walEntryWrite, LBA: lsn, Length: 64, Data: make([]byte, 64)} + } + e0 := mk(0) + size, err := e0.encodedSize() + if err != nil { + t.Fatal(err) + } + sz := uint64(size) + n := uint64(walSize) / sz // the last walSize%sz bytes force a padding wrap + fill := func(t *testing.T) (*walWriter, *os.File) { + f, err := os.CreateTemp(t.TempDir(), "wal") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = f.Close() }) + if err := f.Truncate(walSize); err != nil { + t.Fatal(err) + } + w := newWALWriter(f, 0, walSize, 0, 0, nil) + for i := uint64(0); i < n; i++ { + e := mk(i + 1) + if _, err := w.append(&e); err != nil { + t.Fatalf("fill %d: %v", i, err) + } + } + return w, f + } + batch := func() []walEntry { return []walEntry{mk(n + 1), mk(n + 2)} } + refused := func(t *testing.T, w *walWriter, f *os.File, why string) { + t.Helper() + head := w.logicalHeadValue() + tailBytes := make([]byte, walSize-n*sz) + if _, err := f.ReadAt(tailBytes, int64(n*sz)); err != nil { + t.Fatal(err) + } + if _, err := w.appendBatch(batch()); !errors.Is(err, errWALFull) { + t.Fatalf("%s: appendBatch err=%v; want errWALFull", why, err) + } + after := make([]byte, len(tailBytes)) + if _, err := f.ReadAt(after, int64(n*sz)); err != nil { + t.Fatal(err) + } + if w.logicalHeadValue() != head || !bytes.Equal(after, tailBytes) { + t.Fatalf("%s: a refused batch moved the head or wrote padding", why) + } + } + accepted := func(t *testing.T, w *walWriter) { + t.Helper() + offs, err := w.appendBatch(batch()) + if err != nil { + t.Fatalf("after the tail is persisted: appendBatch: %v", err) + } + if len(offs) != 2 || offs[0] != 0 || offs[1] != sz { + t.Fatalf("offsets %v; want the batch wrapped to [0 %d]", offs, sz) + } + } + + t.Run("released in memory only", func(t *testing.T) { + w, f := fill(t) + w.advanceTailPastEntry(0, 2*sz) + refused(t, w, f, "in-memory release") + w.tailPersisted(2 * sz) + accepted(t, w) + }) + t.Run("recovered bounds pending", func(t *testing.T) { + w, f := fill(t) + w.tailPersisted(2 * sz) // the space is free on disk; only the pending flag refuses it + if err := w.restoreRecoveredBounds(n*sz, 2*sz); err != nil { + t.Fatal(err) + } + refused(t, w, f, "durablePending") + single := mk(n + 1) + if _, err := w.append(&single); !errors.Is(err, errWALFull) { + t.Fatalf("durablePending: append err=%v; want errWALFull", err) + } + w.tailPersisted(2 * sz) + accepted(t, w) + }) +} + +// codex01 #159 P2-S3: when Recover cannot persist the rebuilt bounds (the +// superblock write or its fsync fails), it fails, admits no append, and a +// same-instance retry persists them; later writes survive a reopen exactly. +func TestWALStoreRecoverBoundsPersistFailureRefusesAppendsUntilRetry(t *testing.T) { + const blockSize = 4096 + S := uint64(walEntryHeaderSize + blockSize) + errInjected := errors.New("injected superblock failure") + for _, seam := range []string{"write", "sync"} { + t.Run(seam, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "store.bin") + s := createWALStoreWithWALSizeForTest(t, path, 64, blockSize, 24*1024) + s.DisableAutoFlushForRecoveryTest() + crashed := false + t.Cleanup(func() { + if !crashed { + _ = s.Close() + } + }) + if _, err := s.Write(0, makeBlock(blockSize, 0x30)); err != nil { // LSN 1 + 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(1, makeBlock(blockSize, 0x31)); err != nil { // LSN 2, synced, unflushed + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + sb := *s.sb // an older flush's superblock: the bounds Recover must rebuild and persist + sb.WALCheckpointLSN, sb.WALTail, sb.WALHead = 1, 0, 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) + } + crashRecoveryHardeningStore(t, s) + crashed = true + + r, err := OpenWALStore(path) + if err != nil { + t.Fatal(err) + } + r.DisableAutoFlushForRecoveryTest() + rClosed := false + t.Cleanup(func() { + if !rClosed { + _ = r.Close() + } + }) + realWrite, realSync := r.writeSuperblockMetadata, r.syncSuperblockMetadata + if seam == "write" { + r.writeSuperblockMetadata = func([]byte) error { return errInjected } + } else { + r.syncSuperblockMetadata = func() error { return errInjected } + } + if _, err := r.Recover(); !errors.Is(err, errInjected) { + t.Fatalf("Recover with a failing superblock %s: err=%v; want the injected failure", seam, err) + } + head := r.wal.logicalHeadValue() + r.admissionTimeout = 200 * time.Millisecond + if _, err := r.Write(5, makeBlock(blockSize, 0x55)); err == nil { + t.Fatal("Write after a failed Recover succeeded; want it refused until the bounds are persisted") + } + if r.wal.logicalHeadValue() != head { + t.Fatalf("refused Write moved the WAL head %d -> %d", head, r.wal.logicalHeadValue()) + } + + r.writeSuperblockMetadata, r.syncSuperblockMetadata = realWrite, realSync + if _, err := r.Recover(); err != nil { + t.Fatalf("same-instance Recover retry: %v", err) + } + disk := diskSuperblockForTest(t, path) + if tail, h := r.wal.logicalTailValue(), r.wal.logicalHeadValue(); disk.WALTail != tail || disk.WALHead != h { + t.Fatalf("after the retry: persisted tail=%d head=%d, writer tail=%d head=%d", disk.WALTail, disk.WALHead, tail, h) + } + r.admissionTimeout = 30 * time.Second + if _, err := r.Write(5, makeBlock(blockSize, 0x55)); err != nil { + t.Fatal(err) + } + if _, err := r.Sync(); err != nil { + t.Fatal(err) + } + crashRecoveryHardeningStore(t, r) + rClosed = true + + q, err := OpenWALStore(path) + if err != nil { + t.Fatal(err) + } + q.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = q.Close() }) + if _, err := q.Recover(); err != nil { + t.Fatalf("reopen Recover: %v", err) + } + assertRecoveryHardeningBlock(t, q, 1, makeBlock(blockSize, 0x31)) + assertRecoveryHardeningBlock(t, q, 5, makeBlock(blockSize, 0x55)) + }) + } +}