From 88fbb345b010aa39c83b43507452077172ab5d6d Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 23:39:27 -0800 Subject: [PATCH] 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))