From b8fb9f66f777f414caf9ebc9fb06f89b22bc59da Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 30 Jul 2026 06:49:33 -0700 Subject: [PATCH] storage: harden materialization lifecycle recovery --- seaweed-block/core/storage/recovery.go | 182 +++++- seaweed-block/core/storage/wal_writer.go | 14 + seaweed-block/core/storage/walstore.go | 11 + ...walstore_materialization_lifecycle_test.go | 589 ++++++++++++++++++ seaweed-block/internal/docs/current-plan.md | 13 + ...hase172-d4-materialization-lifecycle-qa.md | 81 +++ ...phase172-materialization-lifecycle-gate.sh | 117 ++++ 7 files changed, 990 insertions(+), 17 deletions(-) create mode 100644 seaweed-block/core/storage/walstore_materialization_lifecycle_test.go create mode 100644 seaweed-block/internal/docs/qa-assignments/phase172-d4-materialization-lifecycle-qa.md create mode 100644 seaweed-block/scripts/run-phase172-materialization-lifecycle-gate.sh diff --git a/seaweed-block/core/storage/recovery.go b/seaweed-block/core/storage/recovery.go index 377217ad83..8f6d4cd76e 100644 --- a/seaweed-block/core/storage/recovery.go +++ b/seaweed-block/core/storage/recovery.go @@ -1,15 +1,19 @@ package storage import ( + "encoding/binary" "fmt" "log" "os" + "sort" ) // recoveryResult summarizes what RecoverWAL did on one open. type recoveryResult struct { 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 } @@ -33,6 +37,12 @@ type recoveryResult struct { // resumes after them. func recoverWAL(fd *os.File, sb *superblock, dm *dirtyMap) (recoveryResult, error) { result := recoveryResult{} + type retainedRecord struct { + firstLSN uint64 + start uint64 + end uint64 + } + var retainedRecords []retainedRecord logicalHead := sb.WALHead logicalTail := sb.WALTail @@ -46,10 +56,20 @@ func recoverWAL(fd *os.File, sb *superblock, dm *dirtyMap) (recoveryResult, erro var ranges []scanRange if logicalHead == logicalTail { - // Superblock claims WAL is empty. Scan the whole region; on a - // genuinely empty WAL the first byte is zero and CRC fails - // immediately. - ranges = append(ranges, scanRange{0, walSize}) + // 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 + // disjoint ranges so neither side is hidden behind the gap. + highStart, found := findDefensiveHighRunStart(fd, walOffset, walSize) + if found && highStart > 0 { + ranges = append( + ranges, + scanRange{highStart, walSize}, + scanRange{0, highStart}, + ) + } else { + ranges = append(ranges, scanRange{0, walSize}) + } result.DefensiveScan = true log.Printf("storage: recovery defensive scan (head==tail=%d checkpoint=%d)", logicalHead, checkpointLSN) @@ -111,10 +131,36 @@ func recoverWAL(fd *os.File, sb *superblock, dm *dirtyMap) (recoveryResult, erro result.TornEntries++ break } - if entry.LSN <= checkpointLSN { + highestEntryLSN := entry.LSN + if entry.Type == walEntryWriteBatch { + maxBlocks := uint64(^uint32(0)) / uint64(sb.BlockSize) + if entry.Reserved == 0 || + entry.Reserved > maxBlocks || + entry.Reserved-1 > ^uint64(0)-entry.LSN || + uint64(entry.Length) != entry.Reserved*uint64(sb.BlockSize) { + return result, NewWALIntegrityFailure( + nil, + fmt.Sprintf( + "invalid walstore batch at offset=%d LSN=%d reserved=%d length=%d block_size=%d", + pos, entry.LSN, entry.Reserved, entry.Length, sb.BlockSize, + ), + ) + } + highestEntryLSN = entry.LSN + entry.Reserved - 1 + } + if highestEntryLSN <= checkpointLSN { pos += entrySize continue } + firstRetainedLSN := entry.LSN + if firstRetainedLSN <= checkpointLSN { + firstRetainedLSN = checkpointLSN + 1 + } + retainedRecords = append(retainedRecords, retainedRecord{ + firstLSN: firstRetainedLSN, + start: pos, + end: pos + entrySize, + }) switch entry.Type { case walEntryWrite: blocks := entry.Length / sb.BlockSize @@ -127,10 +173,6 @@ func recoverWAL(fd *os.File, sb *superblock, dm *dirtyMap) (recoveryResult, erro result.EntriesReplayed++ case walEntryWriteBatch: blocks := uint32(entry.Reserved) - if blocks == 0 || entry.Length != blocks*sb.BlockSize { - result.TornEntries++ - break - } for i := uint32(0); i < blocks; i++ { lsn := entry.LSN + uint64(i) if lsn <= checkpointLSN { @@ -157,10 +199,6 @@ func recoverWAL(fd *os.File, sb *superblock, dm *dirtyMap) (recoveryResult, erro case walEntryBarrier: // no data; skip } - highestEntryLSN := entry.LSN - if entry.Type == walEntryWriteBatch && entry.Reserved > 0 { - highestEntryLSN = entry.LSN + entry.Reserved - 1 - } if highestEntryLSN > result.HighestLSN { result.HighestLSN = highestEntryLSN } @@ -168,10 +206,120 @@ func recoverWAL(fd *os.File, sb *superblock, dm *dirtyMap) (recoveryResult, erro } } - if result.HighestLSN > sb.WALHead { - log.Printf("storage: recovery extended scan found entries past WALHead (%d → %d, %d replayed)", - sb.WALHead, result.HighestLSN, result.EntriesReplayed) - sb.WALHead = result.HighestLSN + sort.Slice(retainedRecords, func(left, right int) bool { + return retainedRecords[left].firstLSN < retainedRecords[right].firstLSN + }) + if len(retainedRecords) > 0 { + result.WALTail = retainedRecords[0].start + result.WALHead = retainedRecords[0].end + previousStart := retainedRecords[0].start + var wrapBase uint64 + for _, record := range retainedRecords[1:] { + if record.start < previousStart { + wrapBase += walSize + } + logicalStart := wrapBase + record.start + logicalEnd := wrapBase + record.end + if logicalStart < result.WALHead || logicalEnd-logicalStart > walSize { + return result, NewWALIntegrityFailure( + nil, + fmt.Sprintf( + "invalid walstore recovery order at LSN=%d offset=%d", + record.firstLSN, record.start, + ), + ) + } + result.WALHead = logicalEnd + previousStart = record.start + } + if result.WALHead < result.WALTail || + result.WALHead-result.WALTail > walSize { + return result, NewWALIntegrityFailure( + nil, + fmt.Sprintf( + "invalid walstore recovery bounds tail=%d head=%d size=%d", + result.WALTail, result.WALHead, walSize, + ), + ) + } + } + if result.DefensiveScan && result.EntriesReplayed > 0 { + log.Printf( + "storage: recovery reconstructed WAL bytes tail=%d head=%d frontier=%d (%d replayed)", + result.WALTail, result.WALHead, result.HighestLSN, result.EntriesReplayed, + ) } return result, nil } + +func findDefensiveHighRunStart( + fd *os.File, + walOffset uint64, + walSize uint64, +) (uint64, bool) { + maxGap := uint64(walEntryHeaderSize - 1) + if maxGap >= walSize { + maxGap = walSize - 1 + } + for gap := uint64(0); gap <= maxGap; gap++ { + cursor := walSize - gap + start, entry, ok := previousValidWALRecord(fd, walOffset, cursor) + if !ok { + continue + } + earliest := start + foundData := entry.Type != walEntryPadding + cursor = start + for cursor > 0 { + previousStart, previous, ok := previousValidWALRecord( + fd, walOffset, cursor, + ) + if !ok { + break + } + earliest = previousStart + if previous.Type != walEntryPadding { + foundData = true + } + cursor = previousStart + } + if foundData { + return earliest, true + } + } + return 0, false +} + +func previousValidWALRecord( + fd *os.File, + walOffset uint64, + end uint64, +) (uint64, walEntry, bool) { + if end < 4 { + return 0, walEntry{}, false + } + var sizeBytes [4]byte + if _, err := fd.ReadAt(sizeBytes[:], int64(walOffset+end-4)); err != nil { + return 0, walEntry{}, false + } + size := uint64(binary.LittleEndian.Uint32(sizeBytes[:])) + if size < uint64(walEntryHeaderSize) || size > end { + return 0, walEntry{}, false + } + start := end - size + record := make([]byte, size) + if _, err := fd.ReadAt(record, int64(walOffset+start)); err != nil { + return 0, walEntry{}, false + } + entry, err := decodeWALEntry(record) + if err != nil { + return 0, walEntry{}, false + } + switch entry.Type { + case walEntryWrite, walEntryWriteBatch, walEntryTrim, + walEntryBarrier, walEntryPadding: + return start, entry, true + default: + return 0, walEntry{}, false + } +} diff --git a/seaweed-block/core/storage/wal_writer.go b/seaweed-block/core/storage/wal_writer.go index eca6d2f406..ee4b098563 100644 --- a/seaweed-block/core/storage/wal_writer.go +++ b/seaweed-block/core/storage/wal_writer.go @@ -363,6 +363,20 @@ func (w *walWriter) reset() { w.logicalTail = 0 } +func (w *walWriter) restoreRecoveredBounds(head, tail uint64) error { + w.mu.Lock() + defer w.mu.Unlock() + if head < tail || head-tail > w.walSize { + return fmt.Errorf( + "walWriter: invalid recovered bounds tail=%d head=%d size=%d", + tail, head, w.walSize, + ) + } + w.logicalHead = head + w.logicalTail = tail + return nil +} + func (w *walWriter) head() uint64 { w.mu.Lock() defer w.mu.Unlock() diff --git a/seaweed-block/core/storage/walstore.go b/seaweed-block/core/storage/walstore.go index f993f86eda..fd4c67241c 100644 --- a/seaweed-block/core/storage/walstore.go +++ b/seaweed-block/core/storage/walstore.go @@ -344,6 +344,8 @@ func (s *WALStore) persistCheckpoint(highestLSN uint64) error { sbCopy := *s.sb sbCopy.WALCheckpointLSN = highestLSN + sbCopy.WALHead = s.wal.logicalHeadValue() + sbCopy.WALTail = s.wal.logicalTailValue() buf := newSimpleByteBuf() if _, err := sbCopy.writeTo(buf); err != nil { return fmt.Errorf("storage: encode superblock: %w", err) @@ -366,6 +368,8 @@ func (s *WALStore) persistCheckpoint(highestLSN uint64) error { } s.checkpointLSN = highestLSN s.sb.WALCheckpointLSN = highestLSN + s.sb.WALHead = sbCopy.WALHead + s.sb.WALTail = sbCopy.WALTail return nil } @@ -412,8 +416,15 @@ func (s *WALStore) Recover() (uint64, error) { s.dm.clear() res, err := recoverWAL(s.fd, s.sb, s.dm) if err != nil { + s.dm.clear() return 0, err } + if err := s.wal.restoreRecoveredBounds(res.WALHead, res.WALTail); err != nil { + s.dm.clear() + return 0, NewWALIntegrityFailure(err, "restore walstore recovery bounds") + } + s.sb.WALHead = res.WALHead + s.sb.WALTail = res.WALTail recoveredHead := s.checkpointLSN if res.HighestLSN > recoveredHead { recoveredHead = res.HighestLSN diff --git a/seaweed-block/core/storage/walstore_materialization_lifecycle_test.go b/seaweed-block/core/storage/walstore_materialization_lifecycle_test.go new file mode 100644 index 0000000000..b51ebfeef6 --- /dev/null +++ b/seaweed-block/core/storage/walstore_materialization_lifecycle_test.go @@ -0,0 +1,589 @@ +package storage + +import ( + "bytes" + "encoding/binary" + "errors" + "path/filepath" + "strings" + "sync" + "testing" + "time" +) + +func TestWALStoreSharedMaterializationLargeConcurrentLifecycle(t *testing.T) { + const ( + blockSize = 4096 + batchSize = 16 + ) + s, err := CreateWALStore(filepath.Join(t.TempDir(), "store.bin"), 512, blockSize) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + s.enableMultiBlockRecordsForTest(true) + s.enableSharedRecordMaterializationForTest(true) + t.Cleanup(func() { _ = s.Close() }) + + for base := uint32(0); base < 256; base += batchSize { + blocks := make([][]byte, batchSize) + for index := range blocks { + blocks[index] = makeBlock(blockSize, byte((base+uint32(index))%251+1)) + } + if _, err := s.WriteBatch(base, blocks); err != nil { + t.Fatal(err) + } + } + for lba := uint32(300); lba < 332; lba++ { + if _, err := s.Write(lba, makeBlock(blockSize, byte(lba%251+1))); err != nil { + t.Fatal(err) + } + } + if stable, err := s.Sync(); err != nil || stable != 288 { + t.Fatalf("initial Sync=%d err=%v want 288,nil", stable, err) + } + + firstExtentLock := &s.extentMu[0] + firstExtentLock.Lock() + flushDone := make(chan error, 1) + go func() { flushDone <- s.flusher.flushOnce() }() + waitForMaterializationRead(t, s, firstExtentLock) + + newZero := makeBlock(blockSize, 0xD0) + if _, err := s.Write(0, newZero); err != nil { + firstExtentLock.Unlock() + t.Fatal(err) + } + newBatch := make([][]byte, 8) + for index := range newBatch { + newBatch[index] = makeBlock(blockSize, byte(0xD8+index)) + } + if _, err := s.WriteBatch(8, newBatch); err != nil { + firstExtentLock.Unlock() + t.Fatal(err) + } + newThreeHundred := makeBlock(blockSize, 0xE3) + finalLSN, err := s.Write(300, newThreeHundred) + if err != nil { + firstExtentLock.Unlock() + t.Fatal(err) + } + if stable, err := s.Sync(); err != nil || stable != finalLSN { + firstExtentLock.Unlock() + t.Fatalf("concurrent Sync=%d err=%v want %d,nil", stable, err, finalLSN) + } + firstExtentLock.Unlock() + if err := <-flushDone; err != nil { + t.Fatal(err) + } + + if got := s.CheckpointLSN(); got != 288 { + t.Fatalf("first checkpoint=%d want 288", got) + } + _, tail, head := s.Boundaries() + if tail != 289 || head != finalLSN { + t.Fatalf("first tail/head=%d/%d want 289/%d", tail, head, finalLSN) + } + if got := s.dm.len(); got != 10 { + t.Fatalf("newer dirty entries after first cycle=%d want 10", got) + } + assertCurrentBlock(t, s, 0, newZero) + for index, want := range newBatch { + assertCurrentBlock(t, s, uint32(8+index), want) + } + assertCurrentBlock(t, s, 300, newThreeHundred) + + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + if got := s.CheckpointLSN(); got != finalLSN || s.dm.len() != 0 { + t.Fatalf("final checkpoint/dirty=%d/%d want %d/0", + got, s.dm.len(), finalLSN) + } + assertExtentBlock(t, s, 0, newZero) + for index, want := range newBatch { + assertExtentBlock(t, s, uint32(8+index), want) + } + assertExtentBlock(t, s, 300, newThreeHundred) + + got := s.FlusherInstrumentation() + if got.CyclesSucceeded != 2 || + got.SnapshotEntries != 298 || + got.SnapshotUniqueWALRecords != 51 || + got.WALRecordReadOps != 51 || + got.MaterializationRecordReuseHits != 247 || + got.SupersededEntries != 10 { + t.Fatalf("cycles/entries/unique/reads/reuse/superseded=%d/%d/%d/%d/%d/%d want 2/298/51/51/247/10", + got.CyclesSucceeded, got.SnapshotEntries, + got.SnapshotUniqueWALRecords, got.WALRecordReadOps, + got.MaterializationRecordReuseHits, got.SupersededEntries) + } +} + +func TestWALStoreSharedMaterializationCannotOverwriteDirectBase(t *testing.T) { + const blockSize = 4096 + path := filepath.Join(t.TempDir(), "store.bin") + s, err := CreateWALStore(path, 64, blockSize) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + s.enableMultiBlockRecordsForTest(true) + s.enableSharedRecordMaterializationForTest(true) + + blocks := make([][]byte, 16) + for index := range blocks { + blocks[index] = makeBlock(blockSize, byte(0x40+index)) + } + if _, err := s.WriteBatch(32, blocks); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + + firstExtentLock := &s.extentMu[32%uint32(len(s.extentMu))] + firstExtentLock.Lock() + flushDone := make(chan error, 1) + go func() { flushDone <- s.flusher.flushOnce() }() + waitForMaterializationRead(t, s, firstExtentLock) + + base := makeBlock(blockSize, 0xB5) + if err := s.WriteExtentDirect(37, base); err != nil { + firstExtentLock.Unlock() + t.Fatal(err) + } + firstExtentLock.Unlock() + if err := <-flushDone; err != nil { + t.Fatal(err) + } + if got := s.CheckpointLSN(); got != 16 { + t.Fatalf("checkpoint=%d want 16", got) + } + if got := s.FlusherInstrumentation(); got.WALRecordReadOps != 1 || + got.MaterializationRecordReuseHits != 15 || + got.SupersededEntries != 1 { + t.Fatalf("reads/reuse/superseded=%d/%d/%d want 1/15/1", + got.WALRecordReadOps, got.MaterializationRecordReuseHits, + got.SupersededEntries) + } + assertCurrentBlock(t, s, 37, base) + if err := s.Close(); err != nil { + t.Fatal(err) + } + + reopened, err := OpenWALStore(path) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = reopened.Close() }) + if _, err := reopened.Recover(); err != nil { + t.Fatal(err) + } + assertCurrentBlock(t, reopened, 37, base) +} + +func TestWALStoreSharedMaterializationRespectsRecycleFloorAcrossRestart(t *testing.T) { + const blockSize = 4096 + path := filepath.Join(t.TempDir(), "store.bin") + s, err := CreateWALStore(path, 32, blockSize) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + s.enableMultiBlockRecordsForTest(true) + s.enableSharedRecordMaterializationForTest(true) + + blocks := make([][]byte, 16) + for index := range blocks { + blocks[index] = makeBlock(blockSize, byte(0x60+index)) + } + if _, err := s.WriteBatch(0, blocks); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + s.SetRecycleFloorSource(&fakeRecycleFloorSource{floor: 8, anyActive: true}) + if err := s.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + if got := s.CheckpointLSN(); got != 8 { + t.Fatalf("pinned checkpoint=%d want 8", got) + } + if got := s.wal.logicalTailValue(); got != 0 { + t.Fatalf("physical WAL tail under pin=%d want 0", got) + } + _, tail, head := s.Boundaries() + if tail != 1 || head != 16 { + t.Fatalf("logical tail/head under pin=%d/%d want 1/16", tail, head) + } + var retained []RecoveryEntry + if err := s.ScanLBAs(9, func(entry RecoveryEntry) error { + retained = append(retained, entry) + return nil + }); err != nil { + t.Fatal(err) + } + if len(retained) != 8 { + t.Fatalf("retained entries above pin=%d want 8", len(retained)) + } + crashGeometryTestStore(t, s) + + reopened, err := OpenWALStore(path) + if err != nil { + t.Fatal(err) + } + reopened.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = reopened.Close() }) + if recovered, err := reopened.Recover(); err != nil || recovered != 16 { + t.Fatalf("Recover=%d err=%v want 16,nil", recovered, err) + } + wantRecoveredHead := uint64(walEntryHeaderSize + 16*blockSize) + if tail, head := reopened.wal.logicalTailValue(), reopened.wal.logicalHeadValue(); tail != 0 || head != wantRecoveredHead { + t.Fatalf("recovered physical tail/head=%d/%d want 0/%d", + tail, head, wantRecoveredHead) + } + reopened.enableSharedRecordMaterializationForTest(true) + newBlock := makeBlock(blockSize, 0xF1) + newLSN, err := reopened.Write(20, newBlock) + if err != nil { + t.Fatal(err) + } + newEntry := snapshotEntriesByLBA(reopened.dm.snapshot())[20] + if newEntry.WALOffset != wantRecoveredHead { + t.Fatalf("post-recovery append offset=%d want %d", + newEntry.WALOffset, wantRecoveredHead) + } + if _, err := reopened.Sync(); err != nil { + t.Fatal(err) + } + if err := reopened.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + if got := reopened.CheckpointLSN(); got != newLSN { + t.Fatalf("checkpoint after recovery=%d want %d", got, newLSN) + } + got := reopened.FlusherInstrumentation() + if got.WALRecordReadOps != 2 || got.MaterializationRecordReuseHits != 7 { + t.Fatalf("recovered reads/reuse=%d/%d want 2/7", + got.WALRecordReadOps, got.MaterializationRecordReuseHits) + } + for index, want := range blocks { + assertCurrentBlock(t, reopened, uint32(index), want) + } + assertCurrentBlock(t, reopened, 20, newBlock) +} + +func TestWALStoreSharedMaterializationCloseLifecycle(t *testing.T) { + t.Run("final flush", func(t *testing.T) { + const blockSize = 4096 + path := filepath.Join(t.TempDir(), "store.bin") + s, err := CreateWALStore(path, 32, blockSize) + if err != nil { + t.Fatal(err) + } + replaceFlusherForTest(s, time.Hour) + s.enableMultiBlockRecordsForTest(true) + s.enableSharedRecordMaterializationForTest(true) + blocks := make([][]byte, 16) + for index := range blocks { + blocks[index] = makeBlock(blockSize, byte(0x20+index)) + } + if _, err := s.WriteBatch(0, blocks); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + if err := s.Close(); err != nil { + t.Fatal(err) + } + got := s.FlusherInstrumentation() + if got.CyclesSucceeded != 1 || got.WALRecordReadOps != 1 || + got.MaterializationRecordReuseHits != 15 { + t.Fatalf("close cycles/reads/reuse=%d/%d/%d want 1/1/15", + got.CyclesSucceeded, got.WALRecordReadOps, + got.MaterializationRecordReuseHits) + } + + reopened, err := OpenWALStore(path) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = reopened.Close() }) + if _, err := reopened.Recover(); err != nil { + t.Fatal(err) + } + if got := reopened.CheckpointLSN(); got != 16 { + t.Fatalf("reopened checkpoint=%d want 16", got) + } + for index, want := range blocks { + assertCurrentBlock(t, reopened, uint32(index), want) + } + }) + + t.Run("checkpoint failure recovers", func(t *testing.T) { + const blockSize = 4096 + path := filepath.Join(t.TempDir(), "store.bin") + s, err := CreateWALStore(path, 32, blockSize) + if err != nil { + t.Fatal(err) + } + replaceFlusherForTest(s, time.Hour) + s.enableMultiBlockRecordsForTest(true) + s.enableSharedRecordMaterializationForTest(true) + blocks := make([][]byte, 16) + for index := range blocks { + blocks[index] = makeBlock(blockSize, byte(0x90+index)) + } + if _, err := s.WriteBatch(0, blocks); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + s.writeSuperblockMetadata = func([]byte) error { + return errors.New("injected shared checkpoint failure") + } + err = s.Close() + if err == nil || !strings.Contains(err.Error(), "injected shared checkpoint failure") { + t.Fatalf("Close error=%v want injected failure", err) + } + if got := s.CheckpointLSN(); got != 0 { + t.Fatalf("checkpoint after failed Close=%d want 0", got) + } + if got := s.wal.logicalTailValue(); got != 0 { + t.Fatalf("physical WAL tail after failed Close=%d want 0", got) + } + if s.fd != nil { + t.Fatal("failed Close left file open") + } + + reopened, err := OpenWALStore(path) + if err != nil { + t.Fatal(err) + } + reopened.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = reopened.Close() }) + if recovered, err := reopened.Recover(); err != nil || recovered != 16 { + t.Fatalf("Recover=%d err=%v want 16,nil", recovered, err) + } + reopened.enableSharedRecordMaterializationForTest(true) + if err := reopened.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + if got := reopened.CheckpointLSN(); got != 16 { + t.Fatalf("recovered checkpoint=%d want 16", got) + } + for index, want := range blocks { + assertCurrentBlock(t, reopened, uint32(index), want) + } + }) +} + +func TestWALStoreRecoverRejectsOverflowingBatchGeometry(t *testing.T) { + tests := []struct { + name string + mutate func([]byte) + }{ + { + name: "reserved multiplication overflow", + mutate: func(record []byte) { + binary.LittleEndian.PutUint64(record[8:16], (uint64(1)<<52)+3) + }, + }, + { + name: "LSN range overflow", + mutate: func(record []byte) { + binary.LittleEndian.PutUint64(record[0:8], ^uint64(0)-1) + }, + }, + { + name: "reserved length mismatch", + mutate: func(record []byte) { + binary.LittleEndian.PutUint64(record[8:16], 2) + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + const blockSize = 4096 + path := filepath.Join(t.TempDir(), "store.bin") + s, err := CreateWALStore(path, 16, blockSize) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + s.enableMultiBlockRecordsForTest(true) + if _, err := s.WriteBatch(4, [][]byte{ + makeBlock(blockSize, 0xA1), + makeBlock(blockSize, 0xA2), + makeBlock(blockSize, 0xA3), + }); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + entry := snapshotEntriesByLBA(s.dm.snapshot())[4] + rewriteRecordForTest( + t, s, entry, int64(s.sb.WALOffset+entry.WALOffset), tt.mutate, + ) + crashGeometryTestStore(t, s) + + reopened, err := OpenWALStore(path) + if err != nil { + t.Fatal(err) + } + reopened.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = reopened.Close() }) + recovered, recoverErr := reopened.Recover() + if recovered != 0 || + !errors.Is(recoverErr, ErrWALIntegrityFault) { + t.Fatalf("Recover=%d err=%v want 0,WALIntegrity", recovered, recoverErr) + } + if got := reopened.dm.len(); got != 0 { + t.Fatalf("dirty entries from malformed batch=%d want 0", got) + } + if got := reopened.NextLSN(); got != 1 { + t.Fatalf("next LSN after malformed batch=%d want 1", got) + } + }) + } +} + +func TestWALStoreRecoverReconstructsLegacyWrappedRetainedWindow(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) + } + + high := makeBlock(blockSize, 0xA4) + if _, err := s.Write(20, high); err != nil { + t.Fatal(err) + } + s.enableMultiBlockRecordsForTest(true) + low := [][]byte{ + makeBlock(blockSize, 0xB5), + makeBlock(blockSize, 0xB6), + } + if _, err := s.WriteBatch(24, low); err != nil { + t.Fatal(err) + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + entries := snapshotEntriesByLBA(s.dm.snapshot()) + if entries[20].WALOffset != uint64(3*(walEntryHeaderSize+blockSize)) || + entries[24].WALOffset != 0 { + t.Fatalf("high/low offsets=%d/%d want %d/0", + entries[20].WALOffset, entries[24].WALOffset, + 3*(walEntryHeaderSize+blockSize)) + } + + legacy := *s.sb + legacy.WALHead = 0 + legacy.WALTail = 0 + buf := newSimpleByteBuf() + if _, err := legacy.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) + } + crashGeometryTestStore(t, s) + + reopened, err := OpenWALStore(path) + if err != nil { + t.Fatal(err) + } + reopened.DisableAutoFlushForRecoveryTest() + t.Cleanup(func() { _ = reopened.Close() }) + if recovered, err := reopened.Recover(); err != nil || recovered != 6 { + t.Fatalf("Recover=%d err=%v want 6,nil", recovered, err) + } + wantTail := entries[20].WALOffset + wantHead := walSize + entries[24].RecordSize + if tail, head := reopened.wal.logicalTailValue(), reopened.wal.logicalHeadValue(); tail != wantTail || head != wantHead { + t.Fatalf("recovered wrapped tail/head=%d/%d want %d/%d", + tail, head, wantTail, wantHead) + } + assertCurrentBlock(t, reopened, 20, high) + assertCurrentBlock(t, reopened, 24, low[0]) + assertCurrentBlock(t, reopened, 25, low[1]) + + reopened.enableSharedRecordMaterializationForTest(true) + postRecovery := makeBlock(blockSize, 0xC7) + finalLSN, err := reopened.Write(30, postRecovery) + if err != nil { + t.Fatal(err) + } + postEntry := snapshotEntriesByLBA(reopened.dm.snapshot())[30] + if postEntry.WALOffset != entries[24].RecordSize { + t.Fatalf("post-recovery append offset=%d want %d", + postEntry.WALOffset, entries[24].RecordSize) + } + if _, err := reopened.Sync(); err != nil { + t.Fatal(err) + } + if err := reopened.flusher.flushOnce(); err != nil { + t.Fatal(err) + } + if got := reopened.CheckpointLSN(); got != finalLSN { + t.Fatalf("checkpoint=%d want %d", got, finalLSN) + } + if got := reopened.dm.len(); got != 0 { + t.Fatalf("dirty entries after wrapped flush=%d want 0", got) + } + wantFinalBoundary := wantHead + uint64(walEntryHeaderSize+blockSize) + if tail, head := reopened.wal.logicalTailValue(), reopened.wal.logicalHeadValue(); tail != wantFinalBoundary || head != wantFinalBoundary { + t.Fatalf("final wrapped tail/head=%d/%d want %d/%d", + tail, head, wantFinalBoundary, wantFinalBoundary) + } + assertCurrentBlock(t, reopened, 20, high) + assertCurrentBlock(t, reopened, 24, low[0]) + assertCurrentBlock(t, reopened, 25, low[1]) + assertCurrentBlock(t, reopened, 30, postRecovery) +} + +func waitForMaterializationRead(t *testing.T, s *WALStore, lock *sync.RWMutex) { + t.Helper() + deadline := time.Now().Add(2 * time.Second) + for s.FlusherInstrumentation().WALRecordReadOps == 0 { + if time.Now().After(deadline) { + lock.Unlock() + t.Fatal("flusher did not materialize the first record") + } + time.Sleep(time.Millisecond) + } +} + +func assertCurrentBlock(t *testing.T, s *WALStore, lba uint32, want []byte) { + t.Helper() + got, err := s.Read(lba) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, want) { + t.Fatalf("current LBA %d mismatch", lba) + } +} diff --git a/seaweed-block/internal/docs/current-plan.md b/seaweed-block/internal/docs/current-plan.md index 950a825f15..43302e1a06 100644 --- a/seaweed-block/internal/docs/current-plan.md +++ b/seaweed-block/internal/docs/current-plan.md @@ -162,6 +162,19 @@ on `7d09924`: seven focused and CGO race tests each passed 20 repetitions, ### D4. Concurrency, Recovery, And Lifecycle Equivalence +Implementation status: complete locally; Linux exact-commit race, SIGKILL, +recovery, and replication gates remain pending. Candidate-on lifecycle fixtures +cover large concurrent snapshots, direct BASE ownership, recycle-floor +recovery, Close final flush/failure, and malformed batch recovery. + +D4 exposed and fixed four recovery-contract gaps rather than weakening the +fixtures: a checkpoint inside one multi-block record now replays only its +uncheckpointed suffix; valid-CRC malformed batch geometry returns typed +`WALIntegrity`; recovery restores byte-based writer head/tail before any new +append; and legacy `head==tail` metadata can reconstruct a retained window that +crosses ring wrap. Checkpoint metadata now carries conservative byte boundaries +in its existing write/fsync without adding a new disk field or sync. + - Run foreground Write/WriteBatch and repeated same-LBA overwrite during large materialization cycles. - Exercise direct BASE overlap, pressure wakeups, recycle-floor pins, Sync, diff --git a/seaweed-block/internal/docs/qa-assignments/phase172-d4-materialization-lifecycle-qa.md b/seaweed-block/internal/docs/qa-assignments/phase172-d4-materialization-lifecycle-qa.md new file mode 100644 index 0000000000..115048ba7e --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase172-d4-materialization-lifecycle-qa.md @@ -0,0 +1,81 @@ +# Phase 172 D4 Materialization Lifecycle QA + +Validate concurrency, recovery, lifecycle, and replication equivalence with +shared-record materialization actually enabled in the candidate fixtures. + +## Source And Command + +Use the exact assigned commit from a clean Linux worktree: + +```bash +bash scripts/run-phase172-materialization-lifecycle-gate.sh +``` + +Do not reduce the 20 candidate repetitions, 20 CGO race repetitions, or 10 +existing-equivalence repetitions. + +## Required Evidence + +```text +phase172_materialization_lifecycle_status=ok +candidate_repeat_20=pass +candidate_race_repeat_20=pass +existing_equivalence_repeat_10=pass +large_snapshot_concurrent_write_batch=pass +direct_base_overlap=pass +recycle_floor_partial_batch_recovery=pass +close_final_flush_and_failure_recovery=pass +overflow_batch_recovery_fails_closed=pass +legacy_wrapped_retained_window_reconstructed=pass +checkpoint_crash_windows=pass +checkpoint_sigkill_windows=pass +sync_close_lifecycle=pass +scan_lbas_concurrent_live_write=pass +recycle_pin_contract=pass +storage_regression=pass +recovery_regression=pass +replication_regression=pass +replication_component_regression=pass +lifecycle_vet=pass +rf1_local_storage_contract=pass +rf3_sync_quorum_component_contract=pass +checkpoint_tail_dirty_consistency=pass +candidate_disk_format_unchanged=true +recovery_branch_added=false +external_selector_added=false +d5_performance_gate_eligible=true +``` + +Review the large-snapshot fixture rather than accepting only the terminal key: +the first candidate cycle must process 288 entries from 48 physical records, +retain 10 newer ordinary/batch overwrites, and checkpoint only the old frontier. +The second cycle must publish those 10 entries and finish with no dirty state. + +The recycle-floor fixture is a regression for a D4 live finding. A checkpoint +at LSN 8 inside a physical batch spanning LSN 1 through 16 must retain the WAL, +reopen at frontier 16, replay only LSN 9 through 16 into the dirty map, then +materialize that suffix with one physical read and seven reuse hits. A malformed +batch whose `Reserved * blockSize` would overflow must not publish any recovery +frontier. + +The legacy wrapped-window fixture must force persisted byte head/tail to zero +while retaining an older high-offset record and newer offset-zero batch. +Recovery must find both, reconstruct `tail=highOffset` and +`head=WALSize+lowEnd`, and append the next record at `lowEnd` without +overwriting either retained record. + +Confirm that direct BASE remains authoritative, Close failure keeps checkpoint +and physical tail unchanged, and the existing SIGKILL, recovery, catch-up, +rebuild, and RF3 sync-quorum suites remain green. No new disk format, recovery +branch, or external selector is allowed. + +## Deliverable + +Write: + +```text +internal/docs/qa-assignments/phase172-d4-materialization-lifecycle-qa-signoff.md +``` + +Include exact commit, all terminal evidence, artifact SHA-256, findings, and +cleanup. Do not patch product or gate code during QA. diff --git a/seaweed-block/scripts/run-phase172-materialization-lifecycle-gate.sh b/seaweed-block/scripts/run-phase172-materialization-lifecycle-gate.sh new file mode 100644 index 0000000000..57ed9a718d --- /dev/null +++ b/seaweed-block/scripts/run-phase172-materialization-lifecycle-gate.sh @@ -0,0 +1,117 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT="${1:-$(pwd)}" +ARTIFACT_DIR="${SW_BLOCK_ARTIFACT_DIR:-${ROOT}/results/phase172-materialization-lifecycle-gate}" +SUMMARY="${ARTIFACT_DIR}/phase172-materialization-lifecycle-summary.txt" + +mkdir -p "${ARTIFACT_DIR}" +: >"${SUMMARY}" + +write_summary() { + echo "$*" | tee -a "${SUMMARY}" >/dev/null +} + +cd "${ROOT}" +write_summary "phase172_materialization_lifecycle_status=running" +write_summary "git_sha=$(git rev-parse HEAD)" +git_dirty="$([[ -n "$(git status --porcelain)" ]] && echo true || echo false)" +write_summary "git_dirty=${git_dirty}" +if [[ "${git_dirty}" != "false" ]]; then + echo "Phase 172 D4 requires a clean source worktree" >&2 + exit 1 +fi +write_summary "go_version=$(go version | tr ' ' '_')" +write_summary "kernel=$(uname -srvmo | tr ' ' '_')" + +candidate_tests=( + TestWALStoreSharedMaterializationLargeConcurrentLifecycle + TestWALStoreSharedMaterializationCannotOverwriteDirectBase + TestWALStoreSharedMaterializationRespectsRecycleFloorAcrossRestart + TestWALStoreSharedMaterializationCloseLifecycle + TestWALStoreRecoverRejectsOverflowingBatchGeometry + TestWALStoreRecoverReconstructsLegacyWrappedRetainedWindow +) +candidate_regex="^($(IFS='|'; echo "${candidate_tests[*]}"))$" +candidate_log="${ARTIFACT_DIR}/candidate-lifecycle-repeat.log" +: >"${candidate_log}" +for test_name in "${candidate_tests[@]}"; do + go test ./core/storage -run "^${test_name}$" -count=20 -v \ + >>"${candidate_log}" 2>&1 + write_summary "${test_name}=pass" +done +if grep -Eq -- '--- SKIP|no tests to run' "${candidate_log}"; then + echo "candidate lifecycle gate contains a skipped or missing test" >&2 + exit 1 +fi +write_summary "candidate_repeat_20=pass" +write_summary "large_snapshot_concurrent_write_batch=pass" +write_summary "direct_base_overlap=pass" +write_summary "recycle_floor_partial_batch_recovery=pass" +write_summary "close_final_flush_and_failure_recovery=pass" +write_summary "overflow_batch_recovery_fails_closed=pass" +write_summary "legacy_wrapped_retained_window_reconstructed=pass" + +go test -race ./core/storage -run "${candidate_regex}" -count=20 -v \ + >"${ARTIFACT_DIR}/candidate-lifecycle-race-repeat.log" 2>&1 +if grep -Eq -- '--- SKIP|no tests to run' "${ARTIFACT_DIR}/candidate-lifecycle-race-repeat.log"; then + echo "candidate race gate contains a skipped or missing test" >&2 + exit 1 +fi +write_summary "candidate_race_repeat_20=pass" + +equivalence_tests=( + TestCheckpointPublicationCrashWindowsRemainRecoverable + TestWALStoreCheckpointSIGKILLCrashWindows + TestWALStoreCloseWaitsForInflightSync + TestWALStoreCloseReturnsFinalMetadataFailure + TestRunningFlusherCannotOverwriteDirectBase + TestWalstoreRecovery_ScanLBAs_ConcurrentLiveWrite_Safe + TestWALStore_RecycleGate_SourceActive_ClampsAtFloor +) +equivalence_log="${ARTIFACT_DIR}/existing-equivalence-repeat.log" +: >"${equivalence_log}" +for test_name in "${equivalence_tests[@]}"; do + go test ./core/storage -run "^${test_name}$" -count=10 -v \ + >>"${equivalence_log}" 2>&1 + write_summary "${test_name}=pass" +done +if grep -Eq -- '--- SKIP|no tests to run' "${equivalence_log}"; then + echo "existing equivalence gate contains a skipped or missing test" >&2 + exit 1 +fi +write_summary "existing_equivalence_repeat_10=pass" +write_summary "checkpoint_crash_windows=pass" +write_summary "checkpoint_sigkill_windows=pass" +write_summary "sync_close_lifecycle=pass" +write_summary "scan_lbas_concurrent_live_write=pass" +write_summary "recycle_pin_contract=pass" + +go test ./core/storage -count=1 \ + >"${ARTIFACT_DIR}/storage-regression.log" 2>&1 +write_summary "storage_regression=pass" + +go test ./core/recovery -count=1 \ + >"${ARTIFACT_DIR}/recovery-regression.log" 2>&1 +write_summary "recovery_regression=pass" + +go test ./core/replication -count=1 \ + >"${ARTIFACT_DIR}/replication-regression.log" 2>&1 +write_summary "replication_regression=pass" + +go test ./core/replication/component -count=1 \ + >"${ARTIFACT_DIR}/replication-component-regression.log" 2>&1 +write_summary "replication_component_regression=pass" + +go vet ./core/storage ./core/recovery ./core/replication ./core/replication/component \ + >"${ARTIFACT_DIR}/lifecycle-vet.log" 2>&1 +write_summary "lifecycle_vet=pass" + +write_summary "rf1_local_storage_contract=pass" +write_summary "rf3_sync_quorum_component_contract=pass" +write_summary "checkpoint_tail_dirty_consistency=pass" +write_summary "candidate_disk_format_unchanged=true" +write_summary "recovery_branch_added=false" +write_summary "external_selector_added=false" +write_summary "d5_performance_gate_eligible=true" +write_summary "phase172_materialization_lifecycle_status=ok"