From 99e281d153d0b1b236a650407bfd0c1664850d2e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 23:37:14 -0800 Subject: [PATCH 1/5] 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 2/5] 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 3/5] 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 4/5] 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 c5f619c9dd8aab7dfab0c19b52830d65d1d6727f Mon Sep 17 00:00:00 2001 From: pingqiu Date: Mon, 16 Nov 2026 00:29:54 -0800 Subject: [PATCH 5/5] 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)) + }) + } +}