From f6cc36a58773d4815f8e8c1efe52be6360e35362 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 22:47:00 -0800 Subject: [PATCH 1/4] test: power-loss replay with real binaries: acked iSCSI writes survive a dm-log-writes replay to the sync mark Co-Authored-By: Claude Opus 5.5 --- .../iscsi_powerloss_replay_test.go | 153 ++++++++++++++++++ 1 file changed, 153 insertions(+) create mode 100644 seaweed-block/cmd/blockvolume/iscsi_powerloss_replay_test.go diff --git a/seaweed-block/cmd/blockvolume/iscsi_powerloss_replay_test.go b/seaweed-block/cmd/blockvolume/iscsi_powerloss_replay_test.go new file mode 100644 index 0000000000..b67620d274 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/iscsi_powerloss_replay_test.go @@ -0,0 +1,153 @@ +//go:build subprocess + +package main_test + +import ( + "bytes" + "fmt" + "os" + "os/exec" + "path/filepath" + "testing" + "time" +) + +// Power loss with real binaries (V1-SPEC r2.55 gap 3, INV-FE-FLUSH-SYNC-001): +// blockvolume keeps its durable root on a dm-log-writes device. The guest +// writes over iSCSI and issues SYNCHRONIZE CACHE; once the last sync returns, +// the harness marks the log "acknowledged". Later writes are not synced. The +// volume is killed, and the harness replays the log only up to that mark onto +// a fresh device mounted at the same path: the disk as a power cut at the +// mark would have left it, with no page cache. A restarted blockvolume must +// read back every block acknowledged by a sync. +// +// Environment, set by the external replay harness (root, dm_log_writes): +// SWBLOCK_REPLAY_ROOT mount point of the dm-log-writes filesystem +// SWBLOCK_REPLAY_CUT executable: "mark" marks the log, "replay" +// unmounts, replays to the mark and remounts +// SWBLOCK_REPLAY_BINS optional dir with prebuilt blockmaster/blockvolume +// SWBLOCK_REPLAY_DROP_SYNC "1" = negative control: no SYNCHRONIZE CACHE, so +// the acknowledged writes must be lost +func TestPowerLossReplayAckedWritesSurvive(t *testing.T) { + root, cut := os.Getenv("SWBLOCK_REPLAY_ROOT"), os.Getenv("SWBLOCK_REPLAY_CUT") + if root == "" || cut == "" { + t.Skip("requires the isolated dm-log-writes replay harness") + } + dropSync := os.Getenv("SWBLOCK_REPLAY_DROP_SYNC") == "1" + bins := powerLossBins(t) + art := t.TempDir() // master state and logs stay off the replayed device + _, masterAddr := startSingleSlotMaster(t, bins, art) + + iqn := "iqn.2026-11.example.powerloss:v1" + store := filepath.Join(root, "r1-store") + dataAddr, ctrlAddr := pickAddr(t), pickAddr(t) + statusAddr, iscsiAddr := pickAddr(t), pickAddr(t) + opts := volOpts{ + masterAddr: masterAddr, + serverID: "s1", + replicaID: "r1", + dataAddr: dataAddr, + ctrlAddr: ctrlAddr, + statusAddr: statusAddr, + iscsiAddr: iscsiAddr, + iscsiIQN: iqn, + durableRoot: store, + logTag: "powerloss-r1-initial", + } + r1 := startG54Volume(t, bins, art, opts) + waitHealthyReplica(t, statusAddr, "r1", 10*time.Second) + waitProductIscsiReady(t, iscsiAddr, 5*time.Second) + + const ( + bs = 4096 + acked = 160 // LBAs 0..159 are written and synced before the mark + afterBy = 32 // LBAs 160..191 are written after the mark, never synced + ) + block := func(lba uint32, gen byte) []byte { + b := bytes.Repeat([]byte{byte(lba) ^ gen}, bs) + copy(b, fmt.Sprintf("powerloss lba=%d gen=%d", lba, gen)) + return b + } + cli := dialG8Iscsi(t, iscsiAddr, iqn) + want := map[uint32][]byte{} + for lba := uint32(0); lba < acked; lba++ { + b := block(lba, 1) + cli.write10(t, lba, b) + want[lba] = b + if !dropSync && (lba+1)%8 == 0 { + cli.syncCache10(t) + } + } + if !dropSync { + cli.syncCache10(t) + } + runReplayCut(t, cut, "mark") + for lba := uint32(acked); lba < acked+afterBy; lba++ { + cli.write10(t, lba, block(lba, 2)) + } + if !dropSync { + cli.syncCache10(t) // after the mark: the replay must exclude it + } + cli.close(t) + + // Power cut: no shutdown, no page cache. The replay stops at the mark. + if err := r1.cmd.Process.Kill(); err != nil { + t.Fatalf("kill blockvolume: %v", err) + } + _ = r1.cmd.Wait() + runReplayCut(t, cut, "replay") + + opts.logTag = "powerloss-r1-after-replay" + _ = startG54Volume(t, bins, art, opts) + waitHealthyReplica(t, statusAddr, "r1", 20*time.Second) + waitProductIscsiReady(t, iscsiAddr, 5*time.Second) + + cli2 := dialG8Iscsi(t, iscsiAddr, iqn) + defer cli2.close(t) + lost := 0 + first := -1 + for lba := uint32(0); lba < acked; lba++ { + if got := cli2.read10(t, lba, 1, bs); !bytes.Equal(got, want[lba]) { + if first < 0 { + first = int(lba) + } + lost++ + } + } + after := 0 + for lba := uint32(acked); lba < acked+afterBy; lba++ { + if bytes.Equal(cli2.read10(t, lba, 1, bs), block(lba, 2)) { + after++ + } + } + t.Logf("drop_sync=%v: acked blocks lost %d of %d (first %d); post-mark blocks present %d of %d", + dropSync, lost, acked, first, after, afterBy) + if lost > 0 { + t.Fatalf("REPLAY_BYTES_MISMATCH volume: %d of %d acknowledged blocks lost after power-loss replay (first LBA %d, drop_sync=%v)", + lost, acked, first, dropSync) + } + fmt.Printf("REPLAY_volume_OK drop_sync=%v acked=%d post_mark_present=%d\n", dropSync, acked, after) +} + +func powerLossBins(t *testing.T) l2bins { + t.Helper() + if d := os.Getenv("SWBLOCK_REPLAY_BINS"); d != "" { + b := l2bins{master: filepath.Join(d, "blockmaster"), volume: filepath.Join(d, "blockvolume")} + for _, p := range []string{b.master, b.volume} { + if _, err := os.Stat(p); err != nil { + t.Fatalf("prebuilt binary: %v", err) + } + } + return b + } + return buildG54Binaries(t) +} + +func runReplayCut(t *testing.T, cut, step string) { + t.Helper() + out, err := exec.Command(cut, step).CombinedOutput() + if err != nil { + t.Fatalf("replay harness %s: %v\n%s", step, err, out) + } + t.Logf("replay harness %s: %s", step, bytes.TrimSpace(out)) +} From c4a8aa322fc11957028709d89b9075bf772433df Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 22:48:56 -0800 Subject: [PATCH 2/4] test: power-loss replay keeps master and volume logs in an optional dir Co-Authored-By: Claude Opus 5.5 --- .../blockvolume/iscsi_powerloss_replay_test.go | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/iscsi_powerloss_replay_test.go b/seaweed-block/cmd/blockvolume/iscsi_powerloss_replay_test.go index b67620d274..f32aedc2e3 100644 --- a/seaweed-block/cmd/blockvolume/iscsi_powerloss_replay_test.go +++ b/seaweed-block/cmd/blockvolume/iscsi_powerloss_replay_test.go @@ -22,12 +22,14 @@ import ( // read back every block acknowledged by a sync. // // Environment, set by the external replay harness (root, dm_log_writes): -// SWBLOCK_REPLAY_ROOT mount point of the dm-log-writes filesystem -// SWBLOCK_REPLAY_CUT executable: "mark" marks the log, "replay" -// unmounts, replays to the mark and remounts -// SWBLOCK_REPLAY_BINS optional dir with prebuilt blockmaster/blockvolume -// SWBLOCK_REPLAY_DROP_SYNC "1" = negative control: no SYNCHRONIZE CACHE, so -// the acknowledged writes must be lost +// +// SWBLOCK_REPLAY_ROOT mount point of the dm-log-writes filesystem +// SWBLOCK_REPLAY_CUT executable: "mark" marks the log, "replay" +// unmounts, replays to the mark and remounts +// SWBLOCK_REPLAY_BINS optional dir with prebuilt blockmaster/blockvolume +// SWBLOCK_REPLAY_LOGS optional existing dir for master state and logs +// SWBLOCK_REPLAY_DROP_SYNC "1" = negative control: no SYNCHRONIZE CACHE, so +// the acknowledged writes must be lost func TestPowerLossReplayAckedWritesSurvive(t *testing.T) { root, cut := os.Getenv("SWBLOCK_REPLAY_ROOT"), os.Getenv("SWBLOCK_REPLAY_CUT") if root == "" || cut == "" { @@ -36,6 +38,9 @@ func TestPowerLossReplayAckedWritesSurvive(t *testing.T) { dropSync := os.Getenv("SWBLOCK_REPLAY_DROP_SYNC") == "1" bins := powerLossBins(t) art := t.TempDir() // master state and logs stay off the replayed device + if d := os.Getenv("SWBLOCK_REPLAY_LOGS"); d != "" { + art = d // kept for the receipts + } _, masterAddr := startSingleSlotMaster(t, bins, art) iqn := "iqn.2026-11.example.powerloss:v1" From ee5ff92157ac6b547448b1a172f7fd7aabdc6622 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 23:13:23 -0800 Subject: [PATCH 3/4] test: power loss on a chunk volume (three power cuts: after a committed cut, before a flush, mid-upload); post-mark loss asserted; harness in testdata Co-Authored-By: Claude Opus 5.5 --- .../iscsi_powerloss_replay_test.go | 53 ++++-- .../planned_handoff_integration_test.go | 8 + .../procedure_powerloss_integration_test.go | 170 ++++++++++++++++++ .../blockvolume/testdata/powerloss-replay.sh | 85 +++++++++ 4 files changed, 304 insertions(+), 12 deletions(-) create mode 100644 seaweed-block/cmd/blockvolume/procedure_powerloss_integration_test.go create mode 100755 seaweed-block/cmd/blockvolume/testdata/powerloss-replay.sh diff --git a/seaweed-block/cmd/blockvolume/iscsi_powerloss_replay_test.go b/seaweed-block/cmd/blockvolume/iscsi_powerloss_replay_test.go index f32aedc2e3..b0adfe51a4 100644 --- a/seaweed-block/cmd/blockvolume/iscsi_powerloss_replay_test.go +++ b/seaweed-block/cmd/blockvolume/iscsi_powerloss_replay_test.go @@ -4,6 +4,7 @@ package main_test import ( "bytes" + "context" "fmt" "os" "os/exec" @@ -15,7 +16,8 @@ import ( // Power loss with real binaries (V1-SPEC r2.55 gap 3, INV-FE-FLUSH-SYNC-001): // blockvolume keeps its durable root on a dm-log-writes device. The guest // writes over iSCSI and issues SYNCHRONIZE CACHE; once the last sync returns, -// the harness marks the log "acknowledged". Later writes are not synced. The +// the harness marks the log "acknowledged". Later writes and their sync must +// not survive the replay. The // volume is killed, and the harness replays the log only up to that mark onto // a fresh device mounted at the same path: the disk as a power cut at the // mark would have left it, with no page cache. A restarted blockvolume must @@ -26,15 +28,22 @@ import ( // SWBLOCK_REPLAY_ROOT mount point of the dm-log-writes filesystem // SWBLOCK_REPLAY_CUT executable: "mark" marks the log, "replay" // unmounts, replays to the mark and remounts -// SWBLOCK_REPLAY_BINS optional dir with prebuilt blockmaster/blockvolume +// SWBLOCK_TEST_BINS optional dir with prebuilt blockmaster/blockvolume // SWBLOCK_REPLAY_LOGS optional existing dir for master state and logs -// SWBLOCK_REPLAY_DROP_SYNC "1" = negative control: no SYNCHRONIZE CACHE, so -// the acknowledged writes must be lost +// SWBLOCK_REPLAY_DROP_SYNC "1" = negative control: after one SYNCHRONIZE +// CACHE makes the store durable, the measured +// writes get none, so blocks must be lost (the test +// passes and prints REPLAY_control_RED) +// +// The harness is cmd/blockvolume/testdata/powerloss-replay.sh. func TestPowerLossReplayAckedWritesSurvive(t *testing.T) { root, cut := os.Getenv("SWBLOCK_REPLAY_ROOT"), os.Getenv("SWBLOCK_REPLAY_CUT") - if root == "" || cut == "" { + if root == "" && cut == "" { t.Skip("requires the isolated dm-log-writes replay harness") } + if root == "" || cut == "" { + t.Fatalf("SWBLOCK_REPLAY_ROOT=%q and SWBLOCK_REPLAY_CUT=%q must be set together", root, cut) + } dropSync := os.Getenv("SWBLOCK_REPLAY_DROP_SYNC") == "1" bins := powerLossBins(t) art := t.TempDir() // master state and logs stay off the replayed device @@ -74,6 +83,11 @@ func TestPowerLossReplayAckedWritesSurvive(t *testing.T) { return b } cli := dialG8Iscsi(t, iscsiAddr, iqn) + // The store and one block are durable before the measured writes, so a + // red control shows block loss in an existing store, not a lost store. + base := block(acked+afterBy, 9) + cli.write10(t, acked+afterBy, base) + cli.syncCache10(t) want := map[uint32][]byte{} for lba := uint32(0); lba < acked; lba++ { b := block(lba, 1) @@ -109,6 +123,9 @@ func TestPowerLossReplayAckedWritesSurvive(t *testing.T) { cli2 := dialG8Iscsi(t, iscsiAddr, iqn) defer cli2.close(t) + if got := cli2.read10(t, acked+afterBy, 1, bs); !bytes.Equal(got, base) { + t.Fatalf("the block synced before the measured writes is gone: the store did not survive the replay") + } lost := 0 first := -1 for lba := uint32(0); lba < acked; lba++ { @@ -127,16 +144,26 @@ func TestPowerLossReplayAckedWritesSurvive(t *testing.T) { } t.Logf("drop_sync=%v: acked blocks lost %d of %d (first %d); post-mark blocks present %d of %d", dropSync, lost, acked, first, after, afterBy) - if lost > 0 { - t.Fatalf("REPLAY_BYTES_MISMATCH volume: %d of %d acknowledged blocks lost after power-loss replay (first LBA %d, drop_sync=%v)", - lost, acked, first, dropSync) + if after != 0 { + t.Fatalf("%d of %d post-mark blocks survived: the replay did not stop at the mark", after, afterBy) } - fmt.Printf("REPLAY_volume_OK drop_sync=%v acked=%d post_mark_present=%d\n", dropSync, acked, after) + if dropSync { + if lost == 0 { + t.Fatalf("CONTROL_NOT_RED: no block lost without SYNCHRONIZE CACHE; the replay cannot show a missing sync") + } + fmt.Printf("REPLAY_control_RED lost=%d of %d first=%d\n", lost, acked, first) + return + } + if lost > 0 { + t.Fatalf("REPLAY_BYTES_MISMATCH volume: %d of %d acknowledged blocks lost after power-loss replay (first LBA %d)", + lost, acked, first) + } + fmt.Printf("REPLAY_volume_OK acked=%d post_mark_present=%d\n", acked, after) } func powerLossBins(t *testing.T) l2bins { t.Helper() - if d := os.Getenv("SWBLOCK_REPLAY_BINS"); d != "" { + if d := os.Getenv("SWBLOCK_TEST_BINS"); d != "" { b := l2bins{master: filepath.Join(d, "blockmaster"), volume: filepath.Join(d, "blockvolume")} for _, p := range []string{b.master, b.volume} { if _, err := os.Stat(p); err != nil { @@ -148,9 +175,11 @@ func powerLossBins(t *testing.T) l2bins { return buildG54Binaries(t) } -func runReplayCut(t *testing.T, cut, step string) { +func runReplayCut(t *testing.T, cut string, step ...string) { t.Helper() - out, err := exec.Command(cut, step).CombinedOutput() + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + out, err := exec.CommandContext(ctx, cut, step...).CombinedOutput() if err != nil { t.Fatalf("replay harness %s: %v\n%s", step, err, out) } diff --git a/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go b/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go index 43d8cb8b6d..0f0e297c86 100644 --- a/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go +++ b/seaweed-block/cmd/blockvolume/planned_handoff_integration_test.go @@ -327,6 +327,14 @@ func newPlannedHandoffHarness(t *testing.T) *plannedHandoffHarness { {"blockmaster", &h.master}, {"blockvolume", &h.volume}, {"sw-block", &h.cli}, } { *b.dst = filepath.Join(h.dir, b.name+suffix) + if d := os.Getenv("SWBLOCK_TEST_BINS"); d != "" { + // Prebuilt binaries, for a test host without a Go toolchain. + *b.dst = filepath.Join(d, b.name+suffix) + if _, err := os.Stat(*b.dst); err != nil { + t.Fatalf("SWBLOCK_TEST_BINS: %v", err) + } + continue + } ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) cmd := exec.CommandContext(ctx, "go", "build", "-o", *b.dst, "github.com/seaweedfs/seaweed-block/cmd/"+b.name) cmd.WaitDelay = 5 * time.Second diff --git a/seaweed-block/cmd/blockvolume/procedure_powerloss_integration_test.go b/seaweed-block/cmd/blockvolume/procedure_powerloss_integration_test.go new file mode 100644 index 0000000000..d04ebbc452 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/procedure_powerloss_integration_test.go @@ -0,0 +1,170 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "bytes" + "fmt" + "os" + "path/filepath" + "syscall" + "testing" + "time" +) + +// Power loss on a chunk volume (V1-SPEC r2.55 gap 3, INV-FE-FLUSH-SYNC-001), +// with real binaries: blockmaster, a real filer (weed, its data off the +// replayed device) and a walstore-chunk blockvolume whose durable root is on +// a dm-log-writes device. Each power cut freezes the holder (SIGSTOP), so +// neither its disk nor the filer moves past the mark, marks the log, kills +// the holder, replays the log only up to the mark onto a fresh device (the +// harness puts a new log-writes layer on it and remounts it at the same +// path), restarts the holder and requires every flush-acknowledged block, +// then a cut that commits and verifies at depth data. The phases: +// +// 1. image A flushed and cut (committed, WAL trimmed), then a power cut; +// 2. image B over the same LBAs, flushed, one more write without a flush, +// then a power cut (image A in HEAD must not show through); +// 3. a new image flushed, a cut started, a power cut while it uploads (the +// delay adapts until chunk objects reached the filer but HEAD did not move). +// +// Environment: SWBLOCK_REPLAY_ROOT and SWBLOCK_REPLAY_CUT as for +// TestPowerLossReplayAckedWritesSurvive; CHUNKSTORE_WEED; optional +// SWBLOCK_TEST_BINS and SWBLOCK_REPLAY_LOGS. +func TestPowerLossReplayChunkVolume(t *testing.T) { + root, cutTool := os.Getenv("SWBLOCK_REPLAY_ROOT"), os.Getenv("SWBLOCK_REPLAY_CUT") + if root == "" && cutTool == "" { + t.Skip("requires the isolated dm-log-writes replay harness") + } + if root == "" || cutTool == "" { + t.Fatalf("SWBLOCK_REPLAY_ROOT=%q and SWBLOCK_REPLAY_CUT=%q must be set together", root, cutTool) + } + env := startHandoffEnvWith(t, 1, nil) + if d := os.Getenv("SWBLOCK_REPLAY_LOGS"); d != "" { + t.Cleanup(func() { copyLogs(t, env.h.dir, d) }) + } + h := env.hosts["s1"] + h.root = filepath.Join(root, "vol") + env.hosts["s1"] = h + env.volExtra = []string{"--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"} + cut := []string{"ops", "chunk", "cut", "--volume", "v1", "--status-addr", env.hosts["s1"].status} + verify := []string{"ops", "chunk", "verify", "--volume", "v1", "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath, "--depth", "data", "--timeout", "5m"} + headGen := func() uint64 { + out, _ := env.h.command(t, env.chunkShow()...) + hd, err := parseHead(out) + if err != nil { + t.Fatal(err) + } + return hd.Gen + } + + holder := env.start(t, "blockvolume-v1", "s1") + e := env.adopt(t, holder, "s1") + cuts := 0 + // powerCut ends at a restarted holder that serves every acknowledged block + // of img, and a cut that commits and verifies. + powerCut := func(phase string, img byte) { + t.Helper() + if err := holder.proc.Signal(syscall.SIGSTOP); err != nil { + t.Fatalf("%s: freeze the holder: %v", phase, err) + } + runReplayCut(t, cutTool, "mark") + holder.kill(t) + runReplayCut(t, cutTool, "replay") + cuts++ + holder = env.start(t, fmt.Sprintf("blockvolume-v1-after-cut-%d", cuts), "s1") + if got := env.adopt(t, holder, "s1"); got != e { + t.Fatalf("%s: the restarted holder adopted epoch %d; want %d", phase, got, e) + } + env.requireCutCrashImage(t, "s1", img) + env.h.command(t, cut...) + if out, errOut, rc := env.h.run(t, verify...); rc != 0 { + t.Fatalf("%s: HEAD does not verify after the replay (exit %d):\n%s\n%s", phase, rc, out, errOut) + } + t.Logf("%s: power cut %d replayed; image %c read back; the next cut committed and verified", phase, cuts, img) + } + + // Phase 1: a committed cut before the power cut. + env.writeCutCrashImage(t, 'A') + cutStart := time.Now() + env.h.command(t, cut...) + cutTook := time.Since(cutStart) + powerCut("phase 1 (after a committed cut)", 'A') + + // Phase 2: overwrite with B; then a write the guest never flushed. + env.writeCutCrashImage(t, 'B') + extra := uint64(cutCrashChunks * ladderChunkBlocks) + before := func() []byte { + c := dialNVMe(t, env.hosts["s1"].nvme, plannedHandoffNQN) + defer c.close() + return c.read(t, extra, 4096) + }() + func() { + c := dialNVMe(t, env.hosts["s1"].nvme, plannedHandoffNQN) + defer c.close() + c.write(t, extra, cutCrashBlock('x', extra)) + }() + powerCut("phase 2 (between a write and its flush)", 'B') + func() { + c := dialNVMe(t, env.hosts["s1"].nvme, plannedHandoffNQN) + defer c.close() + got := c.read(t, extra, 4096) + if !bytes.Equal(got, before) && !bytes.Equal(got, cutCrashBlock('x', extra)) { + t.Fatalf("phase 2: the unflushed block reads neither its old nor its new content") + } + }() + + // Phase 3: a power cut while a cut uploads. + delay := cutTook / 2 + img, landed := byte('B'), false + for attempt := 1; attempt <= cutCrashAttempts && !landed; attempt++ { + img++ + env.writeCutCrashImage(t, img) + gen, entries := headGen(), f1FilerEntries(t, env) + done := make(chan int, 1) + go func() { + _, _, code := env.h.run(t, cut...) + done <- code + }() + time.Sleep(delay) + if err := holder.proc.Signal(syscall.SIGSTOP); err != nil { + t.Fatalf("phase 3: freeze the holder: %v", err) + } + uploaded, after := f1FilerEntries(t, env)-entries, headGen() + switch { + case after != gen: + t.Logf("phase 3 attempt %d: the cut committed before %s (HEAD gen %d -> %d); shorter", attempt, delay, gen, after) + delay /= 2 + case uploaded <= 0: + t.Logf("phase 3 attempt %d: nothing uploaded by %s; longer", attempt, delay) + delay *= 2 + default: + landed = true + t.Logf("phase 3 attempt %d: frozen at %s mid-upload: %d new filer entries, HEAD still gen %d", attempt, delay, uploaded, gen) + } + if landed { + // Still frozen mid-upload: the power cut starts from here (its + // SIGSTOP is a no-op on a stopped process). + powerCut(fmt.Sprintf("phase 3 attempt %d (cut in progress)", attempt), img) + <-done + break + } + if err := holder.proc.Signal(syscall.SIGCONT); err != nil { + t.Fatalf("phase 3: resume: %v", err) + } + <-done + } + if !landed { + t.Fatalf("no power cut landed while a cut uploaded, in %d attempts", cutCrashAttempts) + } + fmt.Printf("REPLAY_chunk_OK power_cuts=%d last_image=%c\n", cuts, img) +} + +func copyLogs(t *testing.T, from, to string) { + logs, _ := filepath.Glob(filepath.Join(from, "*.log")) + for _, l := range logs { + if b, err := os.ReadFile(l); err == nil { + _ = os.WriteFile(filepath.Join(to, filepath.Base(l)), b, 0o644) + } + } +} diff --git a/seaweed-block/cmd/blockvolume/testdata/powerloss-replay.sh b/seaweed-block/cmd/blockvolume/testdata/powerloss-replay.sh new file mode 100755 index 0000000000..fe1f67f54d --- /dev/null +++ b/seaweed-block/cmd/blockvolume/testdata/powerloss-replay.sh @@ -0,0 +1,85 @@ +#!/usr/bin/env bash +# Power-loss replay harness for TestPowerLossReplayAckedWritesSurvive and +# TestPowerLossReplayChunkVolume. Root only, on a disposable host with the +# dm_log_writes module and replay-log (upstream log-writes); it formats only +# loop devices over private sparse files under WORKDIR. +# +# powerloss-replay.sh REPLAY_LOG WORKDIR -- TEST_COMMAND... +# +# The test runs with SWBLOCK_REPLAY_ROOT (an ext4 mount on dm-log-writes), +# SWBLOCK_REPLAY_LOGS and SWBLOCK_REPLAY_CUT, a helper with two steps: +# mark marks the current log 'acknowledged' +# replay unmounts, replays the current log only up to that mark onto a +# fresh device, puts a new log-writes layer on it and mounts it at +# the same path, so the next power cut is logged too +# Exit status is the test's. Everything this script created is removed. +set -euo pipefail +[ "$(id -u)" = 0 ] || { echo "root required" >&2; exit 2; } +replayer=$(realpath "${1:?replay-log}") +work=$(realpath "${2:?existing empty work dir}") +[ "${3:-}" = -- ] || { echo "usage: $0 REPLAY_LOG WORKDIR -- TEST_COMMAND..." >&2; exit 2; } +shift 3 +for c in losetup dmsetup mkfs.ext4 mount umount mountpoint blockdev truncate; do command -v "$c" >/dev/null; done +dmsetup targets | awk '$1=="log-writes"{f=1} END{exit !f}' || { echo "dm-log-writes unavailable" >&2; exit 2; } +mkdir "$work/mnt" "$work/logs" +name=swb-powerloss-$$ + +# layer K BACKING_IMG: a log-writes target over BACKING_IMG with log K. The +# log holds only writes made through this layer, so its replay starts from a +# copy of BACKING_IMG as it is now (base-K). +layer() { + local k=$1 img=$2 dev log + cp --sparse=always "$img" "$work/base-$k.img" + truncate -s 2G "$work/log-$k.img" + dev=$(losetup --find --show "$img"); echo "$dev" >> "$work/loops" + log=$(losetup --find --show "$work/log-$k.img"); echo "$log" >> "$work/loops" + dmsetup create "$name-$k" --table "0 $(blockdev --getsz "$dev") log-writes $dev $log" + echo "$k $log" > "$work/current" +} +truncate -s 1G "$work/data-0.img" +layer 0 "$work/data-0.img" +mkfs.ext4 -q -F -E lazy_itable_init=0,lazy_journal_init=0 "/dev/mapper/$name-0" +mount "/dev/mapper/$name-0" "$work/mnt" + +cat > "$work/cut" < "$work/logs/dm-status-\$k.txt" + dmsetup remove "$name-\$k" + n=\$((k + 1)) + cp --sparse=always "$work/base-\$k.img" "$work/data-\$n.img" + rep=\$(losetup --find --show "$work/data-\$n.img") + "$replayer" --log "\$log" --replay "\$rep" --end-mark acknowledged > "$work/logs/replay-\$k.log" 2>&1 + losetup -d "\$rep" + # Layer k's own devices stay attached until cleanup; its images are no longer read. + $(declare -f layer) + name="$name" work="$work" + layer "\$n" "$work/data-\$n.img" + mount "/dev/mapper/$name-\$n" "$work/mnt" + echo "replayed to mark onto layer \$n" ;; + *) echo "usage: cut mark|replay" >&2; exit 2 ;; +esac +EOF +chmod 700 "$work/cut" + +cleanup() { + set +e + mountpoint -q "$work/mnt" && umount "$work/mnt" + for d in $(dmsetup ls | awk -v p="$name-" 'index($1, p) == 1 {print $1}'); do dmsetup remove "$d"; done + [ -f "$work/loops" ] && while read -r l; do losetup -d "$l" 2>/dev/null; done < "$work/loops" + # Only the sparse images this script created under WORKDIR. + rm -f -- "$work"/data-*.img "$work"/log-*.img "$work"/base-*.img +} +trap cleanup EXIT +set +e +SWBLOCK_REPLAY_ROOT=$work/mnt SWBLOCK_REPLAY_CUT=$work/cut SWBLOCK_REPLAY_LOGS=$work/logs "$@" +rc=$? +set -e +exit $rc From 19d29d3a80cc276bcdd0db9d341488e0a872e737 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 22 Nov 2026 23:33:03 -0800 Subject: [PATCH 4/4] test: chunk power loss requires each later cut to move HEAD, HEAD unmoved after the freeze, and the image back from a snapshot restore; cut helper WaitDelay Co-Authored-By: Claude Opus 5.5 --- .../iscsi_powerloss_replay_test.go | 4 ++- .../procedure_powerloss_integration_test.go | 32 +++++++++++++++---- 2 files changed, 28 insertions(+), 8 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/iscsi_powerloss_replay_test.go b/seaweed-block/cmd/blockvolume/iscsi_powerloss_replay_test.go index b0adfe51a4..20e21e5ca9 100644 --- a/seaweed-block/cmd/blockvolume/iscsi_powerloss_replay_test.go +++ b/seaweed-block/cmd/blockvolume/iscsi_powerloss_replay_test.go @@ -179,7 +179,9 @@ func runReplayCut(t *testing.T, cut string, step ...string) { t.Helper() ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) defer cancel() - out, err := exec.CommandContext(ctx, cut, step...).CombinedOutput() + cmd := exec.CommandContext(ctx, cut, step...) + cmd.WaitDelay = 5 * time.Second // a hung child keeping the pipe open does not outlive the kill + out, err := cmd.CombinedOutput() if err != nil { t.Fatalf("replay harness %s: %v\n%s", step, err, out) } diff --git a/seaweed-block/cmd/blockvolume/procedure_powerloss_integration_test.go b/seaweed-block/cmd/blockvolume/procedure_powerloss_integration_test.go index d04ebbc452..e57919a320 100644 --- a/seaweed-block/cmd/blockvolume/procedure_powerloss_integration_test.go +++ b/seaweed-block/cmd/blockvolume/procedure_powerloss_integration_test.go @@ -20,7 +20,8 @@ import ( // the holder, replays the log only up to the mark onto a fresh device (the // harness puts a new log-writes layer on it and remounts it at the same // path), restarts the holder and requires every flush-acknowledged block, -// then a cut that commits and verifies at depth data. The phases: +// then a cut that moves HEAD to a new generation and verifies at depth data; +// at the end a snapshot restored into a new volume is the last image. The phases: // // 1. image A flushed and cut (committed, WAL trimmed), then a power cut; // 2. image B over the same LBAs, flushed, one more write without a flush, @@ -39,7 +40,7 @@ func TestPowerLossReplayChunkVolume(t *testing.T) { if root == "" || cutTool == "" { t.Fatalf("SWBLOCK_REPLAY_ROOT=%q and SWBLOCK_REPLAY_CUT=%q must be set together", root, cutTool) } - env := startHandoffEnvWith(t, 1, nil) + env := startHandoffEnvWith(t, 1, []string{"v2"}) if d := os.Getenv("SWBLOCK_REPLAY_LOGS"); d != "" { t.Cleanup(func() { copyLogs(t, env.h.dir, d) }) } @@ -62,14 +63,22 @@ func TestPowerLossReplayChunkVolume(t *testing.T) { e := env.adopt(t, holder, "s1") cuts := 0 // powerCut ends at a restarted holder that serves every acknowledged block - // of img, and a cut that commits and verifies. - powerCut := func(phase string, img byte) { + // of img, and a cut that verifies; with advance, that cut must move HEAD to + // a new generation (a cut that uploads nothing would leave it). frozenGen, + // when not 0, is the HEAD generation seen while frozen: it must still hold + // after the kill, so no HEAD write from before the freeze landed later. + powerCut := func(phase string, img byte, frozenGen uint64, advance bool) { t.Helper() if err := holder.proc.Signal(syscall.SIGSTOP); err != nil { t.Fatalf("%s: freeze the holder: %v", phase, err) } runReplayCut(t, cutTool, "mark") holder.kill(t) + if frozenGen != 0 { + if g := headGen(); g != frozenGen { + t.Fatalf("%s: HEAD moved from gen %d to %d after the freeze: the cut was not in progress at the mark", phase, frozenGen, g) + } + } runReplayCut(t, cutTool, "replay") cuts++ holder = env.start(t, fmt.Sprintf("blockvolume-v1-after-cut-%d", cuts), "s1") @@ -77,7 +86,11 @@ func TestPowerLossReplayChunkVolume(t *testing.T) { t.Fatalf("%s: the restarted holder adopted epoch %d; want %d", phase, got, e) } env.requireCutCrashImage(t, "s1", img) + g0 := headGen() env.h.command(t, cut...) + if g := headGen(); advance && g <= g0 { + t.Fatalf("%s: the cut after the replay left HEAD at gen %d (was %d): the replayed writes were not published", phase, g, g0) + } if out, errOut, rc := env.h.run(t, verify...); rc != 0 { t.Fatalf("%s: HEAD does not verify after the replay (exit %d):\n%s\n%s", phase, rc, out, errOut) } @@ -89,7 +102,7 @@ func TestPowerLossReplayChunkVolume(t *testing.T) { cutStart := time.Now() env.h.command(t, cut...) cutTook := time.Since(cutStart) - powerCut("phase 1 (after a committed cut)", 'A') + powerCut("phase 1 (after a committed cut)", 'A', 0, false) // Phase 2: overwrite with B; then a write the guest never flushed. env.writeCutCrashImage(t, 'B') @@ -104,7 +117,7 @@ func TestPowerLossReplayChunkVolume(t *testing.T) { defer c.close() c.write(t, extra, cutCrashBlock('x', extra)) }() - powerCut("phase 2 (between a write and its flush)", 'B') + powerCut("phase 2 (between a write and its flush)", 'B', 0, true) func() { c := dialNVMe(t, env.hosts["s1"].nvme, plannedHandoffNQN) defer c.close() @@ -130,6 +143,7 @@ func TestPowerLossReplayChunkVolume(t *testing.T) { if err := holder.proc.Signal(syscall.SIGSTOP); err != nil { t.Fatalf("phase 3: freeze the holder: %v", err) } + time.Sleep(time.Second) // a HEAD write already on the wire lands before the reading uploaded, after := f1FilerEntries(t, env)-entries, headGen() switch { case after != gen: @@ -145,7 +159,7 @@ func TestPowerLossReplayChunkVolume(t *testing.T) { if landed { // Still frozen mid-upload: the power cut starts from here (its // SIGSTOP is a no-op on a stopped process). - powerCut(fmt.Sprintf("phase 3 attempt %d (cut in progress)", attempt), img) + powerCut(fmt.Sprintf("phase 3 attempt %d (cut in progress)", attempt), img, gen, true) <-done break } @@ -157,6 +171,10 @@ func TestPowerLossReplayChunkVolume(t *testing.T) { if !landed { t.Fatalf("no power cut landed while a cut uploaded, in %d attempts", cutCrashAttempts) } + // What the filer holds is the image: a snapshot restored into a new volume. + env.snapshot(t, "s1", "v1", "after-power-cuts") + env.restoreInto(t, "v1", "after-power-cuts", "v2") + env.requireCutCrashImage(t, "n-v2", img) fmt.Printf("REPLAY_chunk_OK power_cuts=%d last_image=%c\n", cuts, img) }