diff --git a/seaweed-block/core/storage/start_wal_replay_crash_test.go b/seaweed-block/core/storage/start_wal_replay_crash_test.go new file mode 100644 index 0000000000..457a5e9506 --- /dev/null +++ b/seaweed-block/core/storage/start_wal_replay_crash_test.go @@ -0,0 +1,343 @@ +package storage + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "os/exec" + "path/filepath" + "runtime" + "strconv" + "testing" + "time" +) + +const k3ReplayPath = "SWBLOCK_TEST_START_REPLAY_PATH" +const k3ReplayPoint = "SWBLOCK_TEST_START_REPLAY_POINT" +const k3ReplayBlocks = 128 + +type k3ReplayRecord struct { + lba uint32 + blocks int + first, last uint64 +} +type k3ReplayCut struct { + Record int + Block int +} // Block 0 = completed record; >0 = inside batch +// A private typed IPC witness, not a product log line or a timed guess. +type k3ReplayWitness struct { + Record, Block int + AppliedLSN, BlockedLSN uint64 +} + +func k3ReplayRecords() []k3ReplayRecord { + var out []k3ReplayRecord + var lsn uint64 + for i := 0; i < 10; i++ { + r := k3ReplayRecord{lba: 7, blocks: 1, first: lsn + 1} + if i%2 != 0 { + r.lba, r.blocks = uint32((i/2)%3)*16, 8 + } + lsn += uint64(r.blocks) + r.last = lsn + out = append(out, r) + } + return out +} + +func k3ReplayData(record int, lba uint32) []byte { + b := make([]byte, 4096) + for i := range b { + b[i] = byte((record+1)*37 + int(lba)*11 + i*13 + i/251) + } + return b +} + +func k3ReplaySeed(t *testing.T, path string, mode WMode) ([][]byte, uint64) { + t.Helper() + s, err := createMappedWALStoreV3ForTest(path, k3ReplayBlocks, 4096, 1<<20, mode, 8) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() // stop before any write; the image must need replay + expected := make([][]byte, k3ReplayBlocks) + for i := range expected { + expected[i] = make([]byte, 4096) + } + var ack uint64 + for i, r := range k3ReplayRecords() { + blocks := make([][]byte, r.blocks) + for j := range blocks { + blocks[j] = k3ReplayData(i, r.lba+uint32(j)) + } + if r.blocks == 1 { + _, err = s.Write(r.lba, blocks[0]) + } else { + _, err = s.WriteBatch(r.lba, blocks) + } + if err != nil { + t.Fatal(err) + } + if ack, err = s.Sync(); err != nil || ack != r.last { + t.Fatalf("ack=%d want=%d: %v", ack, r.last, err) + } + for j, b := range blocks { + expected[int(r.lba)+j] = b + } + } + if s.CheckpointLSN() != 0 { + t.Fatal("seed checkpointed: the test would not prove WAL replay") + } + crashRecoveryHardeningStore(t, s) // no clean stop, no extent drain + return expected, ack +} + +func k3ReplayCopy(t *testing.T, source, target string) { + t.Helper() + for _, suffix := range []string{"", ".chunkmap"} { + in, err := os.Open(source + suffix) + if err != nil { + t.Fatal(err) + } + out, err := os.OpenFile(target+suffix, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600) + if err != nil { + in.Close() + t.Fatal(err) + } + _, err = io.Copy(out, in) + if err == nil { + err = out.Sync() + } + err = errors.Join(err, in.Close(), out.Close()) + if err != nil { + t.Fatal(err) + } + } +} + +func k3ReplayChild(t *testing.T, path string, cut k3ReplayCut) { + t.Helper() + s, err := OpenWALStore(path) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + if s.CheckpointLSN() != 0 { + t.Fatal("child has no WAL-only image") + } + records := k3ReplayRecords() + target := records[cut.Record] + if cut.Block < 0 || cut.Block >= target.blocks { + t.Fatal("invalid replay cut", cut) + } + emit := func(w k3ReplayWitness) { + if err := json.NewEncoder(os.Stdout).Encode(w); err != nil { + panic(err) + } + } + now := time.Unix(0, 0) + ctx := context.WithValue(context.Background(), recoveryClockKey{}, func(RecoveryPhase) time.Time { + now = now.Add(2 * time.Second) // expose every completed record, without sleeping + return now + }) + ctx = WithRecoveryProgress(ctx, func(phase RecoveryPhase, done uint64) { + if phase != RecoveryReplay || os.Getenv("SWBLOCK_TEST_START_REPLAY_SKIP_POINT") == "1" { + return + } + if cut.Block == 0 && done == uint64(cut.Record+1) { + var applied uint64 + for _, e := range s.dm.snapshot() { + applied = max(applied, e.LSN) + } + if applied != target.last { + panic("record progress does not match the applied WAL prefix") + } + emit(k3ReplayWitness{Record: cut.Record, AppliedLSN: applied}) + select {} // parent kills this process before recovery can publish/serve + } + if cut.Block == 0 || done != uint64(cut.Record) { + return + } + blocked := target.lba + uint32(cut.Block) + prior := blocked - 1 + // The preceding record's progress callback runs AFTER dirty-map clear. + // Hold only the shard the target block will enter; the earlier blocks of + // this multi-block record can still be replayed by the real product loop. + shard := s.dm.shard(uint64(blocked)) + if shard == s.dm.shard(uint64(prior)) { + panic("mid-record witness shares blocked shard") + } + shard.mu.Lock() + old := shard.m[uint64(blocked)].lsn + if old >= target.first { + panic("batch interruption armed after its target block was applied") + } + go func() { + watchdog := time.NewTimer(5 * time.Second) + defer watchdog.Stop() + for { + _, _, lsn, _, ok := s.dm.get(uint64(prior)) + if ok && lsn == target.first+uint64(cut.Block)-1 { + emit(k3ReplayWitness{Record: cut.Record, Block: cut.Block, AppliedLSN: lsn, BlockedLSN: old}) + return // shard remains held until the parent kills the child + } + select { + case <-watchdog.C: + panic("replay never reached the batch prefix") + default: + runtime.Gosched() + } + } + }() + }) + if _, err := s.RecoverContext(ctx); err != nil { + t.Fatal(err) + } + t.Fatal("replay completed without reaching the requested interruption") +} + +func k3ReplayKill(t *testing.T, path string, cut k3ReplayCut) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestStartWALReplayInterruptionsConverge$", "-test.timeout=12s") + raw, err := json.Marshal(cut) + if err != nil { + t.Fatal(err) + } + cmd.Env = append(os.Environ(), k3ReplayPath+"="+path, k3ReplayPoint+"="+string(raw)) + var stderr bytes.Buffer + cmd.Stderr = &stderr + stdout, err := cmd.StdoutPipe() + if err != nil { + t.Fatal(err) + } + if err = cmd.Start(); err != nil { + t.Fatal(err) + } + waited := false + defer func() { + if !waited { + _ = cmd.Process.Kill() + _ = cmd.Wait() + } + }() + var witness k3ReplayWitness + if err := json.NewDecoder(stdout).Decode(&witness); err != nil { + _ = cmd.Process.Kill() + _ = cmd.Wait() + waited = true + t.Fatalf("interruption not reached: %v (deadline=%v): %s", err, ctx.Err(), stderr.String()) + } + wantLSN := k3ReplayRecords()[cut.Record].last + if cut.Block != 0 { + wantLSN = k3ReplayRecords()[cut.Record].first + uint64(cut.Block) - 1 + } + if witness.Record != cut.Record || witness.Block != cut.Block || witness.AppliedLSN != wantLSN || (cut.Block != 0 && witness.BlockedLSN >= wantLSN) { + t.Fatalf("wrong typed replay witness: %+v for %+v", witness, cut) + } + if err = cmd.Process.Kill(); err != nil { + t.Fatal(err) + } // SIGKILL on Linux + err = cmd.Wait() + waited = true + var exited *exec.ExitError + if ctx.Err() != nil || !errors.As(err, &exited) || exited.ProcessState.Success() { + t.Fatalf("child not killed at replay witness: %v deadline=%v: %s", err, ctx.Err(), stderr.String()) + } +} + +func k3ReplayVerify(t *testing.T, s *WALStore, expected [][]byte, ack uint64) { + t.Helper() + if s.NextLSN() != ack+1 || s.CheckpointLSN() != 0 { + t.Fatalf("frontier next=%d cp=%d ack=%d", s.NextLSN(), s.CheckpointLSN(), ack) + } + for lba, want := range expected { + got, err := s.Read(uint32(lba)) + if err != nil || !bytes.Equal(got, want) { + t.Fatalf("acknowledged image differs at LBA %d: %v", lba, err) + } + } +} + +// Kill the actual startup store replay, not a clean stop or a torn WAL write. +// The mid-record points interrupt application of a validated multi-block WAL +// record after a proved prefix, while its next block is causally blocked. +func TestStartWALReplayInterruptionsConverge(t *testing.T) { + if path := os.Getenv(k3ReplayPath); path != "" { + var cut k3ReplayCut + if err := json.Unmarshal([]byte(os.Getenv(k3ReplayPoint)), &cut); err != nil { + t.Fatal(err) + } + k3ReplayChild(t, path, cut) + return + } + for _, mode := range []struct { + name string + mode WMode + }{{"lagged", WModeLagged}, {"strict", WModeStrict}} { + t.Run(mode.name, func(t *testing.T) { + seed := filepath.Join(t.TempDir(), "seed") + expected, ack := k3ReplaySeed(t, seed, mode.mode) + var cuts []k3ReplayCut + for i, r := range k3ReplayRecords() { + cuts = append(cuts, k3ReplayCut{Record: i}) + if r.blocks > 1 { + for _, block := range []int{1, 4, 7} { + cuts = append(cuts, k3ReplayCut{Record: i, Block: block}) + } + } + } + for _, cut := range cuts { + name := "record-" + fmt.Sprintf("%02d", cut.Record) + if cut.Block != 0 { + name = "batch-" + fmt.Sprintf("%02d", cut.Record) + "-block-" + strconv.Itoa(cut.Block) + } + t.Run(name, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "volume") + k3ReplayCopy(t, seed, path) + k3ReplayKill(t, path, cut) + s, err := OpenWALStore(path) + if err != nil { + t.Fatal(err) + } + s.DisableAutoFlushForRecoveryTest() + defer func() { _ = s.Close() }() + // The first attempt was killed; the restarted replay must finish with + // exactly the last acknowledged image, including every untouched zero. + if frontier, err := s.Recover(); err != nil || frontier != ack { + t.Fatalf("restart frontier=%d want=%d: %v", frontier, ack, err) + } + k3ReplayVerify(t, s, expected, ack) + beforeR, beforeS, beforeH := s.Boundaries() + if frontier, err := s.Recover(); err != nil || frontier != ack { + t.Fatalf("second replay frontier=%d: %v", frontier, err) + } + k3ReplayVerify(t, s, expected, ack) + if r, tail, h := s.Boundaries(); r != beforeR || tail != beforeS || h != beforeH { + t.Fatalf("replay did not converge: %d/%d/%d -> %d/%d/%d", beforeR, beforeS, beforeH, r, tail, h) + } + if err := s.Close(); err != nil { + t.Fatal(err) + } + next, err := OpenWALStore(path) + if err != nil { + t.Fatal(err) + } + next.DisableAutoFlushForRecoveryTest() + defer next.Close() + if frontier, err := next.Recover(); err != nil || frontier != ack { + t.Fatalf("physical reopen frontier=%d: %v", frontier, err) + } + k3ReplayVerify(t, next, expected, ack) + }) + } + }) + } + +}