mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 10:07:28 +01:00
Merge pull request #155 from seaweedfs/fix/issue51-walstore-midhistory
storage: detect WAL holes (warning only) for issue #51
This commit is contained in:
commit
515a092dc9
12 files changed
+832
-15
No files matched your search
@@ -0,0 +1,207 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
|
||||
"github.com/seaweedfs/seaweed-block/core/host/volume"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage/smartwal"
|
||||
)
|
||||
|
||||
// Issue #51: a real SmartWAL WAL-slot corruption (the issue's mutation:
|
||||
// the last byte of a committed record's 32-byte slot, i.e. its record CRC)
|
||||
// must not let the volume start Ready.
|
||||
|
||||
// writeSmartWAL writes the given LBAs in order through the real provider,
|
||||
// syncs and closes it, and returns the store's path.
|
||||
func writeSmartWAL(t *testing.T, cfg durable.ProviderConfig, lbas []uint32) string {
|
||||
t.Helper()
|
||||
dp, err := durable.NewDurableProvider(cfg, healthyView{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
st, err := dp.EnsureStorage("v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for i, lba := range lbas {
|
||||
data := make([]byte, 4096)
|
||||
data[0], data[1] = byte(0xA0+i), byte(lba)
|
||||
if _, err := st.Write(lba, data); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := st.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := dp.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return filepath.Join(cfg.StorageRoot, "v1.bin")
|
||||
}
|
||||
|
||||
// corruptSlotCRC flips the last byte (the record CRC) of the newest slot
|
||||
// recorded for lba, as the issue's QA mutation did (target_record_offset
|
||||
// +31).
|
||||
func corruptSlotCRC(t *testing.T, path string, lba uint32) {
|
||||
t.Helper()
|
||||
_, records, err := smartwal.InspectRecords(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var off int64 = -1
|
||||
var lsn uint64
|
||||
for _, r := range records {
|
||||
if r.LBA == lba && r.LSN >= lsn {
|
||||
off, lsn = r.Offset, r.LSN
|
||||
}
|
||||
}
|
||||
if off < 0 {
|
||||
t.Fatalf("no record for LBA %d", lba)
|
||||
}
|
||||
f, err := os.OpenFile(path, os.O_RDWR, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer f.Close()
|
||||
b := make([]byte, 1)
|
||||
if _, err := f.ReadAt(b, off+31); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b[0] ^= 0xFF
|
||||
if _, err := f.WriteAt(b, off+31); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func startAfterCorruption(t *testing.T, cfg durable.ProviderConfig) (durableStartupOutcome, *spyHost) {
|
||||
t.Helper()
|
||||
dp, err := durable.NewDurableProvider(cfg, healthyView{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = dp.Close() })
|
||||
h := &spyHost{}
|
||||
outcome, evidence, err := openAndRecoverDurable(dp, h, "v1", 5*time.Second)
|
||||
t.Logf("outcome=%v reported=%v evidence=%q err=%v", outcome, h.reported, evidence, err)
|
||||
return outcome, h
|
||||
}
|
||||
|
||||
// The issue's schedule: LBA 0 was written twice; the newer record's slot
|
||||
// is corrupted, so recovery drops it as torn and falls back to the older
|
||||
// record, whose CRC no longer matches the extent. Current main fails
|
||||
// closed (85d93753): wal_corrupt, readiness blocked.
|
||||
func TestDurableStartup_Issue51_CorruptNewerSlotIsWALCorrupt(t *testing.T) {
|
||||
cfg := durable.ProviderConfig{Impl: durable.ImplSmartWAL, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: 16}
|
||||
path := writeSmartWAL(t, cfg, []uint32{0, 1, 2, 0})
|
||||
corruptSlotCRC(t, path, 0)
|
||||
outcome, h := startAfterCorruption(t, cfg)
|
||||
if outcome != durableStartupFaulted || len(h.reported) != 1 || h.reported[0] != volume.UnhealthyWALCorrupt || len(h.blocked) == 0 {
|
||||
t.Fatalf("corrupt newer slot: outcome=%v reported=%v blocked=%v; want faulted, wal_corrupt, readiness blocked", outcome, h.reported, h.blocked)
|
||||
}
|
||||
}
|
||||
|
||||
// claude05's ruling (A), 06:47Z: detection only for smartwal too. A
|
||||
// corrupted committed slot with later valid records starts as before
|
||||
// (ready), and the durable status carries the counted warning.
|
||||
func TestDurableStartup_Issue51_SmartWALHoleIsAWarningNotAnOutage(t *testing.T) {
|
||||
cfg := durable.ProviderConfig{Impl: durable.ImplSmartWAL, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: 16}
|
||||
path := writeSmartWAL(t, cfg, []uint32{0, 1, 2, 3})
|
||||
corruptSlotCRC(t, path, 1) // LSN 2; LSN 3 and 4 stay valid
|
||||
dp, err := durable.NewDurableProvider(cfg, healthyView{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer dp.Close()
|
||||
h := &spyHost{}
|
||||
outcome, evidence, err := openAndRecoverDurable(dp, h, "v1", 5*time.Second)
|
||||
if outcome != durableStartupReady || len(h.reported) != 0 {
|
||||
t.Fatalf("smartwal hole: outcome=%v reported=%v evidence=%q err=%v; want ready", outcome, h.reported, evidence, err)
|
||||
}
|
||||
warned := false
|
||||
for _, st := range dp.DurableStatuses() {
|
||||
for _, w := range st.Warnings {
|
||||
if strings.HasPrefix(w, storage.WarningWALHoleSuspected+":") && st.HolesSuspected == 1 {
|
||||
warned = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if !warned {
|
||||
t.Fatalf("durable statuses %+v; want the counted %s warning", dp.DurableStatuses(), storage.WarningWALHoleSuspected)
|
||||
}
|
||||
}
|
||||
|
||||
// Control: a torn tail (the newest slot bad, nothing valid after it)
|
||||
// still recovers: a power loss is not an outage.
|
||||
func TestDurableStartup_Issue51_SmartWALTornTailRecovers(t *testing.T) {
|
||||
cfg := durable.ProviderConfig{Impl: durable.ImplSmartWAL, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: 16}
|
||||
path := writeSmartWAL(t, cfg, []uint32{0, 1, 2})
|
||||
corruptSlotCRC(t, path, 2) // LSN 3, the newest
|
||||
outcome, h := startAfterCorruption(t, cfg)
|
||||
if outcome != durableStartupReady || len(h.reported) != 0 {
|
||||
t.Fatalf("torn tail: outcome=%v reported=%v; want ready", outcome, h.reported)
|
||||
}
|
||||
}
|
||||
|
||||
// walstore interim (claude05's ruling 06:14Z): the same mid-history
|
||||
// corruption on a walstore volume does not become an outage: startup is
|
||||
// ready, and the durable status carries the typed warning.
|
||||
func TestDurableStartup_Issue51_WALStoreHoleIsAWarningNotAnOutage(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
cfg := durable.ProviderConfig{Impl: durable.ImplWALStore, StorageRoot: root, BlockSize: 4096, NumBlocks: 16}
|
||||
path := filepath.Join(root, "v1.bin")
|
||||
// A crashed walstore: entries synced, nothing checkpointed (the file
|
||||
// as it is right after Sync; a clean close would checkpoint).
|
||||
s, err := storage.CreateWALStore(path, 16, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
for i := uint32(0); i < 4; i++ {
|
||||
data := make([]byte, 4096)
|
||||
data[0] = byte(0xD0 + i)
|
||||
if _, err := s.Write(i, data); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
crashed, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = s.Close()
|
||||
// Corrupt a payload byte of the second entry (walstore's WAL starts at
|
||||
// 4096; a one-block entry is 38+4096 bytes).
|
||||
crashed[4096+(38+4096)+38+100] ^= 0xFF
|
||||
if err := os.WriteFile(path, crashed, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dp, err := durable.NewDurableProvider(cfg, healthyView{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer dp.Close()
|
||||
h := &spyHost{}
|
||||
outcome, evidence, err := openAndRecoverDurable(dp, h, "v1", 5*time.Second)
|
||||
if outcome != durableStartupReady || len(h.reported) != 0 {
|
||||
t.Fatalf("walstore hole: outcome=%v reported=%v evidence=%q err=%v; want ready (no outage)", outcome, h.reported, evidence, err)
|
||||
}
|
||||
warned := false
|
||||
for _, st := range dp.DurableStatuses() {
|
||||
for _, w := range st.Warnings {
|
||||
if strings.HasPrefix(w, storage.WarningWALHoleSuspected+":") {
|
||||
warned = st.HolesSuspected == 1
|
||||
}
|
||||
}
|
||||
}
|
||||
if !warned {
|
||||
t.Fatalf("durable statuses %+v; want the %s warning, counted once", dp.DurableStatuses(), storage.WarningWALHoleSuspected)
|
||||
}
|
||||
}
|
||||
@@ -228,6 +228,11 @@ type VolumeStatus struct {
|
||||
// Chunk is the chunk layer's state and cut counters; walstore-chunk
|
||||
// volumes only.
|
||||
Chunk *ChunkStatus
|
||||
// Warnings are the store's typed recovery warnings (e.g.
|
||||
// wal_hole_suspected, issue #51); they do not change readiness.
|
||||
// HolesSuspected counts the recoveries that found a WAL hole.
|
||||
Warnings []string `json:",omitempty"`
|
||||
HolesSuspected uint64 `json:",omitempty"`
|
||||
}
|
||||
|
||||
// ChunkStatus is one walstore-chunk volume's chunk layer (B9 7.2-7.3).
|
||||
|
||||
@@ -275,6 +275,14 @@ func (b *StorageBackend) durableStatus(volumeID, path, impl string) VolumeStatus
|
||||
b.mu.Unlock()
|
||||
durableLSN, retainedLSN, headLSN := b.storage.Boundaries()
|
||||
evidence, _ := b.opEvidence.Load().(string)
|
||||
var warnings []string
|
||||
var holes uint64
|
||||
if w, ok := b.storage.(storage.RecoveryWarner); ok {
|
||||
warnings = w.RecoveryWarnings()
|
||||
}
|
||||
if c, ok := b.storage.(interface{ HolesSuspected() uint64 }); ok {
|
||||
holes = c.HolesSuspected()
|
||||
}
|
||||
writeProfile := b.profile.snapshot()
|
||||
if instrumented, ok := b.storage.(storage.WriteInstrumented); ok {
|
||||
storageProfile := instrumented.WriteInstrumentation()
|
||||
@@ -303,6 +311,8 @@ func (b *StorageBackend) durableStatus(volumeID, path, impl string) VolumeStatus
|
||||
writeProfile.DirtyMapUpdateDurationNanos = storageProfile.DirtyMapUpdateDurationNanos
|
||||
}
|
||||
return VolumeStatus{
|
||||
Warnings: warnings,
|
||||
HolesSuspected: holes,
|
||||
VolumeID: volumeID,
|
||||
Path: path,
|
||||
Impl: impl,
|
||||
|
||||
@@ -196,6 +196,10 @@ type StatusProjection struct {
|
||||
// CatchUp shows a supporting replica's catch-up progress while it is
|
||||
// not yet replica_ready; it is visible without being an alert.
|
||||
CatchUp *CatchUpStatus `json:",omitempty"`
|
||||
// Warnings are the durable store's typed recovery warnings (e.g.
|
||||
// wal_hole_suspected, issue #51). Visible, not an alert: they do not
|
||||
// change Healthy or the frontend's readiness.
|
||||
Warnings []string `json:",omitempty"`
|
||||
}
|
||||
|
||||
// CatchUpStatus is a supporting replica's catch-up state.
|
||||
@@ -477,7 +481,15 @@ func (s *StatusServer) statusProjection() StatusProjection {
|
||||
s.mu.Lock()
|
||||
p.Healthy = p.Healthy && !s.nvmePending
|
||||
p.FrontendPrimaryReady = p.FrontendPrimaryReady && !s.nvmePending
|
||||
src := s.durableSource
|
||||
s.mu.Unlock()
|
||||
if src != nil { // outside s.mu: the provider takes its own lock
|
||||
for _, st := range src.DurableStatuses() {
|
||||
if st.VolumeID == p.VolumeID {
|
||||
p.Warnings = append(p.Warnings, st.Warnings...)
|
||||
}
|
||||
}
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
package volume
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/engine"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
|
||||
)
|
||||
|
||||
// Issue #51 (walstore interim): the durable store's typed recovery warning
|
||||
// is visible on /status and does not change Healthy or readiness.
|
||||
func TestStatusServer_StatusCarriesRecoveryWarningsWithoutChangingHealth(t *testing.T) {
|
||||
t.Run("not-ready replica", func(t *testing.T) {
|
||||
statusWarningsCase(t, NewAdapterProjectionView(stubProjector{}, "v1", "r1", nil), false)
|
||||
})
|
||||
t.Run("healthy primary", func(t *testing.T) {
|
||||
// codex01's advisory: a healthy primary stays healthy with a warning.
|
||||
p := stubProjector{p: engine.ReplicaProjection{Mode: engine.ModeHealthy, Epoch: 1, EndpointVersion: 1}}
|
||||
statusWarningsCase(t, NewAdapterProjectionView(p, "v1", "r1", stubProbe{yes: false}), true)
|
||||
})
|
||||
}
|
||||
|
||||
func statusWarningsCase(t *testing.T, view *AdapterProjectionView, wantHealthy bool) {
|
||||
s := NewStatusServer(view)
|
||||
addr, err := s.Start("127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = s.Close(context.Background()) }()
|
||||
get := func() StatusProjection {
|
||||
t.Helper()
|
||||
resp, err := http.Get("http://" + addr + "/status?volume=v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
var p StatusProjection
|
||||
if err := json.NewDecoder(resp.Body).Decode(&p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return p
|
||||
}
|
||||
before := get()
|
||||
if before.Healthy != wantHealthy || before.FrontendPrimaryReady != wantHealthy {
|
||||
t.Fatalf("before the warning: healthy=%t ready=%t; want %t", before.Healthy, before.FrontendPrimaryReady, wantHealthy)
|
||||
}
|
||||
s.SetDurableStatusSource(stubDurableStatusSource{vols: []durable.VolumeStatus{{
|
||||
VolumeID: "v1", Impl: "walstore", Warnings: []string{"wal_hole_suspected: WAL entry at offset=4134 fails its check"}, HolesSuspected: 1,
|
||||
}}})
|
||||
after := get()
|
||||
if len(after.Warnings) != 1 || after.Warnings[0][:18] != "wal_hole_suspected" {
|
||||
t.Fatalf("/status warnings %v; want the wal_hole_suspected warning", after.Warnings)
|
||||
}
|
||||
if after.Healthy != before.Healthy || after.FrontendPrimaryReady != before.FrontendPrimaryReady {
|
||||
t.Fatalf("a warning changed health: before healthy=%t ready=%t, after healthy=%t ready=%t",
|
||||
before.Healthy, before.FrontendPrimaryReady, after.Healthy, after.FrontendPrimaryReady)
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,11 @@ type recoveryResult struct {
|
||||
WALTail uint64 // reconstructed logical byte tail of retained WAL
|
||||
TornEntries int // entries discarded due to CRC failure or truncation
|
||||
DefensiveScan bool // true when the superblock was empty and we scanned the whole region
|
||||
// HoleSuspected: a bad entry was followed by a valid later entry
|
||||
// (issue #51). Detection only: it changes nothing about what is
|
||||
// replayed. HoleDetail says where.
|
||||
HoleSuspected bool
|
||||
HoleDetail string
|
||||
}
|
||||
|
||||
// recoverWAL scans the WAL region and replays any entries that have
|
||||
@@ -50,10 +55,10 @@ func recoverWAL(fd *os.File, sb *superblock, dm *dirtyMap) (recoveryResult, erro
|
||||
walSize := sb.WALSize
|
||||
checkpointLSN := sb.WALCheckpointLSN
|
||||
|
||||
type scanRange struct {
|
||||
start, end uint64 // physical positions within WAL
|
||||
}
|
||||
type scanRange = recoveryScanRange
|
||||
var ranges []scanRange
|
||||
// lastLSN is the highest LSN decoded so far (detection only).
|
||||
var lastLSN uint64
|
||||
|
||||
if logicalHead == logicalTail {
|
||||
// A pre-boundary-persistence crash can leave a wrapped retained
|
||||
@@ -93,7 +98,7 @@ func recoverWAL(fd *os.File, sb *superblock, dm *dirtyMap) (recoveryResult, erro
|
||||
}
|
||||
}
|
||||
|
||||
for _, r := range ranges {
|
||||
for ri, r := range ranges {
|
||||
pos := r.start
|
||||
for pos < r.end {
|
||||
remaining := r.end - pos
|
||||
@@ -119,6 +124,9 @@ func recoverWAL(fd *os.File, sb *superblock, dm *dirtyMap) (recoveryResult, erro
|
||||
entrySize := uint64(walEntryHeaderSize) + payloadLen
|
||||
if entrySize > remaining {
|
||||
result.TornEntries++
|
||||
if err := detectHole(&result, fd, walOffset, ranges, ri, pos, headerBuf, max(lastLSN, checkpointLSN), sb.BlockSize, nil); err != nil {
|
||||
return result, err
|
||||
}
|
||||
break
|
||||
}
|
||||
fullBuf := make([]byte, entrySize)
|
||||
@@ -129,6 +137,9 @@ func recoverWAL(fd *os.File, sb *superblock, dm *dirtyMap) (recoveryResult, erro
|
||||
if err != nil {
|
||||
// Torn write or trailing zeros — stop scanning this range.
|
||||
result.TornEntries++
|
||||
if herr := detectHole(&result, fd, walOffset, ranges, ri, pos, headerBuf, max(lastLSN, checkpointLSN), sb.BlockSize, err); herr != nil {
|
||||
return result, herr
|
||||
}
|
||||
break
|
||||
}
|
||||
highestEntryLSN := entry.LSN
|
||||
@@ -148,6 +159,9 @@ func recoverWAL(fd *os.File, sb *superblock, dm *dirtyMap) (recoveryResult, erro
|
||||
}
|
||||
highestEntryLSN = entry.LSN + entry.Reserved - 1
|
||||
}
|
||||
if highestEntryLSN > lastLSN {
|
||||
lastLSN = highestEntryLSN
|
||||
}
|
||||
if highestEntryLSN <= checkpointLSN {
|
||||
pos += entrySize
|
||||
continue
|
||||
@@ -323,3 +337,111 @@ func previousValidWALRecord(
|
||||
return 0, walEntry{}, false
|
||||
}
|
||||
}
|
||||
|
||||
// recoveryScanRange is a physical [start, end) span of the WAL region.
|
||||
type recoveryScanRange struct {
|
||||
start, end uint64
|
||||
}
|
||||
|
||||
func allZeroBytes(b []byte) bool {
|
||||
for _, c := range b {
|
||||
if c != 0 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// laterValidEntry looks, from pos in ranges[ri] through the later ranges,
|
||||
// for an offset holding a valid WAL entry (it decodes, CRC included) whose
|
||||
// LSN is above minLSN. It runs only after a bad entry, so a linear resync
|
||||
// over the remaining WAL is acceptable; a cheap header prefilter keeps the
|
||||
// full decodes to plausible candidates.
|
||||
func laterValidEntry(fd *os.File, walOffset uint64, ranges []recoveryScanRange, ri int, pos, minLSN uint64, blockSize uint32) (bool, uint64, error) {
|
||||
const window = 1 << 20
|
||||
hdr := uint64(walEntryHeaderSize)
|
||||
for i := ri; i < len(ranges); i++ {
|
||||
start, end := ranges[i].start, ranges[i].end
|
||||
if i == ri {
|
||||
start = pos
|
||||
}
|
||||
for p := start; p+hdr <= end; p += window {
|
||||
n := min(window+hdr, end-p)
|
||||
buf := make([]byte, n)
|
||||
if _, err := fd.ReadAt(buf, int64(walOffset+p)); err != nil {
|
||||
return false, 0, fmt.Errorf("storage: recovery resync read at %d: %w", p, err)
|
||||
}
|
||||
for q := uint64(0); q+hdr <= n && q < window; q++ {
|
||||
size, ok := plausibleEntryHeader(buf[q:q+hdr], minLSN, end-(p+q), blockSize)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
full := make([]byte, size)
|
||||
if _, err := fd.ReadAt(full, int64(walOffset+p+q)); err != nil {
|
||||
return false, 0, fmt.Errorf("storage: recovery resync read entry at %d: %w", p+q, err)
|
||||
}
|
||||
if _, err := decodeWALEntry(full); err == nil {
|
||||
return true, p + q, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return false, 0, nil
|
||||
}
|
||||
|
||||
// plausibleEntryHeader is the resync prefilter: a known record type, an
|
||||
// LSN above minLSN, and a length that fits in what remains.
|
||||
func plausibleEntryHeader(h []byte, minLSN, remaining uint64, blockSize uint32) (uint64, bool) {
|
||||
lsn := binary.LittleEndian.Uint64(h[0:8])
|
||||
if lsn <= minLSN {
|
||||
return 0, false
|
||||
}
|
||||
length := uint64(parseLengthFromHeader(h))
|
||||
size := uint64(walEntryHeaderSize)
|
||||
switch h[16] {
|
||||
case walEntryWrite, walEntryWriteBatch:
|
||||
if length == 0 || blockSize == 0 || length%uint64(blockSize) != 0 {
|
||||
return 0, false
|
||||
}
|
||||
size += length
|
||||
case walEntryTrim, walEntryBarrier:
|
||||
default:
|
||||
return 0, false
|
||||
}
|
||||
if size > remaining {
|
||||
return 0, false
|
||||
}
|
||||
return size, true
|
||||
}
|
||||
|
||||
// detectHole notes a suspected WAL hole at a bad entry (issue #51;
|
||||
// claude05's ruling 2026-11-16 06:47Z: detection only). An all-zero
|
||||
// header is just the end of what was written. Otherwise, if a valid entry
|
||||
// with an LSN above minLSN (the highest decoded so far, or the checkpoint)
|
||||
// follows it, the hole is recorded as the typed warning
|
||||
// WarningWALHoleSuspected and logged. Nothing about the replay changes:
|
||||
// the caller stops this range exactly as before. A torn tail and a
|
||||
// corrupted record cannot be told apart without a synced watermark, hence
|
||||
// "suspected".
|
||||
func detectHole(result *recoveryResult, fd *os.File, walOffset uint64, ranges []recoveryScanRange, ri int, pos uint64, header []byte, minLSN uint64, blockSize uint32, cause error) error {
|
||||
if allZeroBytes(header) || result.HoleSuspected {
|
||||
return nil
|
||||
}
|
||||
found, at, err := laterValidEntry(fd, walOffset, ranges, ri, pos+1, minLSN, blockSize)
|
||||
if err != nil {
|
||||
// Detection never changes the outcome: a failed look-ahead read
|
||||
// is logged, and recovery goes on exactly as before.
|
||||
log.Printf("storage: recovery hole detection at offset=%d skipped: %v", pos, err)
|
||||
return nil
|
||||
}
|
||||
if !found {
|
||||
return nil
|
||||
}
|
||||
result.HoleSuspected = true
|
||||
result.HoleDetail = fmt.Sprintf("WAL entry at offset=%d fails its check and a valid later entry (LSN > %d) follows at offset=%d", pos, minLSN, at)
|
||||
if cause != nil {
|
||||
result.HoleDetail += " (" + cause.Error() + ")"
|
||||
}
|
||||
log.Printf("storage: recovery %s: %s", WarningWALHoleSuspected, result.HoleDetail)
|
||||
return nil
|
||||
}
|
||||
@@ -37,13 +37,21 @@ import (
|
||||
// - per-block CRC stored alongside extent (extent stays raw blocks)
|
||||
// - cross-checking against any external snapshot
|
||||
func runRecovery(r *ring, fd *os.File, extentBase int64, blockSize int) (uint64, error) {
|
||||
records, err := r.scanValid()
|
||||
frontier, _, err := runRecoveryCounting(r, fd, extentBase, blockSize)
|
||||
return frontier, err
|
||||
}
|
||||
|
||||
// runRecoveryCounting is runRecovery that also reports how many populated
|
||||
// slots fail their record CRC (issue #51, detection only: they are
|
||||
// skipped exactly as before; see Store.Recover's warning).
|
||||
func runRecoveryCounting(r *ring, fd *os.File, extentBase int64, blockSize int) (uint64, int, error) {
|
||||
records, bad, err := r.scanSlots()
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("smartwal: recovery scan: %w", err)
|
||||
return 0, 0, fmt.Errorf("smartwal: recovery scan: %w", err)
|
||||
}
|
||||
if len(records) == 0 {
|
||||
log.Printf("smartwal: recovery: ring empty; nothing to verify")
|
||||
return 0, nil
|
||||
return 0, len(bad), nil
|
||||
}
|
||||
|
||||
// Last-writer-wins map. Records arrive sorted by LSN ascending,
|
||||
@@ -65,12 +73,12 @@ func runRecovery(r *ring, fd *os.File, extentBase int64, blockSize int) (uint64,
|
||||
data := make([]byte, blockSize)
|
||||
off := extentBase + int64(rec.LBA)*int64(blockSize)
|
||||
if _, err := fd.ReadAt(data, off); err != nil {
|
||||
return 0, fmt.Errorf("smartwal: recovery read trim LBA %d: %w", rec.LBA, err)
|
||||
return 0, 0, fmt.Errorf("smartwal: recovery read trim LBA %d: %w", rec.LBA, err)
|
||||
}
|
||||
if crc32.ChecksumIEEE(data) != rec.DataCRC32 {
|
||||
detail := fmt.Sprintf("trim CRC mismatch LSN=%d LBA=%d", rec.LSN, rec.LBA)
|
||||
log.Printf("smartwal: recovery %s — failing closed", detail)
|
||||
return 0, storage.NewWALIntegrityFailure(nil, detail)
|
||||
return 0, 0, storage.NewWALIntegrityFailure(nil, detail)
|
||||
}
|
||||
recovered++
|
||||
if rec.LSN > highestVerifiedLSN {
|
||||
@@ -82,14 +90,14 @@ func runRecovery(r *ring, fd *os.File, extentBase int64, blockSize int) (uint64,
|
||||
data := make([]byte, blockSize)
|
||||
off := extentBase + int64(rec.LBA)*int64(blockSize)
|
||||
if _, err := fd.ReadAt(data, off); err != nil {
|
||||
return 0, fmt.Errorf("smartwal: recovery read LBA %d: %w", rec.LBA, err)
|
||||
return 0, 0, fmt.Errorf("smartwal: recovery read LBA %d: %w", rec.LBA, err)
|
||||
}
|
||||
actual := crc32.ChecksumIEEE(data)
|
||||
if actual != rec.DataCRC32 {
|
||||
detail := fmt.Sprintf("CRC mismatch LSN=%d LBA=%d expected=%08x actual=%08x",
|
||||
rec.LSN, rec.LBA, rec.DataCRC32, actual)
|
||||
log.Printf("smartwal: recovery %s — failing closed", detail)
|
||||
return 0, storage.NewWALIntegrityFailure(nil, detail)
|
||||
return 0, 0, storage.NewWALIntegrityFailure(nil, detail)
|
||||
}
|
||||
recovered++
|
||||
if rec.LSN > highestVerifiedLSN {
|
||||
@@ -99,5 +107,5 @@ func runRecovery(r *ring, fd *os.File, extentBase int64, blockSize int) (uint64,
|
||||
|
||||
log.Printf("smartwal: recovery: %d LBAs verified, frontier=%d",
|
||||
recovered, highestVerifiedLSN)
|
||||
return highestVerifiedLSN, nil
|
||||
return highestVerifiedLSN, len(bad), nil
|
||||
}
|
||||
@@ -60,23 +60,34 @@ func (r *ring) appendAt(lsn uint64, rec record) error {
|
||||
//
|
||||
// Used during recovery to rebuild the in-memory view.
|
||||
func (r *ring) scanValid() ([]record, error) {
|
||||
records, _, err := r.scanSlots()
|
||||
return records, err
|
||||
}
|
||||
|
||||
// scanSlots is scanValid that also returns the indexes of populated slots
|
||||
// (magic present) whose record CRC fails: torn or corrupted.
|
||||
func (r *ring) scanSlots() ([]record, []uint64, error) {
|
||||
totalSize := r.capacity * recordSize
|
||||
buf := make([]byte, totalSize)
|
||||
r.mu.Lock()
|
||||
_, err := r.fd.ReadAt(buf, r.base)
|
||||
r.mu.Unlock()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("smartwal: ring scan read: %w", err)
|
||||
return nil, nil, fmt.Errorf("smartwal: ring scan read: %w", err)
|
||||
}
|
||||
var out []record
|
||||
var bad []uint64
|
||||
for i := uint64(0); i < r.capacity; i++ {
|
||||
off := i * recordSize
|
||||
rec, ok := decode(buf[off : off+recordSize])
|
||||
if !ok {
|
||||
if buf[off] == recordMagic {
|
||||
bad = append(bad, i)
|
||||
}
|
||||
continue
|
||||
}
|
||||
out = append(out, rec)
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].LSN < out[j].LSN })
|
||||
return out, nil
|
||||
return out, bad, nil
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package smartwal
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
func flipSlotCRC(t *testing.T, path string, lsn uint64) {
|
||||
t.Helper()
|
||||
_, records, err := InspectRecords(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, r := range records {
|
||||
if r.LSN != lsn {
|
||||
continue
|
||||
}
|
||||
f, err := os.OpenFile(path, os.O_RDWR, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer f.Close()
|
||||
b := make([]byte, 1)
|
||||
if _, err := f.ReadAt(b, r.Offset+31); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b[0] ^= 0xFF
|
||||
if _, err := f.WriteAt(b, r.Offset+31); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return
|
||||
}
|
||||
t.Fatalf("no record LSN %d", lsn)
|
||||
}
|
||||
|
||||
func warnsHole(s *Store) bool {
|
||||
for _, w := range s.RecoveryWarnings() {
|
||||
if strings.HasPrefix(w, storage.WarningWALHoleSuspected+":") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// codex01's r1 P1, under claude05's 06:47Z ruling (detection only): a torn
|
||||
// slot accepted by one recovery stays a recoverable warning after a
|
||||
// frontier jump and a new synced write; nothing infers its generation from
|
||||
// its position in the ring.
|
||||
func TestSmartWALTornSlotSurvivesAFrontierJump(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "s.sw")
|
||||
s, err := CreateStore(path, 16, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for i, lba := range []uint32{0, 1} { // LSN 1, 2
|
||||
data := make([]byte, 4096)
|
||||
data[0] = byte(0xE0 + i)
|
||||
if _, err := s.Write(lba, data); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
flipSlotCRC(t, path, 2) // LSN 2 torn
|
||||
|
||||
s, err = OpenStore(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Recover(); err != nil {
|
||||
t.Fatalf("first recovery: %v; want the torn tail accepted", err)
|
||||
}
|
||||
firstWarned, firstHoles := warnsHole(s), s.HolesSuspected()
|
||||
s.AdvanceFrontier(4)
|
||||
data := make([]byte, 4096)
|
||||
data[0] = 0xEF
|
||||
if _, err := s.Write(2, data); err != nil { // LSN 5
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
s, err = OpenStore(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer s.Close()
|
||||
if _, err := s.Recover(); err != nil {
|
||||
t.Fatalf("second recovery after the frontier jump: %v; want recovered (the old torn slot is not corruption)", err)
|
||||
}
|
||||
if !firstWarned || firstHoles != 1 || !warnsHole(s) {
|
||||
t.Fatalf("warnings: first %t (%d), second %v; want the counted %s both times", firstWarned, firstHoles, s.RecoveryWarnings(), storage.WarningWALHoleSuspected)
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"hash/crc32"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
@@ -52,6 +53,11 @@ const defaultWALSlots = 65536
|
||||
// the same LBA from different goroutines are NOT serialized at this
|
||||
// layer — callers must order their own per-LBA writes.
|
||||
type Store struct {
|
||||
// recoveryWarnings and holesSuspected: the last Recover's typed
|
||||
// warnings, and how many recoveries saw bad slots (issue #51).
|
||||
recoveryWarnings []string
|
||||
holesSuspected uint64
|
||||
|
||||
path string
|
||||
fd *os.File
|
||||
hdr *header
|
||||
@@ -176,16 +182,41 @@ func openInitialized(path string, f *os.File, hdr *header) (*Store, error) {
|
||||
// Recover rebuilds the in-memory LSN counter from the ring buffer.
|
||||
// Idempotent: calling twice on the same on-disk state yields the
|
||||
// same result.
|
||||
// RecoveryWarnings returns the last Recover's typed warnings.
|
||||
func (s *Store) RecoveryWarnings() []string {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
return append([]string(nil), s.recoveryWarnings...)
|
||||
}
|
||||
|
||||
// HolesSuspected counts the recoveries that saw populated slots failing
|
||||
// their record CRC.
|
||||
func (s *Store) HolesSuspected() uint64 {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
return s.holesSuspected
|
||||
}
|
||||
|
||||
func (s *Store) Recover() (uint64, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.closed {
|
||||
return 0, errors.New("smartwal: Recover after Close")
|
||||
}
|
||||
frontier, err := runRecovery(s.ring, s.fd, s.extentBase, int(s.hdr.BlockSize))
|
||||
frontier, bad, err := runRecoveryCounting(s.ring, s.fd, s.extentBase, int(s.hdr.BlockSize))
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
// Detection only (issue #51): populated slots whose record CRC fails
|
||||
// were skipped as before. Without a synced watermark a torn tail and
|
||||
// a corrupted committed record cannot be told apart, so this is a
|
||||
// "suspected" warning that changes nothing else.
|
||||
s.recoveryWarnings = nil
|
||||
if bad > 0 {
|
||||
s.holesSuspected++
|
||||
s.recoveryWarnings = []string{fmt.Sprintf("%s: %d populated WAL slot(s) fail their record CRC (a torn tail or a corrupted record; not distinguishable without a synced watermark)", storage.WarningWALHoleSuspected, bad)}
|
||||
log.Printf("smartwal: recovery %s", s.recoveryWarnings[0])
|
||||
}
|
||||
if frontier >= s.nextLSN {
|
||||
s.nextLSN = frontier + 1
|
||||
}
|
||||
|
||||
@@ -43,6 +43,11 @@ import (
|
||||
// - Online resize
|
||||
// - Compaction (the WAL is bounded but periodic checkpoints free space)
|
||||
type WALStore struct {
|
||||
// recoveryWarnings and holesSuspected: the last Recover's typed
|
||||
// warnings, and how many recoveries found a WAL hole (issue #51).
|
||||
recoveryWarnings []string
|
||||
holesSuspected uint64
|
||||
|
||||
metadata BlockMetadata // immutable before publication
|
||||
|
||||
path string
|
||||
@@ -456,6 +461,32 @@ func (s *WALStore) FlusherInstrumentation() FlusherInstrumentationStatus {
|
||||
return s.flusher.instr.snapshot()
|
||||
}
|
||||
|
||||
// WarningWALHoleSuspected is the typed recovery warning for a WAL hole
|
||||
// followed by valid records (issue #51): reported on /status, it does not
|
||||
// change readiness.
|
||||
const WarningWALHoleSuspected = "wal_hole_suspected"
|
||||
|
||||
// RecoveryWarner is a store that reports warnings from its last Recover.
|
||||
type RecoveryWarner interface {
|
||||
RecoveryWarnings() []string
|
||||
}
|
||||
|
||||
// RecoveryWarnings returns the warnings of the last Recover (nil when it
|
||||
// found nothing to warn about).
|
||||
func (s *WALStore) RecoveryWarnings() []string {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return append([]string(nil), s.recoveryWarnings...)
|
||||
}
|
||||
|
||||
// HolesSuspected counts the recoveries of this store that found a WAL hole
|
||||
// followed by valid records.
|
||||
func (s *WALStore) HolesSuspected() uint64 {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.holesSuspected
|
||||
}
|
||||
|
||||
// Recover replays WAL entries past the last checkpoint into the dirty
|
||||
// map. After Recover, the in-memory state matches what an aborted
|
||||
// process would have left durably on disk.
|
||||
@@ -497,6 +528,11 @@ func (s *WALStore) Recover() (uint64, error) {
|
||||
}
|
||||
s.sb.WALHead = res.WALHead
|
||||
s.sb.WALTail = res.WALTail
|
||||
s.recoveryWarnings = nil
|
||||
if res.HoleSuspected {
|
||||
s.holesSuspected++
|
||||
s.recoveryWarnings = []string{WarningWALHoleSuspected + ": " + res.HoleDetail}
|
||||
}
|
||||
recoveredHead := s.checkpointLSN
|
||||
if res.HighestLSN > recoveredHead {
|
||||
recoveredHead = res.HighestLSN
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Issue #51, walstore (claude05's ruling 2026-11-16 06:47Z): pure
|
||||
// detection. A WAL hole followed by valid records is logged, counted and
|
||||
// reported as the typed warning wal_hole_suspected; nothing about what is
|
||||
// replayed, where replay stops, or whether the volume opens changes.
|
||||
|
||||
// writeSyncedEntries writes one block to each of lbas (in order), syncs,
|
||||
// and returns the store with auto-flush off (nothing checkpointed) and
|
||||
// each LBA's WAL offset.
|
||||
func writeSyncedEntries(t *testing.T, lbas []uint32) (*WALStore, string, map[uint64]uint64) {
|
||||
t.Helper()
|
||||
const blockSize = 4096
|
||||
path := filepath.Join(t.TempDir(), "store.bin")
|
||||
s, err := CreateWALStore(path, 16, blockSize)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
for i, lba := range lbas {
|
||||
if _, err := s.Write(lba, makeBlock(blockSize, byte(0xB0+i))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return s, path, walOffsetsByLBA(s)
|
||||
}
|
||||
|
||||
func walOffsetsByLBA(s *WALStore) map[uint64]uint64 {
|
||||
offs := map[uint64]uint64{}
|
||||
for _, e := range s.dm.snapshot() {
|
||||
offs[e.LBA] = e.WALOffset
|
||||
}
|
||||
return offs
|
||||
}
|
||||
|
||||
// flipDataByte corrupts one payload byte of the entry at walOffset without
|
||||
// fixing its CRC.
|
||||
func flipDataByte(t *testing.T, s *WALStore, walOffset uint64) {
|
||||
t.Helper()
|
||||
off := int64(s.sb.WALOffset+walOffset) + int64(walEntryHeaderSize) + 100
|
||||
b := make([]byte, 1)
|
||||
if _, err := s.fd.ReadAt(b, off); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b[0] ^= 0xFF
|
||||
if _, err := s.fd.WriteAt(b, off); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func reopenAfterCrash(t *testing.T, s *WALStore, path string) (*WALStore, uint64, error) {
|
||||
t.Helper()
|
||||
crashRecoveryHardeningStore(t, s)
|
||||
r, err := OpenWALStore(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.DisableAutoFlushForRecoveryTest()
|
||||
t.Cleanup(func() { _ = r.Close() })
|
||||
lsn, rerr := r.Recover()
|
||||
return r, lsn, rerr
|
||||
}
|
||||
|
||||
func holeWarning(s *WALStore) bool {
|
||||
for _, w := range s.RecoveryWarnings() {
|
||||
if strings.HasPrefix(w, WarningWALHoleSuspected+":") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// (a) A corrupted mid-history synced record: recovery opens as before
|
||||
// (this range stops at it), and warns (typed, counted).
|
||||
func TestWALStoreRecoverWarnsOnMidHistoryHole(t *testing.T) {
|
||||
s, path, offs := writeSyncedEntries(t, []uint32{0, 1, 2, 3})
|
||||
flipDataByte(t, s, offs[1])
|
||||
r, lsn, err := reopenAfterCrash(t, s, path)
|
||||
if err != nil || lsn != 1 {
|
||||
t.Fatalf("Recover after a mid-history hole = %d, %v; want 1, nil (no outage)", lsn, err)
|
||||
}
|
||||
if !holeWarning(r) || r.HolesSuspected() != 1 {
|
||||
t.Fatalf("warnings %v holes %d; want %s, counted once", r.RecoveryWarnings(), r.HolesSuspected(), WarningWALHoleSuspected)
|
||||
}
|
||||
if got := r.dm.len(); got != 1 {
|
||||
t.Fatalf("dirty entries replayed = %d; want 1 (nothing after the hole)", got)
|
||||
}
|
||||
assertRecoveryHardeningBlock(t, r, 0, makeBlock(4096, 0xB0))
|
||||
}
|
||||
|
||||
// (b) A power loss with an unsynced, out-of-order tail: an earlier
|
||||
// unsynced record torn, a later one written back. No outage: recovery
|
||||
// succeeds with the synced prefix intact.
|
||||
func TestWALStoreRecoverSurvivesAnOutOfOrderUnsyncedTail(t *testing.T) {
|
||||
s, path, _ := writeSyncedEntries(t, []uint32{0, 1}) // synced
|
||||
for i, lba := range []uint32{2, 3} { // unsynced
|
||||
if _, err := s.Write(lba, makeBlock(4096, byte(0xC0+i))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
offs := walOffsetsByLBA(s)
|
||||
flipDataByte(t, s, offs[2]) // LBA 2 torn, LBA 3 reached the disk
|
||||
r, lsn, err := reopenAfterCrash(t, s, path)
|
||||
if err != nil || lsn != 2 {
|
||||
t.Fatalf("Recover after an out-of-order unsynced tail = %d, %v; want 2, nil", lsn, err)
|
||||
}
|
||||
for i, lba := range []uint32{0, 1} {
|
||||
assertRecoveryHardeningBlock(t, r, lba, makeBlock(4096, byte(0xB0+i)))
|
||||
}
|
||||
}
|
||||
|
||||
// A torn tail (nothing valid after it) recovers without a warning.
|
||||
func TestWALStoreRecoverKeepsATornTail(t *testing.T) {
|
||||
s, path, offs := writeSyncedEntries(t, []uint32{0, 1, 2, 3})
|
||||
flipDataByte(t, s, offs[3])
|
||||
r, lsn, err := reopenAfterCrash(t, s, path)
|
||||
if err != nil || lsn != 3 || holeWarning(r) {
|
||||
t.Fatalf("Recover with a torn tail = %d, %v, warnings %v; want 3, nil, none", lsn, err, r.RecoveryWarnings())
|
||||
}
|
||||
for i, lba := range []uint32{0, 1, 2} {
|
||||
assertRecoveryHardeningBlock(t, r, lba, makeBlock(4096, byte(0xB0+i)))
|
||||
}
|
||||
}
|
||||
|
||||
// (c) A hole across wrapped ranges (the older record at the high end
|
||||
// corrupted, the newer batch wrapped to offset 0) is no outage. Detection
|
||||
// here is per range: when the newer entries were scanned first there is
|
||||
// nothing "later" left to find, and telling generations apart across
|
||||
// ranges (like not replaying past such a hole) is the post-M4 watermark
|
||||
// work.
|
||||
func TestWALStoreRecoverWrappedHoleIsNoOutage(t *testing.T) {
|
||||
const (
|
||||
blockSize = 4096
|
||||
walSize = 24 * 1024
|
||||
)
|
||||
path := filepath.Join(t.TempDir(), "store.bin")
|
||||
s := createWALStoreWithWALSizeForTest(t, path, 64, blockSize, walSize)
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
for lba := uint32(0); lba < 3; lba++ {
|
||||
if _, err := s.Write(lba, makeBlock(blockSize, byte(0x10+lba))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.flusher.flushOnce(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Write(20, makeBlock(blockSize, 0xA4)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.enableMultiBlockRecordsForTest(true)
|
||||
if _, err := s.WriteBatch(24, [][]byte{makeBlock(blockSize, 0xB5), makeBlock(blockSize, 0xB6)}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
offs := walOffsetsByLBA(s)
|
||||
flipDataByte(t, s, offs[20])
|
||||
r, _, err := reopenAfterCrash(t, s, path)
|
||||
if err != nil {
|
||||
t.Fatalf("Recover = %v; want no outage", err)
|
||||
}
|
||||
_ = r
|
||||
}
|
||||
|
||||
// codex01's r1 P1: a damaged STALE record in a released range (below the
|
||||
// checkpoint, outside the retained window) must not cost retained data.
|
||||
// Layout: checkpoint 2, persisted tail at S, head at 3S; LSN 1 (released)
|
||||
// at 0 damaged, LSN 2 checkpointed at S, LSN 3 synced and unflushed at 2S.
|
||||
// LSN 3 must be replayed with its exact bytes.
|
||||
func TestWALStoreRecoverStaleReleasedGarbageKeepsRetainedData(t *testing.T) {
|
||||
const blockSize = 4096
|
||||
s, path, offs := writeSyncedEntries(t, []uint32{0, 1, 2})
|
||||
S := uint64(walEntryHeaderSize + blockSize)
|
||||
if offs[0] != 0 || offs[1] != S || offs[2] != 2*S {
|
||||
t.Fatalf("offsets %v; want 0, S, 2S", offs)
|
||||
}
|
||||
sb := *s.sb
|
||||
sb.WALCheckpointLSN, sb.WALTail, sb.WALHead = 2, S, 3*S
|
||||
buf := newSimpleByteBuf()
|
||||
if _, err := sb.writeTo(buf); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.fd.WriteAt(buf.bytes(), 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.fd.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
flipDataByte(t, s, offs[0]) // the released LSN 1
|
||||
r, _, err := reopenAfterCrash(t, s, path)
|
||||
if err != nil {
|
||||
t.Fatalf("Recover: %v", err)
|
||||
}
|
||||
assertRecoveryHardeningBlock(t, r, 2, makeBlock(blockSize, 0xB2)) // LSN 3, exact bytes
|
||||
}
|
||||
Reference in new issue
Block a user