From 4b1f3f4d6fa38dc31aad71adfa5bc00ca4e73c61 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 29 May 2026 20:28:40 -0700 Subject: [PATCH] testops: add smartwal corruption utility --- seaweed-block/cmd/sw-block-testutil/main.go | 129 ++++++++++++++++++ .../cmd/sw-block-testutil/main_test.go | 65 +++++++++ seaweed-block/core/storage/smartwal/layout.go | 69 ++++++++++ .../core/storage/smartwal/layout_test.go | 50 +++++++ .../phase34-d4-smartwal-injection-precheck.md | 24 +++- .../phase34-test-realism-plan.md | 2 + 6 files changed, 337 insertions(+), 2 deletions(-) create mode 100644 seaweed-block/cmd/sw-block-testutil/main.go create mode 100644 seaweed-block/cmd/sw-block-testutil/main_test.go diff --git a/seaweed-block/cmd/sw-block-testutil/main.go b/seaweed-block/cmd/sw-block-testutil/main.go new file mode 100644 index 0000000000..171b1f36fd --- /dev/null +++ b/seaweed-block/cmd/sw-block-testutil/main.go @@ -0,0 +1,129 @@ +package main + +import ( + "encoding/hex" + "flag" + "fmt" + "io" + "os" + "path/filepath" + + "github.com/seaweedfs/seaweed-block/core/storage/smartwal" +) + +func main() { + os.Exit(run(os.Args[1:], os.Stdout, os.Stderr)) +} + +func run(args []string, stdout, stderr io.Writer) int { + if len(args) == 0 { + usage(stderr) + return 2 + } + switch args[0] { + case "smartwal-corrupt-latest-record": + return runSmartWALCorruptLatest(args[1:], stdout, stderr) + default: + fmt.Fprintf(stderr, "sw-block-testutil: unknown command %q\n", args[0]) + usage(stderr) + return 2 + } +} + +func usage(w io.Writer) { + fmt.Fprintln(w, "usage: sw-block-testutil smartwal-corrupt-latest-record --path --out ") +} + +func runSmartWALCorruptLatest(args []string, stdout, stderr io.Writer) int { + fs := flag.NewFlagSet("smartwal-corrupt-latest-record", flag.ContinueOnError) + fs.SetOutput(stderr) + var path, outDir string + fs.StringVar(&path, "path", "", "SmartWAL store file to mutate") + fs.StringVar(&outDir, "out", "", "directory for smartwal-corruption-evidence.txt") + if err := fs.Parse(args); err != nil { + return 2 + } + if path == "" || outDir == "" { + fmt.Fprintln(stderr, "smartwal-corrupt-latest-record: --path and --out are required") + return 2 + } + + layout, rec, err := smartwal.LatestRecord(path) + if err != nil { + fmt.Fprintf(stderr, "smartwal-corrupt-latest-record: %v\n", err) + return 1 + } + mutateOffset := rec.Offset + layout.RecordSize - 1 + if !layout.ContainsWALOffset(mutateOffset) || layout.ContainsExtentOffset(mutateOffset) { + fmt.Fprintf(stderr, "smartwal-corrupt-latest-record: mutate offset %d is not safely inside WAL\n", mutateOffset) + return 1 + } + + f, err := os.OpenFile(path, os.O_RDWR, 0) + if err != nil { + fmt.Fprintf(stderr, "smartwal-corrupt-latest-record: open %s: %v\n", path, err) + return 1 + } + defer f.Close() + + before := make([]byte, layout.RecordSize) + if _, err := f.ReadAt(before, rec.Offset); err != nil { + fmt.Fprintf(stderr, "smartwal-corrupt-latest-record: read before: %v\n", err) + return 1 + } + after := make([]byte, len(before)) + copy(after, before) + after[len(after)-1] ^= 0xff + if _, err := f.WriteAt(after[len(after)-1:], mutateOffset); err != nil { + fmt.Fprintf(stderr, "smartwal-corrupt-latest-record: write corruption: %v\n", err) + return 1 + } + if err := f.Sync(); err != nil { + fmt.Fprintf(stderr, "smartwal-corrupt-latest-record: fsync: %v\n", err) + return 1 + } + + if err := os.MkdirAll(outDir, 0o755); err != nil { + fmt.Fprintf(stderr, "smartwal-corrupt-latest-record: mkdir %s: %v\n", outDir, err) + return 1 + } + evidencePath := filepath.Join(outDir, "smartwal-corruption-evidence.txt") + evidence := fmt.Sprintf(`smartwal_corruption_status=ok +smartwal_path=%s +wal_offset=%d +wal_length=%d +wal_end=%d +extent_start=%d +target_lsn=%d +target_lba=%d +target_slot=%d +target_record_offset=%d +mutated_offset=%d +target_offset_inside_wal=%t +target_offset_inside_extent=%t +before_bytes=%s +after_bytes=%s +mutation=flip_last_record_crc_byte +`, + path, + layout.WALOffset, + layout.WALLength, + layout.WALEnd, + layout.ExtentStart, + rec.LSN, + rec.LBA, + rec.Slot, + rec.Offset, + mutateOffset, + layout.ContainsWALOffset(mutateOffset), + layout.ContainsExtentOffset(mutateOffset), + hex.EncodeToString(before), + hex.EncodeToString(after), + ) + if err := os.WriteFile(evidencePath, []byte(evidence), 0o644); err != nil { + fmt.Fprintf(stderr, "smartwal-corrupt-latest-record: write evidence: %v\n", err) + return 1 + } + fmt.Fprint(stdout, evidence) + return 0 +} diff --git a/seaweed-block/cmd/sw-block-testutil/main_test.go b/seaweed-block/cmd/sw-block-testutil/main_test.go new file mode 100644 index 0000000000..7fbda44904 --- /dev/null +++ b/seaweed-block/cmd/sw-block-testutil/main_test.go @@ -0,0 +1,65 @@ +package main + +import ( + "bytes" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/seaweedfs/seaweed-block/core/storage/smartwal" +) + +func TestSmartWALCorruptLatestRecordWritesEvidence(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "store.sw") + store, err := smartwal.CreateStoreWithSlots(path, 8, 4096, 8) + if err != nil { + t.Fatalf("CreateStoreWithSlots: %v", err) + } + data := make([]byte, 4096) + data[0] = 0xab + if _, err := store.Write(2, data); err != nil { + t.Fatalf("Write: %v", err) + } + if _, err := store.Sync(); err != nil { + t.Fatalf("Sync: %v", err) + } + if err := store.Close(); err != nil { + t.Fatalf("Close: %v", err) + } + + outDir := filepath.Join(dir, "out") + var stdout, stderr bytes.Buffer + code := run([]string{"smartwal-corrupt-latest-record", "--path", path, "--out", outDir}, &stdout, &stderr) + if code != 0 { + t.Fatalf("run code=%d stderr=%s", code, stderr.String()) + } + evidencePath := filepath.Join(outDir, "smartwal-corruption-evidence.txt") + raw, err := os.ReadFile(evidencePath) + if err != nil { + t.Fatalf("ReadFile evidence: %v", err) + } + evidence := string(raw) + for _, want := range []string{ + "smartwal_corruption_status=ok", + "target_offset_inside_wal=true", + "target_offset_inside_extent=false", + "mutation=flip_last_record_crc_byte", + } { + if !strings.Contains(evidence, want) { + t.Fatalf("evidence missing %q:\n%s", want, evidence) + } + } + if stdout.String() != evidence { + t.Fatalf("stdout should mirror evidence file") + } + + _, records, err := smartwal.InspectRecords(path) + if err != nil { + t.Fatalf("InspectRecords after corruption: %v", err) + } + if len(records) != 0 { + t.Fatalf("corrupted latest record should no longer decode, got %d valid records", len(records)) + } +} diff --git a/seaweed-block/core/storage/smartwal/layout.go b/seaweed-block/core/storage/smartwal/layout.go index dce95422bf..b605ffe861 100644 --- a/seaweed-block/core/storage/smartwal/layout.go +++ b/seaweed-block/core/storage/smartwal/layout.go @@ -1,8 +1,11 @@ package smartwal import ( + "encoding/hex" "fmt" + "io" "os" + "sort" ) // Layout describes the on-disk SmartWAL geometry parsed from the file header. @@ -25,6 +28,17 @@ type Layout struct { ImplVersion uint32 } +// RecordInfo describes one valid record currently present in the SmartWAL ring. +type RecordInfo struct { + Slot uint64 + Offset int64 + LSN uint64 + LBA uint32 + Flags uint8 + DataCRC32 uint32 + BytesHex string +} + // InspectLayout opens path read-only and returns the SmartWAL layout described // by its header. It fails closed for non-SmartWAL files or truncated files. func InspectLayout(path string) (Layout, error) { @@ -90,3 +104,58 @@ func (l Layout) ContainsWALOffset(off int64) bool { func (l Layout) ContainsExtentOffset(off int64) bool { return off >= l.ExtentStart && off < l.ExtentStart+l.ExtentBytes } + +// InspectRecords returns all valid records found in the SmartWAL ring, sorted +// by LSN ascending. Torn/empty records are intentionally omitted; corruption +// tools use this to pick a real record before mutating it. +func InspectRecords(path string) (Layout, []RecordInfo, error) { + layout, err := InspectLayout(path) + if err != nil { + return Layout{}, nil, err + } + f, err := os.Open(path) + if err != nil { + return Layout{}, nil, fmt.Errorf("smartwal: inspect records open %s: %w", path, err) + } + defer f.Close() + + buf := make([]byte, layout.RecordSize) + records := make([]RecordInfo, 0) + for slot := uint64(0); slot < layout.WALSlots; slot++ { + offset := layout.WALOffset + int64(slot)*layout.RecordSize + if _, err := f.ReadAt(buf, offset); err != nil && err != io.EOF { + return Layout{}, nil, fmt.Errorf("smartwal: inspect records read slot %d: %w", slot, err) + } + rec, ok := decode(buf) + if !ok { + continue + } + raw := make([]byte, len(buf)) + copy(raw, buf) + records = append(records, RecordInfo{ + Slot: slot, + Offset: offset, + LSN: rec.LSN, + LBA: rec.LBA, + Flags: rec.Flags, + DataCRC32: rec.DataCRC32, + BytesHex: hex.EncodeToString(raw), + }) + } + sort.Slice(records, func(i, j int) bool { + return records[i].LSN < records[j].LSN + }) + return layout, records, nil +} + +// LatestRecord returns the highest-LSN valid record in the SmartWAL ring. +func LatestRecord(path string) (Layout, RecordInfo, error) { + layout, records, err := InspectRecords(path) + if err != nil { + return Layout{}, RecordInfo{}, err + } + if len(records) == 0 { + return Layout{}, RecordInfo{}, fmt.Errorf("smartwal: no valid records in WAL ring") + } + return layout, records[len(records)-1], nil +} diff --git a/seaweed-block/core/storage/smartwal/layout_test.go b/seaweed-block/core/storage/smartwal/layout_test.go index 3acd4a54a9..e54f0ac186 100644 --- a/seaweed-block/core/storage/smartwal/layout_test.go +++ b/seaweed-block/core/storage/smartwal/layout_test.go @@ -88,3 +88,53 @@ func TestInspectLayoutRejectsTruncatedFile(t *testing.T) { t.Fatal("InspectLayout should reject truncated SmartWAL files") } } + +func TestInspectRecordsFindsLatestValidRecord(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "store.sw") + s, err := CreateStoreWithSlots(path, 8, 4096, 8) + if err != nil { + t.Fatalf("CreateStoreWithSlots: %v", err) + } + for i := uint32(0); i < 3; i++ { + data := make([]byte, 4096) + data[0] = byte(i + 1) + if _, err := s.Write(i, data); err != nil { + t.Fatalf("Write: %v", err) + } + } + if _, err := s.Sync(); err != nil { + t.Fatalf("Sync: %v", err) + } + if err := s.Close(); err != nil { + t.Fatalf("Close: %v", err) + } + + layout, records, err := InspectRecords(path) + if err != nil { + t.Fatalf("InspectRecords: %v", err) + } + if len(records) != 3 { + t.Fatalf("records=%d want 3", len(records)) + } + for i, rec := range records { + wantLSN := uint64(i + 1) + if rec.LSN != wantLSN { + t.Fatalf("record[%d].LSN=%d want %d", i, rec.LSN, wantLSN) + } + if !layout.ContainsWALOffset(rec.Offset) { + t.Fatalf("record[%d] offset %d should be inside WAL", i, rec.Offset) + } + if rec.BytesHex == "" { + t.Fatalf("record[%d] missing byte sample", i) + } + } + + _, latest, err := LatestRecord(path) + if err != nil { + t.Fatalf("LatestRecord: %v", err) + } + if latest.LSN != 3 || latest.LBA != 2 { + t.Fatalf("latest=%+v want LSN=3 LBA=2", latest) + } +} diff --git a/seaweed-block/internal/docs/qa-assignments/phase34-d4-smartwal-injection-precheck.md b/seaweed-block/internal/docs/qa-assignments/phase34-d4-smartwal-injection-precheck.md index 3d77fbc67a..58dbcda426 100644 --- a/seaweed-block/internal/docs/qa-assignments/phase34-d4-smartwal-injection-precheck.md +++ b/seaweed-block/internal/docs/qa-assignments/phase34-d4-smartwal-injection-precheck.md @@ -2,7 +2,8 @@ Date: 2026-05-29 -Status: PASS for layout contract; D4 dirty-failure scenario remains pending. +Status: PASS for layout + mutation-tool contract; D4 dirty-failure scenario +remains pending. ## Why this precheck exists @@ -37,6 +38,21 @@ core/storage/smartwal/layout.go core/storage/smartwal/layout_test.go ``` +Added an explicit TestOps-only mutation utility: + +```text +cmd/sw-block-testutil smartwal-corrupt-latest-record --path --out +``` + +This utility is deliberately not part of `sw-block ops`; the user-facing ops +surface stays read-only. The utility: + +- parses the SmartWAL layout from the header, +- selects the highest-LSN valid WAL record, +- flips the last byte of that record's CRC, +- fsyncs the file, +- writes `smartwal-corruption-evidence.txt`. + The inspector returns: ```text @@ -63,13 +79,14 @@ whether an offset is inside the WAL ring or extent region. Command: ```text -go test ./core/storage/smartwal +go test ./core/storage/smartwal ./cmd/sw-block-testutil ``` Result: ```text ok github.com/seaweedfs/seaweed-block/core/storage/smartwal +ok github.com/seaweedfs/seaweed-block/cmd/sw-block-testutil ``` Tests prove: @@ -79,6 +96,8 @@ Tests prove: - Record offset uses `slot = lsn % walSlots`. - Non-SmartWAL files are rejected. - Truncated SmartWAL files are rejected. +- The mutation utility writes evidence, flips a real record CRC byte, and the + corrupted record no longer decodes as valid. ## D4 gate rule @@ -96,6 +115,7 @@ target_offset_inside_wal=true target_offset_inside_extent=false before_bytes= after_bytes= +mutation=flip_last_record_crc_byte restart_persistence=hostpath ``` diff --git a/seaweed-block/internal/docs/qa-assignments/phase34-test-realism-plan.md b/seaweed-block/internal/docs/qa-assignments/phase34-test-realism-plan.md index f30e521607..212f20a20a 100644 --- a/seaweed-block/internal/docs/qa-assignments/phase34-test-realism-plan.md +++ b/seaweed-block/internal/docs/qa-assignments/phase34-test-realism-plan.md @@ -188,6 +188,8 @@ Precheck artifact: - `internal/docs/qa-assignments/phase34-d4-smartwal-injection-precheck.md` - `core/storage/smartwal.InspectLayout` is the required read-only layout contract for future D4 injection code. +- `cmd/sw-block-testutil smartwal-corrupt-latest-record` is the TestOps-only + mutation utility; do not put mutating corruption under `sw-block ops`. Scenario shape: