mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-06 11:07:31 +01:00
Merge pull request #159 from seaweedfs/fix/walstore-persisted-tail-reuse
storage: reuse only WAL bytes the persisted tail released
This commit is contained in:
commit
0517afc77d
5 files changed
+617
-25
No files matched your search
@@ -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,
|
||||
)
|
||||
@@ -220,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
|
||||
|
||||
@@ -60,7 +60,18 @@ func recoverWAL(fd *os.File, sb *superblock, dm *dirtyMap) (recoveryResult, erro
|
||||
// lastLSN is the highest LSN decoded so far (detection only).
|
||||
var lastLSN uint64
|
||||
|
||||
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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -373,8 +373,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
|
||||
@@ -388,26 +401,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)
|
||||
@@ -428,10 +454,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
|
||||
}
|
||||
|
||||
@@ -526,6 +553,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
|
||||
s.recoveryWarnings = nil
|
||||
@@ -1279,8 +1326,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))
|
||||
|
||||
@@ -0,0 +1,460 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
|
||||
// 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)))
|
||||
}
|
||||
}
|
||||
|
||||
// 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))
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user