diff --git a/seaweed-block/README.md b/seaweed-block/README.md index 3a8730f8fc..aebdc321fb 100644 --- a/seaweed-block/README.md +++ b/seaweed-block/README.md @@ -245,9 +245,9 @@ Secrets first ([quickstart](docs/quickstart-kubernetes.md)). control broker, which is not done. - Crash-restart recovery of a ublk server. A crashed server fails closed. - Multi-replica workspaces combined with chunk snapshots. -- The `smartwal` engine, which is experimental: no rollback for a torn - in-place overwrite, no per-block CRC once its ring record recycles, open - handling of a corrupted committed record, and no chunk snapshots. +- The experimental engines `smartwal` and `parallel-walstore`: removed in + v1.1; their volumes are refused (copy the data to a walstore volume with + v1.0.x first). - Kubernetes: backup and restore, a production operator, automatic failback or cleanup, upgrade execution, broad compatibility, and more: see [what you should not expect yet](docs/kubernetes-status.md#what-you-should-not-expect-yet). diff --git a/seaweed-block/charts/seaweed-block/values.schema.json b/seaweed-block/charts/seaweed-block/values.schema.json index f5883c8957..36e66c157c 100644 --- a/seaweed-block/charts/seaweed-block/values.schema.json +++ b/seaweed-block/charts/seaweed-block/values.schema.json @@ -36,7 +36,7 @@ "additionalProperties": { "type": "string" } }, "failbackRuntimeRPC": { "type": "boolean" }, - "durableImpl": { "type": "string", "enum": ["walstore", "smartwal", "parallel-walstore"] }, + "durableImpl": { "type": "string", "enum": ["walstore"] }, "durableWALMultiBlockRecords": { "type": "boolean" }, "durableWALRecoveryTestDisableFlusher": { "type": "boolean" }, "stateHostPath": { "type": "string" }, diff --git a/seaweed-block/cmd/blockmaster/main.go b/seaweed-block/cmd/blockmaster/main.go index ffb1a3fb37..9a6f50eb97 100644 --- a/seaweed-block/cmd/blockmaster/main.go +++ b/seaweed-block/cmd/blockmaster/main.go @@ -119,7 +119,7 @@ func parseFlags(args []string) (flags, error) { fs.StringVar(&f.launcherImage, "launcher-image", "sw-block:local", "G15d rendered blockvolume container image") fs.StringVar(&f.launcherMasterAddr, "launcher-master-addr", "", "G15d master address used in rendered blockvolume args; defaults to listener address after bind") fs.StringVar(&f.launcherDurableRoot, "launcher-durable-root", "/var/lib/sw-block", "G15d rendered blockvolume durable root base") - fs.StringVar(&f.launcherDurableImpl, "launcher-durable-impl", "walstore", "G15d rendered blockvolume durable implementation: walstore (default), smartwal, or opt-in parallel-walstore") + fs.StringVar(&f.launcherDurableImpl, "launcher-durable-impl", "walstore", "G15d rendered blockvolume durable implementation: walstore (the only one; the removed experimental engines are refused)") fs.BoolVar(&f.launcherWALMultiBlockRecords, "launcher-durable-wal-multiblock-records", false, "G15d render opt-in for experimental walstore multi-block WAL records; default false") fs.BoolVar(&f.launcherWALRecoveryTestDisableFlusher, "launcher-durable-wal-recovery-test-disable-flusher", false, "test-only G15d render opt-in for blockvolume --durable-wal-recovery-test-disable-flusher; default false") fs.StringVar(&f.launcherStateHostPath, "launcher-state-hostpath", "", "optional hostPath base mounted at the blockvolume durable root; empty keeps generated blockvolume state on throwaway emptyDir") diff --git a/seaweed-block/cmd/blockvolume/durable_impl_default_test.go b/seaweed-block/cmd/blockvolume/durable_impl_default_test.go index 1a0bab9561..d1583e4a83 100644 --- a/seaweed-block/cmd/blockvolume/durable_impl_default_test.go +++ b/seaweed-block/cmd/blockvolume/durable_impl_default_test.go @@ -9,8 +9,7 @@ import ( ) // --durable-impl defaults to empty (auto): new volumes are walstore, and an -// existing volume opens with its on-disk format. smartwal is experimental -// and only used when chosen explicitly or found on disk. +// existing volume opens with its on-disk format. func TestBlockvolumeDurableImplDefaultIsAuto(t *testing.T) { f, err := parseFlags(phase150RequiredBlockvolumeArgs()) if err != nil { @@ -22,7 +21,7 @@ func TestBlockvolumeDurableImplDefaultIsAuto(t *testing.T) { } func TestBlockvolumeDurableImplExplicitValues(t *testing.T) { - for _, impl := range []string{"walstore", "smartwal", "parallel-walstore"} { + for _, impl := range []string{"walstore"} { args := append(phase150RequiredBlockvolumeArgs(), "--durable-root=/tmp/sw-block", "--durable-impl="+impl) f, err := parseFlags(args) if err != nil { diff --git a/seaweed-block/cmd/blockvolume/durable_startup_slotcrc_test.go b/seaweed-block/cmd/blockvolume/durable_startup_slotcrc_test.go index 7cb6b9097c..60e60c1c58 100644 --- a/seaweed-block/cmd/blockvolume/durable_startup_slotcrc_test.go +++ b/seaweed-block/cmd/blockvolume/durable_startup_slotcrc_test.go @@ -5,82 +5,14 @@ import ( "os" "os/exec" "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{}) @@ -94,62 +26,6 @@ func startAfterCorruption(t *testing.T, cfg durable.ProviderConfig) (durableStar 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) - } -} - -// 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) - } -} - // V3 replaces the legacy warning-only recovery policy with nonce-bound, // contiguous WAL recovery. Corruption below strict W must block readiness. func TestDurableStartup_Issue51_WALStoreV3CommittedHoleBlocksReadiness(t *testing.T) { diff --git a/seaweed-block/cmd/blockvolume/durable_startup_test.go b/seaweed-block/cmd/blockvolume/durable_startup_test.go index ff52fc179a..28630ad3c6 100644 --- a/seaweed-block/cmd/blockvolume/durable_startup_test.go +++ b/seaweed-block/cmd/blockvolume/durable_startup_test.go @@ -14,7 +14,6 @@ import ( "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" ) // #133 (review of #139): blockvolume's startup open-and-replay step @@ -113,7 +112,7 @@ func TestDurableStartup_RealProviderOpenFailureIsIOError(t *testing.T) { if err := os.WriteFile(filepath.Join(root, "v1.bin"), []byte{0x53, 0x57}, 0o644); err != nil { t.Fatal(err) } - dp, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplSmartWAL, StorageRoot: root}, healthyView{}) + dp, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStore, StorageRoot: root}, healthyView{}) if err != nil { t.Fatal(err) } @@ -124,56 +123,3 @@ func TestDurableStartup_RealProviderOpenFailureIsIOError(t *testing.T) { t.Fatalf("truncated volume file: outcome=%v err=%v reported=%v; want faulted with io_error", outcome, oErr, h.reported) } } - -// Real provider, replay path: a smartwal volume written through the -// provider, then an extent corrupted on disk; the next start's replay -// fails with wal_corrupt. -func TestDurableStartup_RealProviderCorruptReplayIsWALCorrupt(t *testing.T) { - root := t.TempDir() - cfg := durable.ProviderConfig{Impl: durable.ImplSmartWAL, StorageRoot: root, BlockSize: 4096, NumBlocks: 16} - 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 := uint32(0); i < 3; i++ { - data := make([]byte, 4096) - data[0] = byte(0xA0 + i) - if _, err := st.Write(i, data); err != nil { - t.Fatal(err) - } - } - if _, err := st.Sync(); err != nil { - t.Fatal(err) - } - if err := dp.Close(); err != nil { - t.Fatal(err) - } - path := filepath.Join(root, "v1.bin") - layout, rec, err := smartwal.LatestRecord(path) - if err != nil { - t.Fatal(err) - } - f, err := os.OpenFile(path, os.O_RDWR, 0) - if err != nil { - t.Fatal(err) - } - if _, err := f.WriteAt([]byte{0x5A}, layout.ExtentStart+int64(rec.LBA)*int64(layout.BlockSize)); err != nil { - t.Fatal(err) - } - _ = f.Close() - - dp2, err := durable.NewDurableProvider(cfg, healthyView{}) - if err != nil { - t.Fatal(err) - } - defer dp2.Close() - h := &spyHost{} - outcome, evidence, _ := openAndRecoverDurable(dp2, h, "v1", 5*time.Second) - if outcome != durableStartupFaulted || len(h.reported) != 1 || h.reported[0] != volume.UnhealthyWALCorrupt { - t.Fatalf("corrupt replay: outcome=%v evidence=%q reported=%v; want faulted with wal_corrupt", outcome, evidence, h.reported) - } -} diff --git a/seaweed-block/cmd/blockvolume/durable_wal_multiblock_flag_test.go b/seaweed-block/cmd/blockvolume/durable_wal_multiblock_flag_test.go index b4972dce9f..06cf2e1fb7 100644 --- a/seaweed-block/cmd/blockvolume/durable_wal_multiblock_flag_test.go +++ b/seaweed-block/cmd/blockvolume/durable_wal_multiblock_flag_test.go @@ -1,6 +1,9 @@ package main -import "testing" +import ( + "strings" + "testing" +) func phase150RequiredBlockvolumeArgs() []string { return []string{ @@ -26,11 +29,10 @@ func TestPhase150_BlockvolumeDurableWALMultiBlockFlagDefaultFalse(t *testing.T) func TestPhase150_BlockvolumeDurableWALMultiBlockFlagRequiresWalstore(t *testing.T) { args := append(phase150RequiredBlockvolumeArgs(), "--durable-root=/tmp/sw-block", - "--durable-impl=smartwal", "--durable-wal-multiblock-records", ) - if _, err := parseFlags(args); err == nil { - t.Fatal("parseFlags succeeded; want walstore requirement error") + if _, err := parseFlags(args); err == nil || !strings.Contains(err.Error(), "requires --durable-impl=walstore") { + t.Fatalf("parseFlags: err=%v; want the walstore requirement error", err) } } @@ -67,25 +69,10 @@ func TestPhase152_BlockvolumeDurableWALRecoveryTestDisableFlusherFlag(t *testing func TestPhase152_BlockvolumeDurableWALRecoveryTestDisableFlusherRequiresWalstore(t *testing.T) { args := append(phase150RequiredBlockvolumeArgs(), "--durable-root=/tmp/sw-block", - "--durable-impl=smartwal", "--durable-wal-recovery-test-disable-flusher", ) - if _, err := parseFlags(args); err == nil { - t.Fatal("parseFlags succeeded; want walstore requirement error") - } -} - -func TestPhase167_BlockvolumeParallelWALStoreIsExplicitOptIn(t *testing.T) { - args := append(phase150RequiredBlockvolumeArgs(), - "--durable-root=/tmp/sw-block", - "--durable-impl=parallel-walstore", - ) - f, err := parseFlags(args) - if err != nil { - t.Fatalf("parseFlags: %v", err) - } - if f.durableImpl != "parallel-walstore" { - t.Fatalf("durableImpl=%q want parallel-walstore", f.durableImpl) + if _, err := parseFlags(args); err == nil || !strings.Contains(err.Error(), "requires --durable-impl=walstore") { + t.Fatalf("parseFlags: err=%v; want the walstore requirement error", err) } } diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index 504b30ac57..4bda58e5cd 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -115,13 +115,13 @@ type flags struct { // Durable-backend flags. When --durable-root is set, the iSCSI // and NVMe providers use DurableProvider instead of memback. - // --durable-impl selects walstore, smartwal (experimental), or the - // explicit parallel-walstore candidate. Empty (default) = auto: an - // existing volume opens with its on-disk format, a new one is walstore. + // --durable-impl selects walstore or walstore-chunk. Empty (default) = + // auto: an existing volume opens with its on-disk format, a new one is + // walstore. The removed experimental engines' names are refused typed. // --durable-blocks + --durable-blocksize are used on first-time // storage create. durableRoot string - durableImpl string // "" (auto) | "walstore" | "smartwal" | "parallel-walstore" | "walstore-chunk" + durableImpl string // "" (auto) | "walstore" | "walstore-chunk" // --chunk-*: the SeaweedFS remote of --durable-impl=walstore-chunk. chunk chunkFlags durableBlocks uint @@ -224,7 +224,7 @@ func parseFlags(args []string) (flags, error) { fs.IntVar(&f.ublkQueues, "ublk-queues", 0, "ublk hardware queues (one server thread each); 0 = default 1. Requires --ublk-device") fs.IntVar(&f.ublkQueueDepth, "ublk-queue-depth", 0, "ublk in-flight requests per queue; 0 = default 64. Requires --ublk-device") fs.StringVar(&f.durableRoot, "durable-root", "", "directory for persistent storage files; empty = memback (non-durable)") - fs.StringVar(&f.durableImpl, "durable-impl", "", "LogicalStorage impl: empty (default) = auto: an existing volume opens with its on-disk format (a walstore-chunk root needs the explicit walstore-chunk selector), a new volume is created as walstore; or walstore, smartwal (experimental), opt-in parallel-walstore, or opt-in walstore-chunk (walstore published to SeaweedFS; proof of concept); ignored unless --durable-root is set") + fs.StringVar(&f.durableImpl, "durable-impl", "", "LogicalStorage impl: empty (default) = auto: an existing volume opens with its on-disk format (a walstore-chunk root needs the explicit walstore-chunk selector), a new volume is created as walstore; or walstore, or opt-in walstore-chunk (walstore published to SeaweedFS; proof of concept); ignored unless --durable-root is set") registerHostLimitFlags(fs, &f.chunk.hostLimit) chunkstore.RegisterSWFSFlags(fs, &f.chunk.filer, &f.chunk.path, &f.chunk.collection, &f.chunk.replication) fs.Bool("chunk-detach-plain-supported", false, "capability: supports idle plain=true on /chunk/detach (no-op flag)") @@ -248,9 +248,7 @@ func parseFlags(args []string) (flags, error) { "Non-zero relaxes the recovery-scan recycle gate so a replica lagging "+ "within the configured envelope still has a catch-up scan path; once a "+ "replica falls past this window the engine escalates to rebuild. "+ - "Substrate semantics: walstore (append-only) honors this directly; "+ - "smartwal (fixed-size ring) bounds retention via --durable-blocks instead "+ - "and ignores this flag. Recommended starting value for sustained-write "+ + "Recommended starting value for sustained-write "+ "workloads on walstore: 10000 LSNs (sized to expected replica lag).") fs.DurationVar(&f.degradedProbeInterval, "degraded-probe-interval", 5*time.Second, "primary-side degraded-peer probe loop interval; 0 = OFF. "+ @@ -317,10 +315,13 @@ func parseFlags(args []string) (flags, error) { if _, _, err := parseReplicationAckProfile(f.replicationAck); err != nil { return flags{}, err } + if err := durable.RemovedEngineName(f.durableImpl); err != nil { + return flags{}, fmt.Errorf("--durable-impl: %w", err) + } switch f.durableImpl { - case "", "walstore", "smartwal", "parallel-walstore", "walstore-chunk": + case "", "walstore", "walstore-chunk": default: - return flags{}, fmt.Errorf("--durable-impl=%q invalid; want empty (auto), walstore, smartwal, parallel-walstore, or walstore-chunk", f.durableImpl) + return flags{}, fmt.Errorf("--durable-impl=%q invalid; want empty (auto), walstore, or walstore-chunk", f.durableImpl) } if f.workspaceLease && (f.durableRoot == "" || f.durableImpl != "walstore-chunk") { return flags{}, fmt.Errorf("--workspace-lease requires --durable-root and --durable-impl=walstore-chunk") diff --git a/seaweed-block/cmd/sw-block-testutil/main.go b/seaweed-block/cmd/sw-block-testutil/main.go deleted file mode 100644 index 171b1f36fd..0000000000 --- a/seaweed-block/cmd/sw-block-testutil/main.go +++ /dev/null @@ -1,129 +0,0 @@ -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 deleted file mode 100644 index 7fbda44904..0000000000 --- a/seaweed-block/cmd/sw-block-testutil/main_test.go +++ /dev/null @@ -1,65 +0,0 @@ -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/cmd/sw-block/shell_check.go b/seaweed-block/cmd/sw-block/shell_check.go index b3a573588a..3fa0fd1b27 100644 --- a/seaweed-block/cmd/sw-block/shell_check.go +++ b/seaweed-block/cmd/sw-block/shell_check.go @@ -386,7 +386,7 @@ func (o *inspectionObservation) chunkstore() checkFinding { return checkElsewhere("chunk store status unavailable") } return checkOK("chunk store configured; snapshot observations follow") - case "walstore", "smartwal", "parallel-walstore": + case "walstore": return checkOK("local engine only: no snapshots; not the supported configuration (start with a filer, see sw-block mini --weed)") default: return checkElsewhere("chunk store implementation unavailable") @@ -407,7 +407,7 @@ func (o *inspectionObservation) cut() checkFinding { if d.VolumeID != v.evidence.VolumeID { continue } - if d.Impl == "walstore" || d.Impl == "smartwal" || d.Impl == "parallel-walstore" { + if d.Impl == "walstore" { return checkFinding{"not applicable", "no chunk store"} } if d.Chunk == nil || d.Chunk.Stats == nil { @@ -455,7 +455,7 @@ func (o *inspectionObservation) cleaning() checkFinding { if d.VolumeID != v.evidence.VolumeID { continue } - if d.Impl == "walstore" || d.Impl == "smartwal" || d.Impl == "parallel-walstore" { + if d.Impl == "walstore" { return checkFinding{"not applicable", "no chunk store"} } if d.Chunk == nil || d.Chunk.Maintenance == nil { diff --git a/seaweed-block/core/frontend/durable/integration_iscsi_test.go b/seaweed-block/core/frontend/durable/integration_iscsi_test.go index 6c3de51609..5d4db46a13 100644 --- a/seaweed-block/core/frontend/durable/integration_iscsi_test.go +++ b/seaweed-block/core/frontend/durable/integration_iscsi_test.go @@ -1,5 +1,5 @@ // T3b integration — iSCSI handler against DurableProvider-sourced -// StorageBackend. Matrix-parameterized over walstore + smartwal per +// StorageBackend. Matrix-parameterized over the durable engines per // Addendum A #1. Exercises Write / Read / SYNC_CACHE through the // real SCSI command path, not just the backend-dispatch boundary. // diff --git a/seaweed-block/core/frontend/durable/integration_nvme_test.go b/seaweed-block/core/frontend/durable/integration_nvme_test.go index a35494f1db..03790891e6 100644 --- a/seaweed-block/core/frontend/durable/integration_nvme_test.go +++ b/seaweed-block/core/frontend/durable/integration_nvme_test.go @@ -1,5 +1,5 @@ // T3b integration — NVMe handler against DurableProvider-sourced -// StorageBackend. Matrix-parameterized over walstore + smartwal. +// StorageBackend. Matrix-parameterized over the durable engines. // Complements TestT3b_NVMe_Flush_DispatchesToBackend with real // round-trip via LogicalStorage. @@ -15,7 +15,7 @@ import ( // TestT3b_Integration_NVMe_WriteReadFlush_Matrix exercises a full // NVMe Write → Flush → Read round-trip through the NVMe IOHandler -// against both walstore and smartwal impls. +// against every durable engine. func TestT3b_Integration_NVMe_WriteReadFlush_Matrix(t *testing.T) { for _, impl := range implMatrix() { impl := impl diff --git a/seaweed-block/core/frontend/durable/m5_sync_bench_test.go b/seaweed-block/core/frontend/durable/m5_sync_bench_test.go index 8c3fe1f46f..6ba66efd9a 100644 --- a/seaweed-block/core/frontend/durable/m5_sync_bench_test.go +++ b/seaweed-block/core/frontend/durable/m5_sync_bench_test.go @@ -16,7 +16,7 @@ import ( ) func BenchmarkQD1PairedBackendSync(b *testing.B) { - for _, impl := range []durable.ImplName{durable.ImplSmartWAL, durable.ImplWALStoreChunk} { + for _, impl := range []durable.ImplName{durable.ImplWALStore, durable.ImplWALStoreChunk} { b.Run(string(impl), func(b *testing.B) { id := frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1} root := b.TempDir() diff --git a/seaweed-block/core/frontend/durable/m5_sync_concurrent_bench_test.go b/seaweed-block/core/frontend/durable/m5_sync_concurrent_bench_test.go index 2567a9d08a..da5c7bd22e 100644 --- a/seaweed-block/core/frontend/durable/m5_sync_concurrent_bench_test.go +++ b/seaweed-block/core/frontend/durable/m5_sync_concurrent_bench_test.go @@ -16,7 +16,7 @@ import ( ) func BenchmarkConcurrentBackendSync(b *testing.B) { - for _, impl := range []durable.ImplName{durable.ImplSmartWAL, durable.ImplWALStoreChunk} { + for _, impl := range []durable.ImplName{durable.ImplWALStore, durable.ImplWALStoreChunk} { for _, qd := range []int{8, 32} { b.Run(fmt.Sprintf("%s/QD%d", impl, qd), func(b *testing.B) { id := frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1} diff --git a/seaweed-block/core/frontend/durable/m5_sync_crash_test.go b/seaweed-block/core/frontend/durable/m5_sync_crash_test.go index aaee58e60b..5e0f97acea 100644 --- a/seaweed-block/core/frontend/durable/m5_sync_crash_test.go +++ b/seaweed-block/core/frontend/durable/m5_sync_crash_test.go @@ -66,7 +66,7 @@ func TestQD1BackendSyncCrashWriter(t *testing.T) { } func TestQD1BackendSyncCrashReopen(t *testing.T) { - for _, impl := range []durable.ImplName{durable.ImplSmartWAL} { + for _, impl := range []durable.ImplName{durable.ImplWALStore} { t.Run(string(impl), func(t *testing.T) { root := t.TempDir() childCtx, cancelChild := context.WithTimeout(context.Background(), 30*time.Second) diff --git a/seaweed-block/core/frontend/durable/perf_baseline_test.go b/seaweed-block/core/frontend/durable/perf_baseline_test.go index 1549e67a8c..e2f8f287c0 100644 --- a/seaweed-block/core/frontend/durable/perf_baseline_test.go +++ b/seaweed-block/core/frontend/durable/perf_baseline_test.go @@ -29,7 +29,7 @@ import ( // eventually-consistent and can't drain faster than this // benchmark writes). For real sustained numbers, run m01 fio. // This benchmark exists to publish first-light relative -// per-op cost between walstore and smartwal; it does NOT claim +// per-op cost between durable engines; it does NOT claim // to saturate either impl. func BenchmarkT3c_DurablePerf(b *testing.B) { for _, impl := range implMatrix() { diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index 0a00bd16c8..d623459fd9 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -41,8 +41,6 @@ import ( "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" "github.com/seaweedfs/seaweed-block/core/geometry" "github.com/seaweedfs/seaweed-block/core/storage" - "github.com/seaweedfs/seaweed-block/core/storage/parallelwal" - "github.com/seaweedfs/seaweed-block/core/storage/smartwal" ) // ImplName is the user-facing selector for the LogicalStorage @@ -54,16 +52,8 @@ const ( // ImplAuto (the zero value) opens an existing volume with the // implementation its on-disk superblock names, and creates a new // volume as ImplWALStore. - ImplAuto ImplName = "" - // ImplSmartWAL is experimental: in-place overwrites have no rollback - // on a torn write, blocks lose their per-block CRC once their ring - // records recycle, and it has no chunk-snapshot support. Selected only - // explicitly, or by auto for an existing smartwal volume. - ImplSmartWAL ImplName = "smartwal" + ImplAuto ImplName = "" ImplWALStore ImplName = "walstore" - // ImplParallelWALStore is the explicit Phase 167 candidate. It remains - // opt-in until the full recovery, replication, and mounted close gates pass. - ImplParallelWALStore ImplName = "parallel-walstore" // ImplWALStoreChunk is a walstore volume with an attached chunk layer: // an asynchronous remote copy of immutable chunks published by a HEAD // compare-and-swap. On disk it is a walstore file. Requires @@ -109,8 +99,13 @@ func (e *RemovedEngineError) Error() string { } // RemovedEngineName returns the typed refusal for a selector naming a removed -// experimental engine, or nil. (Seam: nothing is refused yet.) -func RemovedEngineName(name string) error { return nil } +// experimental engine, or nil. +func RemovedEngineName(name string) error { + if _, ok := removedEngines[ImplName(name)]; ok { + return &RemovedEngineError{Engine: ImplName(name)} + } + return nil +} // ErrVolumeNotOpen is returned by RecoverVolume / Close when the // volumeID has not been Open'd. @@ -171,9 +166,6 @@ type ProviderConfig struct { // - ImplWALStore (append-only): WAL retention is purely the // scan-time gate; non-zero value relaxes the gate to // fromLSN > checkpointLSN - WALRetentionLSNs. - // - ImplSmartWAL (fixed-size ring): retention is implicit from - // ring capacity (--durable-blocks). This flag is informational - // for ImplSmartWAL; operators size retention via NumBlocks. // // Pinned by: INV-G6-RETENTION-POLICY-OPERATOR-VISIBLE. WALRetentionLSNs uint64 @@ -401,7 +393,7 @@ type VolumeStatus struct { HeadWrites map[layout.HeadWriteCause]uint64 // acknowledged HEAD writes by cause since holder catalog start; unknown replies excluded VolumeID string // the volume Path string // its store path under --durable-root - Impl string // the durable implementation (walstore, smartwal, walstore-chunk, ...) + Impl string // the durable implementation (walstore or walstore-chunk) ReplicaID string // the replica this store holds StoreID string `json:",omitempty"` // the store's superblock UUID (hex); empty when it carries none Epoch uint64 // the epoch the store is latched to; 0 before an assignment @@ -456,9 +448,12 @@ func NewDurableProvider(cfg ProviderConfig, view frontend.ProjectionView) (*Dura if cfg.StorageRoot == "" { return nil, fmt.Errorf("durable: ProviderConfig.StorageRoot required") } - if cfg.Impl != ImplAuto && cfg.Impl != ImplSmartWAL && cfg.Impl != ImplWALStore && cfg.Impl != ImplParallelWALStore && cfg.Impl != ImplWALStoreChunk { - return nil, fmt.Errorf("durable: unknown impl %q (want auto (empty), %q, %q, %q, or %q)", - cfg.Impl, ImplSmartWAL, ImplWALStore, ImplParallelWALStore, ImplWALStoreChunk) + if err := RemovedEngineName(string(cfg.Impl)); err != nil { + return nil, err + } + if cfg.Impl != ImplAuto && cfg.Impl != ImplWALStore && cfg.Impl != ImplWALStoreChunk { + return nil, fmt.Errorf("durable: unknown impl %q (want auto (empty), %q, or %q)", + cfg.Impl, ImplWALStore, ImplWALStoreChunk) } if (cfg.ChunkLayoutHeadFor == nil) != (cfg.ChunkLayoutRemoteFor == nil) { return nil, errors.New("durable: both layout factories are required") @@ -970,15 +965,24 @@ func (p *DurableProvider) verifyImplOnDisk(path string) (ImplName, error) { if _, err := io.ReadFull(f, magic); err != nil { return "", fmt.Errorf("durable: read magic: %w", err) } + // A volume a removed experimental engine created is refused typed under + // every selector, before any selector comparison. + for engine, m := range removedEngines { + if string(magic) == m { + return "", &RemovedEngineError{Engine: engine, Path: path} + } + } diskImpl, ok := magicToImpl(string(magic)) if !ok { - // parallelwal has two independently checksummed headers. Slot 0 - // may be torn while slot 1 remains authoritative, so fall back to - // the format's real header selector instead of rejecting on byte 0. - if err := parallelwal.ProbeStore(path); err == nil { - diskImpl, ok = ImplParallelWALStore, true - } else if err := storage.ProbeWALStoreV3(path); err == nil { + if err := storage.ProbeWALStoreV3(path); err == nil { diskImpl, ok = ImplWALStore, true + } else { + // a parallel-walstore volume whose first header is torn still + // carries its magic in the second + slot1 := make([]byte, 4) + if _, err := f.ReadAt(slot1, parallelHeaderSlot1); err == nil && string(slot1) == removedEngines["parallel-walstore"] { + return "", &RemovedEngineError{Engine: "parallel-walstore", Path: path} + } } } if !ok { @@ -998,17 +1002,12 @@ func (p *DurableProvider) verifyImplOnDisk(path string) (ImplName, error) { return diskImpl, nil } -// magicToImpl maps a 4-byte magic to ImplName. Hardcoded per -// on-disk magic constants in core/storage and core/storage/smartwal. -// Keep in sync when new impls land (caught at T3c matrix test time). +// magicToImpl maps a 4-byte magic to ImplName, per the on-disk magic +// constant in core/storage. The removed engines' magics are refused before it. func magicToImpl(magic string) (ImplName, bool) { switch magic { case "SWBK": return ImplWALStore, true - case "SWAW": - return ImplSmartWAL, true - case "SWPW": - return ImplParallelWALStore, true default: return "", false } @@ -1051,18 +1050,6 @@ func (p *DurableProvider) openExisting(volumeID, path string, impl ImplName) (*v ws.DisableAutoFlushForRecoveryTest() } s = ws - case ImplSmartWAL: - sw, err := smartwal.OpenStore(path) - if err != nil { - return nil, fmt.Errorf("durable: smartwal.OpenStore %s: %w", path, err) - } - s = sw - case ImplParallelWALStore: - pw, err := parallelwal.OpenStore(path) - if err != nil { - return nil, fmt.Errorf("durable: parallelwal.OpenStore %s: %w", path, err) - } - s = pw default: return nil, fmt.Errorf("durable: unknown impl %q", impl) } @@ -1114,18 +1101,6 @@ func (p *DurableProvider) createFresh(volumeID, path string, impl ImplName) (*vo ws.DisableAutoFlushForRecoveryTest() } s = ws - case ImplSmartWAL: - sw, err := smartwal.CreateStore(path, p.cfg.NumBlocks, p.cfg.BlockSize) - if err != nil { - return nil, fmt.Errorf("durable: smartwal.CreateStore %s: %w", path, err) - } - s = sw - case ImplParallelWALStore: - pw, err := parallelwal.CreateStore(path, p.cfg.NumBlocks, p.cfg.BlockSize) - if err != nil { - return nil, fmt.Errorf("durable: parallelwal.CreateStore %s: %w", path, err) - } - s = pw default: return nil, fmt.Errorf("durable: unknown impl %q", impl) } diff --git a/seaweed-block/core/frontend/durable/provider_auto_impl_test.go b/seaweed-block/core/frontend/durable/provider_auto_impl_test.go index 37d9023650..bc1e48ae54 100644 --- a/seaweed-block/core/frontend/durable/provider_auto_impl_test.go +++ b/seaweed-block/core/frontend/durable/provider_auto_impl_test.go @@ -15,10 +15,10 @@ import ( ) // The empty selector (ImplAuto) creates new volumes as walstore and opens an -// existing volume with the implementation its on-disk superblock names, so -// volumes created under the old smartwal default keep opening. An explicit -// selector still refuses a different on-disk format -// (TestT3b_DurableProvider_Open_ImplKindMismatch_FailsFast). +// existing volume with the implementation its on-disk superblock names. A +// volume a removed experimental engine created (smartwal, parallel-walstore) +// is refused typed under every selector, and never modified +// (TestDurableProvider_RefusesRemovedEngineVolumes). func autoProvider(t *testing.T, root string, impl durable.ImplName) *durable.DurableProvider { t.Helper() @@ -118,7 +118,7 @@ func TestDurableProvider_AutoOpensV3FallbackSlot(t *testing.T) { } func TestDurableProvider_AutoOpensExistingVolumeByOnDiskFormat(t *testing.T) { - for _, impl := range []durable.ImplName{durable.ImplSmartWAL, durable.ImplWALStore, durable.ImplParallelWALStore} { + for _, impl := range []durable.ImplName{durable.ImplWALStore} { t.Run(string(impl), func(t *testing.T) { root := t.TempDir() created := autoProvider(t, root, impl) diff --git a/seaweed-block/core/frontend/durable/provider_chunk_test.go b/seaweed-block/core/frontend/durable/provider_chunk_test.go index b5756737d6..3fb0549583 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk_test.go +++ b/seaweed-block/core/frontend/durable/provider_chunk_test.go @@ -9,6 +9,8 @@ import ( "bytes" "context" "errors" + "os" + "path/filepath" "reflect" "testing" "time" @@ -345,18 +347,17 @@ func TestWALStoreChunk_SelectorRules(t *testing.T) { if _, err := plain.CaptureVolume(context.Background(), "v1"); !errors.Is(err, durable.ErrNotChunkVolume) { t.Fatalf("CaptureVolume on a plain walstore volume: got %v", err) } - // A smartwal file is not a chunk volume. + // A removed engine's volume is not a chunk volume: the chunk selector + // refuses it typed too. root := t.TempDir() - sw, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplSmartWAL, StorageRoot: root, NumBlocks: pcBlocks}, view) - if err != nil { + sw := make([]byte, 8192) + copy(sw, "SWAW") + if err := os.WriteFile(filepath.Join(root, "v1.bin"), sw, 0o600); err != nil { t.Fatal(err) } - if _, err := sw.EnsureStorage("v1"); err != nil { - t.Fatal(err) - } - _ = sw.Close() p := layoutChunkProvider(t, root, testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks), view, 0) - if _, err := p.EnsureStorage("v1"); !errors.Is(err, durable.ErrImplKindMismatch) { - t.Fatalf("walstore-chunk over a smartwal file: got %v, want ErrImplKindMismatch", err) + var removed *durable.RemovedEngineError + if _, err := p.EnsureStorage("v1"); !errors.As(err, &removed) || removed.Engine != "smartwal" { + t.Fatalf("walstore-chunk over a removed engine's volume: got %v, want the typed removed-engine refusal", err) } } diff --git a/seaweed-block/core/frontend/durable/provider_test.go b/seaweed-block/core/frontend/durable/provider_test.go index 91c3c4afba..3f8a9e79e2 100644 --- a/seaweed-block/core/frontend/durable/provider_test.go +++ b/seaweed-block/core/frontend/durable/provider_test.go @@ -17,14 +17,11 @@ import ( "github.com/seaweedfs/seaweed-block/core/frontend" "github.com/seaweedfs/seaweed-block/core/frontend/durable" "github.com/seaweedfs/seaweed-block/core/storage" - "github.com/seaweedfs/seaweed-block/core/storage/parallelwal" ) func implMatrix() []durable.ImplName { return []durable.ImplName{ - durable.ImplSmartWAL, durable.ImplWALStore, - durable.ImplParallelWALStore, } } @@ -248,10 +245,6 @@ func TestT3b_DurableProvider_Open_SelectsImpl_Matrix(t *testing.T) { switch impl { case durable.ImplWALStore: expectMagic = "SWBK" - case durable.ImplSmartWAL: - expectMagic = "SWAW" - case durable.ImplParallelWALStore: - expectMagic = "SWPW" } if magic != expectMagic { t.Errorf("on-disk magic=%q want %q (impl=%s)", magic, expectMagic, impl) @@ -284,111 +277,6 @@ func TestT3b_DurableProvider_Open_StartsNotOperational(t *testing.T) { } } -// #4 — ImplKind mismatch between selector and on-disk superblock -// fails fast with named error. -func TestT3b_DurableProvider_Open_ImplKindMismatch_FailsFast(t *testing.T) { - root := t.TempDir() - id := frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1} - view := newStubView(healthyProj(id)) - - // Step 1: create a file with impl=smartwal. - pSmart, err := durable.NewDurableProvider(durable.ProviderConfig{ - Impl: durable.ImplSmartWAL, - StorageRoot: root, - BlockSize: 4096, - NumBlocks: 16, - }, view) - if err != nil { - t.Fatalf("create smartwal provider: %v", err) - } - if _, err := pSmart.Open(context.Background(), "v1"); err != nil { - t.Fatalf("smartwal Open: %v", err) - } - _ = pSmart.Close() - - // Step 2: open the same file with selector=walstore — must fail. - pWAL, err := durable.NewDurableProvider(durable.ProviderConfig{ - Impl: durable.ImplWALStore, - StorageRoot: root, - BlockSize: 4096, - NumBlocks: 16, - }, view) - if err != nil { - t.Fatalf("create walstore provider: %v", err) - } - defer pWAL.Close() - - _, err = pWAL.Open(context.Background(), "v1") - if err == nil { - t.Fatal("want ImplKind mismatch error, got nil (silent coerce)") - } - if !errors.Is(err, durable.ErrImplKindMismatch) { - t.Fatalf("want ErrImplKindMismatch, got %v", err) - } -} - -func TestDurableProviderParallelWALUsesDualHeaderProbe(t *testing.T) { - root := t.TempDir() - path := filepath.Join(root, "v1.bin") - s, err := parallelwal.CreateStoreWithConfig(path, parallelwal.Config{ - NumBlocks: 16, - BlockSize: 4096, - LaneCount: 4, - StripeBlocks: 1, - SlotsPerLane: 128, - QueueDepth: 64, - }) - if err != nil { - t.Fatal(err) - } - if _, err := s.Write(0, bytes.Repeat([]byte{0x71}, 4096)); err != nil { - t.Fatal(err) - } - if _, err := s.Sync(); err != nil { - t.Fatal(err) - } - if err := s.Close(); err != nil { - t.Fatal(err) - } - f, err := os.OpenFile(path, os.O_RDWR, 0o644) - if err != nil { - t.Fatal(err) - } - if _, err := f.WriteAt([]byte("BAD!"), 0); err != nil { - _ = f.Close() - t.Fatal(err) - } - if err := f.Close(); err != nil { - t.Fatal(err) - } - - id := frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1} - p, err := durable.NewDurableProvider(durable.ProviderConfig{ - Impl: durable.ImplParallelWALStore, - StorageRoot: root, - BlockSize: 4096, - NumBlocks: 16, - }, newStubView(healthyProj(id))) - if err != nil { - t.Fatal(err) - } - defer p.Close() - raw, err := p.EnsureStorage("v1") - if err != nil { - t.Fatalf("EnsureStorage should recover from header slot 1: %v", err) - } - if _, err := p.RecoverVolume(context.Background(), "v1"); err != nil { - t.Fatalf("RecoverVolume should select header slot 1: %v", err) - } - got, err := raw.Read(0) - if err != nil { - t.Fatal(err) - } - if got[0] != 0x71 { - t.Fatalf("recovered byte=%02x want=71", got[0]) - } -} - // readFirstMagic reads the first 4 bytes of a file to peek magic. func readFirstMagic(path string) (string, error) { f, err := os.Open(path) diff --git a/seaweed-block/core/frontend/durable/storage_adapter.go b/seaweed-block/core/frontend/durable/storage_adapter.go index bb7acc7a1b..4ff20649ae 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter.go +++ b/seaweed-block/core/frontend/durable/storage_adapter.go @@ -1,8 +1,8 @@ // Package durable implements the T3a bridge between V3 // `core/storage.LogicalStorage` and `core/frontend.Backend`. // -// `StorageBackend` wraps any `LogicalStorage` (walstore, smartwal, -// or any future impl) and exposes the `frontend.Backend` surface +// `StorageBackend` wraps any `LogicalStorage` (walstore, the in-memory +// stores, or any future impl) and exposes the `frontend.Backend` surface // iSCSI and NVMe consume. Responsibilities: // // 1. byte ↔ LBA translation (G-int.1). diff --git a/seaweed-block/core/frontend/durable/storage_adapter_test.go b/seaweed-block/core/frontend/durable/storage_adapter_test.go index f682e95172..766a1d4c26 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter_test.go +++ b/seaweed-block/core/frontend/durable/storage_adapter_test.go @@ -1,6 +1,6 @@ // T3a adapter tests — matrix-parameterized per Addendum A #1. -// EVERY test runs against walstore, smartwal.Store, and parallelwal.Store so -// variant skew is caught at L1 instead of prod. +// EVERY test runs against every registered LogicalStorage (walstore, the one +// durable engine) so variant skew is caught at L1 instead of prod. // // Acceptance-criteria mapping (mini plan §2): // #1 TestT3a_StorageBackend_ImplementsBackend @@ -27,8 +27,6 @@ import ( "github.com/seaweedfs/seaweed-block/core/frontend/durable" "github.com/seaweedfs/seaweed-block/core/storage" "github.com/seaweedfs/seaweed-block/core/storage/memorywal" - "github.com/seaweedfs/seaweed-block/core/storage/parallelwal" - "github.com/seaweedfs/seaweed-block/core/storage/smartwal" ) type writeObserverFunc struct { @@ -207,39 +205,6 @@ func logicalStorageFactories() []logicalStorageFactory { return s }, }, - { - name: "smartwal", - make: func(t *testing.T, numBlocks uint32, blockSize int) storage.LogicalStorage { - t.Helper() - path := filepath.Join(t.TempDir(), "smartwal.bin") - s, err := smartwal.CreateStore(path, numBlocks, blockSize) - if err != nil { - t.Fatalf("smartwal.CreateStore: %v", err) - } - t.Cleanup(func() { _ = s.Close() }) - return s - }, - }, - { - name: "parallelwal", - make: func(t *testing.T, numBlocks uint32, blockSize int) storage.LogicalStorage { - t.Helper() - path := filepath.Join(t.TempDir(), "parallelwal.bin") - s, err := parallelwal.CreateStoreWithConfig(path, parallelwal.Config{ - NumBlocks: numBlocks, - BlockSize: blockSize, - LaneCount: 4, - StripeBlocks: 1, - SlotsPerLane: 128, - QueueDepth: 64, - }) - if err != nil { - t.Fatalf("parallelwal.CreateStoreWithConfig: %v", err) - } - t.Cleanup(func() { _ = s.Close() }) - return s - }, - }, } } @@ -837,7 +802,7 @@ func TestT3a_MatrixCoverage(t *testing.T) { names = append(names, f.name) } got := fmt.Sprint(names) - want := "[walstore smartwal parallelwal]" + want := "[walstore]" if got != want { t.Fatalf("matrix drifted: got %s want %s", got, want) } diff --git a/seaweed-block/core/frontend/durable/t3b_qa_l1_addendum_test.go b/seaweed-block/core/frontend/durable/t3b_qa_l1_addendum_test.go index d112a9187f..9395625175 100644 --- a/seaweed-block/core/frontend/durable/t3b_qa_l1_addendum_test.go +++ b/seaweed-block/core/frontend/durable/t3b_qa_l1_addendum_test.go @@ -24,8 +24,6 @@ import ( "github.com/seaweedfs/seaweed-block/core/frontend" "github.com/seaweedfs/seaweed-block/core/frontend/durable" "github.com/seaweedfs/seaweed-block/core/storage" - "github.com/seaweedfs/seaweed-block/core/storage/parallelwal" - "github.com/seaweedfs/seaweed-block/core/storage/smartwal" ) // --- L1-1: ConcurrentIO_SyncBarrier --- @@ -129,21 +127,6 @@ func TestT3_Durable_RecoverThenServe(t *testing.T) { create: func(p string) (storage.LogicalStorage, error) { return storage.CreateWALStore(p, numBlocks, blockSize) }, reopen: func(p string) (storage.LogicalStorage, error) { return storage.OpenWALStore(p) }, }, - { - name: "smartwal", - create: func(p string) (storage.LogicalStorage, error) { return smartwal.CreateStore(p, numBlocks, blockSize) }, - reopen: func(p string) (storage.LogicalStorage, error) { return smartwal.OpenStore(p) }, - }, - { - name: "parallelwal", - create: func(p string) (storage.LogicalStorage, error) { - return parallelwal.CreateStoreWithConfig(p, parallelwal.Config{ - NumBlocks: numBlocks, BlockSize: blockSize, LaneCount: 4, - StripeBlocks: 1, SlotsPerLane: 128, QueueDepth: 64, - }) - }, - reopen: func(p string) (storage.LogicalStorage, error) { return parallelwal.OpenStore(p) }, - }, } for _, f := range factories { diff --git a/seaweed-block/core/frontend/durable/write_command_budget_p1_test.go b/seaweed-block/core/frontend/durable/write_command_budget_p1_test.go index e529b86102..7399790384 100644 --- a/seaweed-block/core/frontend/durable/write_command_budget_p1_test.go +++ b/seaweed-block/core/frontend/durable/write_command_budget_p1_test.go @@ -13,7 +13,7 @@ import ( ) // partialFaultStore commits the first block of a batch and returns that prefix -// together with a physical error (the shape parallelwal and smartwal return), +// together with a physical error (the shape a storage engine may return), // after the command's deadline has passed. type partialFaultStore struct { storage.LogicalStorage diff --git a/seaweed-block/core/frontend/iscsi/p2_sustained_sync_test.go b/seaweed-block/core/frontend/iscsi/p2_sustained_sync_test.go index 5492f4a244..a41302ae15 100644 --- a/seaweed-block/core/frontend/iscsi/p2_sustained_sync_test.go +++ b/seaweed-block/core/frontend/iscsi/p2_sustained_sync_test.go @@ -8,7 +8,7 @@ import ( "github.com/seaweedfs/seaweed-block/core/frontend" "github.com/seaweedfs/seaweed-block/core/frontend/durable" "github.com/seaweedfs/seaweed-block/core/frontend/iscsi" - "github.com/seaweedfs/seaweed-block/core/storage/smartwal" + "github.com/seaweedfs/seaweed-block/core/storage" ) type p2ProjectionView struct { @@ -17,11 +17,11 @@ type p2ProjectionView struct { func (v p2ProjectionView) Projection() frontend.Projection { return v.proj } -// TestP2_ISCSI_SustainedWriteSyncCache_SurvivesSmartWALReopen pins the +// TestP2_ISCSI_SustainedWriteSyncCache_SurvivesWALStoreReopen pins the // product-backed write/flush path that Linux filesystems depend on: // WRITE(10) reaches durable.StorageBackend, SYNCHRONIZE CACHE reaches // storage.Sync, and synced blocks survive a clean close/reopen. -func TestP2_ISCSI_SustainedWriteSyncCache_SurvivesSmartWALReopen(t *testing.T) { +func TestP2_ISCSI_SustainedWriteSyncCache_SurvivesWALStoreReopen(t *testing.T) { const ( blockSize = 4096 numBlocks = 128 @@ -32,10 +32,10 @@ func TestP2_ISCSI_SustainedWriteSyncCache_SurvivesSmartWALReopen(t *testing.T) { frontendByteSize = numBlocks * blockSize ) - path := filepath.Join(t.TempDir(), "smartwal.bin") - store, err := smartwal.CreateStore(path, numBlocks, blockSize) + path := filepath.Join(t.TempDir(), "walstore.bin") + store, err := storage.CreateWALStore(path, numBlocks, blockSize) if err != nil { - t.Fatalf("smartwal.CreateStore: %v", err) + t.Fatalf("storage.CreateWALStore: %v", err) } id := frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1} @@ -76,16 +76,16 @@ func TestP2_ISCSI_SustainedWriteSyncCache_SurvivesSmartWALReopen(t *testing.T) { t.Fatalf("target Close: %v", err) } if err := store.Close(); err != nil { - t.Fatalf("smartwal close: %v", err) + t.Fatalf("walstore close: %v", err) } - reopened, err := smartwal.OpenStore(path) + reopened, err := storage.OpenWALStore(path) if err != nil { - t.Fatalf("smartwal.OpenStore: %v", err) + t.Fatalf("storage.OpenWALStore: %v", err) } defer reopened.Close() if _, err := reopened.Recover(); err != nil { - t.Fatalf("smartwal Recover: %v", err) + t.Fatalf("walstore Recover: %v", err) } for _, lba := range []uint32{0, 7, 8, 23, 47} { diff --git a/seaweed-block/core/host/volume/recovery_typed_reason_test.go b/seaweed-block/core/host/volume/recovery_typed_reason_test.go index 8fb0ea837a..94d1caeeb1 100644 --- a/seaweed-block/core/host/volume/recovery_typed_reason_test.go +++ b/seaweed-block/core/host/volume/recovery_typed_reason_test.go @@ -1,11 +1,13 @@ package volume import ( + "context" "errors" "fmt" "io" "io/fs" "os" + "os/exec" "path/filepath" "syscall" "testing" @@ -13,7 +15,6 @@ import ( "github.com/seaweedfs/seaweed-block/core/frontend/durable" "github.com/seaweedfs/seaweed-block/core/storage" - "github.com/seaweedfs/seaweed-block/core/storage/smartwal" ) // #133: a local durable recovery failure is classified into a typed @@ -48,42 +49,53 @@ func TestLocalRecoveryHealthReason_Classifies(t *testing.T) { } } -// The actual caller chain: a corrupted smartwal store, durable.Recover -// (what DurableProvider.RecoverVolume runs at startup), then the host's +// The actual caller chain: a corrupted walstore (a committed WAL record +// damaged after a crash with no checkpoint), durable.Recover (what +// DurableProvider.RecoverVolume runs at startup), then the host's // ReportLocalRecoveryFailure; a primary-assigned replica reports // wal_corrupt at once, without waiting for the recover timeout. func TestLocalRecoveryFailure_CorruptWALReportsWALCorruptAtOnce(t *testing.T) { - path := filepath.Join(t.TempDir(), "v.sw") - s, err := smartwal.CreateStore(path, 16, 4096) - if err != nil { - t.Fatal(err) - } - for i := uint32(0); i < 3; i++ { - data := make([]byte, 4096) - data[0] = byte(0xA0 + i) - if _, err := s.Write(i, data); err != nil { + const childEnv = "SWBLOCK_HOST_CORRUPT_WAL_PATH" + if path := os.Getenv(childEnv); path != "" { + s, err := storage.CreateWALStoreWithOptions(path, 16, 4096, storage.WALStoreOptions{WMode: storage.WModeStrict}) + if err != nil { t.Fatal(err) } + s.DisableAutoFlushForRecoveryTest() + for i := uint32(0); i < 4; i++ { + data := make([]byte, 4096) + data[0] = byte(0xA0 + i) + if _, err := s.Write(i, data); err != nil { + t.Fatal(err) + } + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + os.Exit(0) // deliberately no Close/checkpoint: recovery must replay the WAL } - if _, err := s.Sync(); err != nil { - t.Fatal(err) - } - if err := s.Close(); err != nil { - t.Fatal(err) - } - layout, rec, err := smartwal.LatestRecord(path) - if err != nil { - t.Fatal(err) + path := filepath.Join(t.TempDir(), "v.bin") + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestLocalRecoveryFailure_CorruptWALReportsWALCorruptAtOnce$") + cmd.Env = append(os.Environ(), childEnv+"="+path) + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("crash fixture: %v\n%s", err, out) } f, err := os.OpenFile(path, os.O_RDWR, 0) if err != nil { t.Fatal(err) } - if _, err := f.WriteAt([]byte{0x5A}, layout.ExtentStart+int64(rec.LBA)*int64(layout.BlockSize)); err != nil { - t.Fatal(err) + at := int64(8192 + (70 + 4096) + 62 + 100) // the second committed record's payload + one := make([]byte, 1) + _, re := f.ReadAt(one, at) + one[0] ^= 0xff + _, we := f.WriteAt(one, at) + ce := f.Close() + if re != nil || we != nil || ce != nil { + t.Fatal(re, we, ce) } - _ = f.Close() - reopened, err := smartwal.OpenStore(path) + reopened, err := storage.OpenWALStore(path) if err != nil { t.Fatal(err) } diff --git a/seaweed-block/core/host/volume/status_server_test.go b/seaweed-block/core/host/volume/status_server_test.go index 8310f769fb..5fdae2574e 100644 --- a/seaweed-block/core/host/volume/status_server_test.go +++ b/seaweed-block/core/host/volume/status_server_test.go @@ -1001,7 +1001,7 @@ func TestStatusServer_DurableStatusEndpoint_EnabledAfterStart_ReturnsLineage(t * s.SetDurableStatusSource(stubDurableStatusSource{vols: []durable.VolumeStatus{{ VolumeID: "v1", Path: "/tmp/v1.bin", - Impl: "smartwal", + Impl: "walstore", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, @@ -1061,7 +1061,7 @@ func TestG9B_StatusProjection_ReturnedReplicaCanBeDurableReadyButFrontendNotRead s.SetDurableStatusSource(stubDurableStatusSource{vols: []durable.VolumeStatus{{ VolumeID: "v1", Path: "/tmp/v1.bin", - Impl: "smartwal", + Impl: "walstore", ReplicaID: "r1", Epoch: 2, EndpointVersion: 1, diff --git a/seaweed-block/core/launcher/k8s_renderer.go b/seaweed-block/core/launcher/k8s_renderer.go index 1e889df0b2..7ce916f4c2 100644 --- a/seaweed-block/core/launcher/k8s_renderer.go +++ b/seaweed-block/core/launcher/k8s_renderer.go @@ -64,9 +64,11 @@ func RenderBlockVolumeDeployments(plan lifecycle.BlockVolumeWorkloadPlan, cfg K8 cfg.DurableImpl = "walstore" } switch cfg.DurableImpl { - case "walstore", "smartwal", "parallel-walstore": + case "walstore": + case "smartwal", "parallel-walstore": + return nil, fmt.Errorf("launcher: durable impl %q is a removed experimental engine; a volume it created by a removed experimental engine; copy the data to a walstore volume with v1.0.x first", cfg.DurableImpl) default: - return nil, fmt.Errorf("launcher: durable impl %q invalid; want walstore, smartwal, or parallel-walstore", cfg.DurableImpl) + return nil, fmt.Errorf("launcher: durable impl %q invalid; want walstore", cfg.DurableImpl) } if cfg.StateHostPathBase != "" && path.Clean(cfg.DurableRootBase) != stateMountPath { return nil, fmt.Errorf("launcher: state hostPath requires durable root base %q, got %q", stateMountPath, cfg.DurableRootBase) diff --git a/seaweed-block/core/launcher/k8s_renderer_test.go b/seaweed-block/core/launcher/k8s_renderer_test.go index 11006076bd..6a9d88d730 100644 --- a/seaweed-block/core/launcher/k8s_renderer_test.go +++ b/seaweed-block/core/launcher/k8s_renderer_test.go @@ -91,17 +91,17 @@ func TestPhase152_K8sRenderer_RendersWALRecoveryTestDisableFlusherOptIn(t *testi } } -func TestPhase34_K8sRendererCanRenderSmartWALDurableImpl(t *testing.T) { - manifests, err := RenderBlockVolumeDeployments(sampleWorkloadPlan(), K8sRenderConfig{ - MasterAddr: "m:9333", - DurableImpl: "smartwal", - }) - if err != nil { - t.Fatalf("RenderBlockVolumeDeployments: %v", err) - } - raw := string(manifests[0].YAML) - if !strings.Contains(raw, "--durable-impl=smartwal") { - t.Fatalf("manifest missing smartwal durable impl:\n%s", raw) +// The removed experimental engines are refused with the advice an operator +// acts on; no manifest selects them. +func TestK8sRendererRefusesRemovedEngines(t *testing.T) { + for _, impl := range []string{"smartwal", "parallel-walstore"} { + _, err := RenderBlockVolumeDeployments(sampleWorkloadPlan(), K8sRenderConfig{ + MasterAddr: "m:9333", + DurableImpl: impl, + }) + if err == nil || !strings.Contains(err.Error(), "removed experimental engine") || !strings.Contains(err.Error(), "copy the data to a walstore volume with v1.0.x first") { + t.Fatalf("DurableImpl %q: err=%v, want the removed-engine refusal", impl, err) + } } } @@ -118,19 +118,6 @@ func TestPhase34_K8sRendererRejectsUnknownDurableImpl(t *testing.T) { } } -func TestPhase167_K8sRendererAllowsParallelWALStoreOptIn(t *testing.T) { - manifests, err := RenderBlockVolumeDeployments(sampleWorkloadPlan(), K8sRenderConfig{ - MasterAddr: "blockmaster.kube-system.svc.cluster.local:9333", - DurableImpl: "parallel-walstore", - }) - if err != nil { - t.Fatal(err) - } - if got := string(manifests[0].YAML); !strings.Contains(got, "--durable-impl=parallel-walstore") { - t.Fatalf("manifest missing parallel-walstore opt-in:\n%s", got) - } -} - func TestG15d_K8sRenderer_RF2UsesDistinctNamesAndPorts(t *testing.T) { manifests, err := RenderBlockVolumeDeployments(sampleWorkloadPlan(), K8sRenderConfig{MasterAddr: "m:9333"}) if err != nil { @@ -786,17 +773,3 @@ func TestK8sRenderer_MasterTLSMountsTheServersNodeSecret(t *testing.T) { t.Fatalf("external status with master TLS: %v, want refused", err) } } - -// The removed experimental engines are refused with the advice an operator -// acts on; no manifest selects them. -func TestK8sRendererRefusesRemovedEngines(t *testing.T) { - for _, impl := range []string{"smartwal", "parallel-walstore"} { - _, err := RenderBlockVolumeDeployments(sampleWorkloadPlan(), K8sRenderConfig{ - MasterAddr: "m:9333", - DurableImpl: impl, - }) - if err == nil || !strings.Contains(err.Error(), "removed experimental engine") || !strings.Contains(err.Error(), "copy the data to a walstore volume with v1.0.x first") { - t.Fatalf("DurableImpl %q: err=%v, want the removed-engine refusal", impl, err) - } - } -} diff --git a/seaweed-block/core/ops/volume_status_artifacts_test.go b/seaweed-block/core/ops/volume_status_artifacts_test.go index 66de3c1134..570d05fdce 100644 --- a/seaweed-block/core/ops/volume_status_artifacts_test.go +++ b/seaweed-block/core/ops/volume_status_artifacts_test.go @@ -230,7 +230,7 @@ func artifactTestCollector(masterErr error) VolumeStatusReportCollector { Durable: func(context.Context) ([]durable.VolumeStatus, error) { return []durable.VolumeStatus{{ VolumeID: "v1", - Impl: "smartwal", + Impl: "walstore", Path: "/var/lib/sw-block/v1.blk", ReplicaID: "r1", Epoch: 7, diff --git a/seaweed-block/core/ops/volume_status_report_collector_test.go b/seaweed-block/core/ops/volume_status_report_collector_test.go index 985941cb2e..f3f25389c3 100644 --- a/seaweed-block/core/ops/volume_status_report_collector_test.go +++ b/seaweed-block/core/ops/volume_status_report_collector_test.go @@ -173,7 +173,7 @@ func TestVolumeStatusReportCollector_ReturnedReplicaDurableReadyButFrontendFence Durable: func(context.Context) ([]durable.VolumeStatus, error) { return []durable.VolumeStatus{{ VolumeID: "v1", - Impl: "smartwal", + Impl: "walstore", Path: "/var/lib/sw-block/v1.blk", ReplicaID: "r2", Epoch: 12, diff --git a/seaweed-block/core/ops/volume_status_report_test.go b/seaweed-block/core/ops/volume_status_report_test.go index b8e60cb837..0d0eb0a46e 100644 --- a/seaweed-block/core/ops/volume_status_report_test.go +++ b/seaweed-block/core/ops/volume_status_report_test.go @@ -65,7 +65,7 @@ func TestBuildVolumeStatusReport_ComposesExistingStatusSurfaces(t *testing.T) { { VolumeID: "v1", Path: "/var/lib/sw-block/v1.bin", - Impl: "smartwal", + Impl: "walstore", ReplicaID: "r1", Epoch: 2, EndpointVersion: 3, @@ -211,7 +211,7 @@ func TestBuildVolumeStatusReport_JSONSchemaShapeIsStable(t *testing.T) { {ReplicaID: "r2", State: "healthy", DataAddr: "127.0.0.1:10001", CtrlAddr: "127.0.0.1:10002", SessionID: 10}, }, Durable: []durable.VolumeStatus{ - {VolumeID: "v1", Impl: "smartwal", Path: "/var/lib/sw-block/v1.blk", ReplicaID: "r1", Epoch: 3, EndpointVersion: 4, Latched: true, Operational: true, FrontierKnown: true, DurableLSN: 9, RetainedLSN: 1, HeadLSN: 10}, + {VolumeID: "v1", Impl: "walstore", Path: "/var/lib/sw-block/v1.blk", ReplicaID: "r1", Epoch: 3, EndpointVersion: 4, Latched: true, Operational: true, FrontierKnown: true, DurableLSN: 9, RetainedLSN: 1, HeadLSN: 10}, }, Residue: ResidueReport{ HostInitiator: HostInitiatorResidue{ISCSISessions: []string{}, NVMESubsystems: []string{}}, @@ -417,7 +417,7 @@ func TestBuildVolumeStatusReport_WritesSampleReportArtifact(t *testing.T) { Durable: []durable.VolumeStatus{ { VolumeID: "v1", - Impl: "smartwal", + Impl: "walstore", Path: "/var/lib/sw-block/v1.blk", ReplicaID: "r1", Epoch: 7, diff --git a/seaweed-block/core/replication/component/cluster.go b/seaweed-block/core/replication/component/cluster.go index d1ce45f6d8..c217cb76a0 100644 --- a/seaweed-block/core/replication/component/cluster.go +++ b/seaweed-block/core/replication/component/cluster.go @@ -21,7 +21,6 @@ import ( "github.com/seaweedfs/seaweed-block/core/replication" "github.com/seaweedfs/seaweed-block/core/storage" "github.com/seaweedfs/seaweed-block/core/storage/memorywal" - "github.com/seaweedfs/seaweed-block/core/storage/smartwal" "github.com/seaweedfs/seaweed-block/core/transport" ) @@ -35,21 +34,7 @@ func setDefaultLogWriter(w io.Writer) { log.SetOutput(w) } // Returns the store + a cleanup func. type SubstrateFactory func(t *testing.T, dir, label string, blocks uint32, blockSize int) (storage.LogicalStorage, func()) -// Smartwal is the sign-bearing substrate factory. -func Smartwal(t *testing.T, dir, label string, blocks uint32, blockSize int) (storage.LogicalStorage, func()) { - t.Helper() - path := filepath.Join(dir, label+".smartwal") - s, err := smartwal.CreateStore(path, blocks, blockSize) - if err != nil { - t.Fatalf("%s: smartwal.CreateStore: %v", label, err) - } - return s, func() { - _ = s.Close() - _ = os.Remove(path) - } -} - -// Walstore is the second matrix row. +// Walstore is the gating on-disk substrate factory. func Walstore(t *testing.T, dir, label string, blocks uint32, blockSize int) (storage.LogicalStorage, func()) { t.Helper() path := filepath.Join(dir, label+".walstore") diff --git a/seaweed-block/core/replication/component/cluster_test.go b/seaweed-block/core/replication/component/cluster_test.go index 3d49ea5369..ab2aeb4e52 100644 --- a/seaweed-block/core/replication/component/cluster_test.go +++ b/seaweed-block/core/replication/component/cluster_test.go @@ -17,7 +17,7 @@ import ( // (b) a copy-paste template for QA authoring more T4c / T4d // scenarios. Aim: each new scenario takes ~20-30 lines. // -// All tests run against the smartwal+walstore matrix unless the +// All tests run against the substrate matrix (walstore) unless the // scenario specifically pins one substrate. // TestComponent_HappyCatchUp is the simplest possible scenario: @@ -48,12 +48,10 @@ func TestComponent_HappyCatchUp(t *testing.T) { // We wrap the primary substrate with a stub that always returns // ErrWALRecycled to avoid the heavy walstore checkpoint dance. func TestComponent_GapExceedsRetention_Recycled(t *testing.T) { - // Smartwal-only because the stub overrides ScanLBAs and the - // substrate-specific behavior under test is the recycle path, - // not the substrate-level scan semantics. The wrap pattern - // applies to either substrate; running once is enough for the - // pin. - component.RunSubstrate(t, "smartwal", component.Smartwal, func(t *testing.T, c *component.Cluster) { + // One substrate because the stub overrides ScanLBAs and the + // behavior under test is the recycle path, not the substrate-level + // scan semantics; running once is enough for the pin. + component.RunSubstrate(t, "walstore", component.Walstore, func(t *testing.T, c *component.Cluster) { c.WithReplicas(1).Start() c.PrimaryWriteN(1) // make H>0 so probe doesn't reject @@ -202,10 +200,14 @@ func TestComponent_RecoveryModeLabel_Walstore(t *testing.T) { }) } -// TestComponent_RecoveryModeLabel_Smartwal — pins that smartwal + -// in-memory substrates emit the state_convergence label. -func TestComponent_RecoveryModeLabel_Smartwal(t *testing.T) { - component.RunSubstrate(t, "smartwal", component.Smartwal, func(t *testing.T, c *component.Cluster) { +// TestComponent_RecoveryModeLabel_BlockStore — pins that the in-memory +// BlockStore substrate emits the state_convergence label. +func TestComponent_RecoveryModeLabel_BlockStore(t *testing.T) { + blockStore := func(t *testing.T, _, _ string, blocks uint32, blockSize int) (storage.LogicalStorage, func()) { + s := storage.NewBlockStore(blocks, blockSize) + return s, func() { _ = s.Close() } + } + component.RunSubstrate(t, "blockstore", blockStore, func(t *testing.T, c *component.Cluster) { c.WithReplicas(1).Start() c.PrimaryWriteN(3) c.PrimarySync() diff --git a/seaweed-block/core/replication/component/doc.go b/seaweed-block/core/replication/component/doc.go index f25947b6f8..006ba27012 100644 --- a/seaweed-block/core/replication/component/doc.go +++ b/seaweed-block/core/replication/component/doc.go @@ -9,7 +9,7 @@ // real localhost TCP using the actual production code paths // (BlockStore + ReplicaListener + BlockExecutor). // - A substrate matrix runner — every scenario runs against -// smartwal AND walstore, both gating per round-22. +// walstore, the one durable engine, gating. // - Network fault primitives: KillReplicaConnection / SeverTransport / // RestoreTransport — for catch-up + degraded scenarios that L1 // unit tests can't reach. @@ -44,8 +44,7 @@ // drive catch-up directly via executor.StartCatchUp until the // engine→adapter→executor wiring lands (forward-carry to T4d). // -// Substrate matrix: smartwal is sign-bearing; walstore is the -// second matrix row. Both are gating in this harness — there is no +// Substrate matrix: walstore is the gating row; there is no // "non-gating" demote; if walstore regresses, the test fails // honestly. See `core/replication/l2_integration_test.go` for the // QA round on this discipline. diff --git a/seaweed-block/core/replication/component/faults_test.go b/seaweed-block/core/replication/component/faults_test.go index c55ee16e92..11fa121522 100644 --- a/seaweed-block/core/replication/component/faults_test.go +++ b/seaweed-block/core/replication/component/faults_test.go @@ -126,7 +126,7 @@ func TestComponent_LiveShip_PrimaryWriteViaBackend_FansOut(t *testing.T) { // engine→adapter→executor recovery, this scenario gains real // coverage; today it exercises the API surface. func TestComponent_EngineDrivenRecovery_StubWarning(t *testing.T) { - component.RunSubstrate(t, "smartwal", component.Smartwal, func(t *testing.T, c *component.Cluster) { + component.RunSubstrate(t, "walstore", component.Walstore, func(t *testing.T, c *component.Cluster) { c.WithReplicas(1).WithEngineDrivenRecovery().Start() c.PrimaryWriteN(5) c.PrimarySync() diff --git a/seaweed-block/core/replication/component/g5_5c_restart_catchup_test.go b/seaweed-block/core/replication/component/g5_5c_restart_catchup_test.go index 0c1aa1e798..345a47f4df 100644 --- a/seaweed-block/core/replication/component/g5_5c_restart_catchup_test.go +++ b/seaweed-block/core/replication/component/g5_5c_restart_catchup_test.go @@ -246,7 +246,7 @@ func anyError(fn func() error) error { // // Bounded by short deadlines on every wait; CI flake guard in place. func TestG5_5C_RestartCatchUp_Convergence(t *testing.T) { - c := NewCluster(t, Smartwal). + c := NewCluster(t, Walstore). WithReplicas(1). WithBlockGeometry(64, 4096). WithLiveShip(). @@ -309,7 +309,7 @@ func TestG5_5C_RestartCatchUp_Convergence(t *testing.T) { // pass trivially via a different reconvergence pathway (e.g., next // natural ship retry on a write). func TestG5_5C_RestartCatchUp_NoConvergence_WithoutProbeLoop(t *testing.T) { - c := NewCluster(t, Smartwal). + c := NewCluster(t, Walstore). WithReplicas(1). WithBlockGeometry(64, 4096). WithLiveShip(). diff --git a/seaweed-block/core/replication/component/g9a_best_effort_recovery_test.go b/seaweed-block/core/replication/component/g9a_best_effort_recovery_test.go index 47ccb23255..90e3398b1d 100644 --- a/seaweed-block/core/replication/component/g9a_best_effort_recovery_test.go +++ b/seaweed-block/core/replication/component/g9a_best_effort_recovery_test.go @@ -8,7 +8,7 @@ import ( ) func TestG9A_BestEffortWriteStillFeedsLaggingReplicaRecovery(t *testing.T) { - c := NewCluster(t, Smartwal). + c := NewCluster(t, Walstore). WithReplicas(1). WithBlockGeometry(64, 4096). WithLiveShip(). diff --git a/seaweed-block/core/replication/component/matrix.go b/seaweed-block/core/replication/component/matrix.go index a2b57ba4ab..6ce49d18ea 100644 --- a/seaweed-block/core/replication/component/matrix.go +++ b/seaweed-block/core/replication/component/matrix.go @@ -2,8 +2,8 @@ package component import "testing" -// RunMatrix runs the given scenario against each substrate factory. -// Both rows are gating; smartwal is sign-bearing per round-22. +// RunMatrix runs the given scenario against each gating on-disk substrate +// factory (walstore, the one durable engine). // // Authoring shape: // @@ -19,9 +19,6 @@ import "testing" // teardown automatically. func RunMatrix(t *testing.T, scenario func(t *testing.T, c *Cluster)) { t.Helper() - t.Run("smartwal", func(t *testing.T) { - scenario(t, NewCluster(t, Smartwal)) - }) t.Run("walstore", func(t *testing.T) { scenario(t, NewCluster(t, Walstore)) }) diff --git a/seaweed-block/core/replication/component/midrecovery/mid_recovery_count_test.go b/seaweed-block/core/replication/component/midrecovery/mid_recovery_count_test.go index f1a870b0c1..1e178a207a 100644 --- a/seaweed-block/core/replication/component/midrecovery/mid_recovery_count_test.go +++ b/seaweed-block/core/replication/component/midrecovery/mid_recovery_count_test.go @@ -74,7 +74,7 @@ func TestReplicaMidCatchUpNeverCompletesAWrite(t *testing.T) { for _, store := range []struct { name string factory component.SubstrateFactory - }{{"walstore", component.Walstore}, {"smartwal", component.Smartwal}} { + }{{"walstore", component.Walstore}} { for _, mode := range []struct { name string replicas int diff --git a/seaweed-block/core/replication/component/qa_t4c_scenarios_test.go b/seaweed-block/core/replication/component/qa_t4c_scenarios_test.go index 84eb9fa768..92c4e6f2e3 100644 --- a/seaweed-block/core/replication/component/qa_t4c_scenarios_test.go +++ b/seaweed-block/core/replication/component/qa_t4c_scenarios_test.go @@ -6,7 +6,7 @@ package component_test // Authoring discipline (per design memo + framework guide): // - Each scenario pins ≥1 invariant from catalogue §3.3 // - Use RunMatrix when invariant applies to both substrates -// - Use RunSubstrate(...,Smartwal/Walstore,...) when substrate-mode +// - Use RunSubstrate(...,Walstore/MemoryWAL,...) when substrate-mode // specific (per memo §13.0a) // - Don't reach into framework internals — surface a primitive gap // to sw if missing @@ -97,12 +97,12 @@ func TestT4c_QA_ProbeCrossFlowWithRebuild_NonMutating(t *testing.T) { // text drifts, engine's retry-loop escalation logic silently breaks. // This test is a regression fence on the cross-package contract. // -// Smartwal-only because the recycled stub overrides ScanLBAs (same +// One substrate because the recycled stub overrides ScanLBAs (same // pattern as `TestComponent_GapExceedsRetention_Recycled` in the // demo file); the substrate-specific scan semantic is not under test // here, only the sentinel propagation. func TestT4c_QA_RetryBudget_RecycledFailureSentinelStable(t *testing.T) { - component.RunSubstrate(t, "smartwal", component.Smartwal, + component.RunSubstrate(t, "walstore", component.Walstore, func(t *testing.T, c *component.Cluster) { c.WithReplicas(1).Start() c.PrimaryWriteN(2) // make H>0 so probe doesn't reject diff --git a/seaweed-block/core/replication/component/t4d3_scenarios_test.go b/seaweed-block/core/replication/component/t4d3_scenarios_test.go index 37a41242d4..5092028541 100644 --- a/seaweed-block/core/replication/component/t4d3_scenarios_test.go +++ b/seaweed-block/core/replication/component/t4d3_scenarios_test.go @@ -12,7 +12,6 @@ import ( // T4d-3 component scenarios per G-1 §7 test parity matrix: // // - TestT4d3_CatchUp_NonEmptyReplica_ShortGap_BandwidthBounded_Walstore -// - TestT4d3_CatchUp_NonEmptyReplica_ShortGap_BandwidthBounded_Smartwal // - TestT4d3_RetryAfterReplicaAdvanced_OverScansHandledByApplyGate // (round-46 ADDITION 1 — pins §6.2 Option A safety claim) // - TestT4d3_RecoveryTargetLSN1_RoutesByConnectionContext @@ -85,40 +84,6 @@ func TestT4d3_CatchUp_NonEmptyReplica_ShortGap_BandwidthBounded_Walstore(t *test }) } -// TestT4d3_CatchUp_NonEmptyReplica_ShortGap_BandwidthBounded_Smartwal -// mirror on smartwal substrate. -func TestT4d3_CatchUp_NonEmptyReplica_ShortGap_BandwidthBounded_Smartwal(t *testing.T) { - component.RunSubstrate(t, "smartwal", component.Smartwal, func(t *testing.T, c *component.Cluster) { - count := new(atomic.Int32) - c.WithReplicas(1). - WithPrimaryStorageWrap(func(inner storage.LogicalStorage) storage.LogicalStorage { - return &observingScanWrap{LogicalStorage: inner, count: count} - }). - Start() - - for i := 0; i < 5; i++ { - data := make([]byte, component.DefaultBlockSize) - data[0] = byte(i + 1) - lsn := c.PrimaryWrite(uint32(i), data) - c.ReplicaApply(0, uint32(i), data, lsn) - } - for i := 5; i < 10; i++ { - data := make([]byte, component.DefaultBlockSize) - data[0] = byte(i + 1) - c.PrimaryWrite(uint32(i), data) - } - c.PrimarySync() - - c.CatchUpReplica(0) - - emitted := count.Load() - if emitted == 0 { - t.Fatal("smartwal ScanLBAs emitted 0 entries") - } - t.Logf("smartwal catch-up emitted %d entries", emitted) - }) -} - // TestT4d3_RetryAfterReplicaAdvanced_OverScansHandledByApplyGate // pins round-46 G-1 ADDITION 1: §6.2 Option A safety claim — when // engine retry re-emits with original Recovery.R+1, and replica's diff --git a/seaweed-block/core/replication/integration_t4b_test.go b/seaweed-block/core/replication/integration_t4b_test.go index e5cc462a36..7f3cdfbca9 100644 --- a/seaweed-block/core/replication/integration_t4b_test.go +++ b/seaweed-block/core/replication/integration_t4b_test.go @@ -18,9 +18,8 @@ package replication // 32B lineage + 8B AchievedLSN). Catches any future refactor that // silently weakens to epoch-only or short form. // -// Matrix discipline: smartwal is product-signing substrate; walstore -// is also gating in this harness (T4a-6 follow-up removed the -// 'non-gating' fiction). Both impls expected to pass at L2. +// Matrix discipline: walstore, the one durable engine, gates in this +// harness. import ( "bytes" diff --git a/seaweed-block/core/replication/l2_integration_test.go b/seaweed-block/core/replication/l2_integration_test.go index 219f25dfb8..fc1bf13eaa 100644 --- a/seaweed-block/core/replication/l2_integration_test.go +++ b/seaweed-block/core/replication/l2_integration_test.go @@ -15,13 +15,7 @@ package replication // together cover the T4a landing; see 2ed72bd for the honest // separation. // -// Matrix: smartwal is the sign-bearing substrate. walstore is a -// second row that also gates in this harness (QA finding #4 -// follow-up removed the earlier "non-gating" fiction; Go's testing -// framework has no clean demote-subtest-failure API, so pretending -// walstore could fail without failing the test was incorrect). If -// walstore ever regresses under BUG-007 the test fails honestly -// and we invest in a real demotion harness. +// Matrix: walstore, the one durable engine, gating. // // Frontend is approximated via direct StorageBackend.Write calls. // The full iSCSI/NVMe PDU layer is NOT exercised (iSCSI and NVMe @@ -41,7 +35,6 @@ import ( "github.com/seaweedfs/seaweed-block/core/frontend" "github.com/seaweedfs/seaweed-block/core/frontend/durable" "github.com/seaweedfs/seaweed-block/core/storage" - "github.com/seaweedfs/seaweed-block/core/storage/smartwal" "github.com/seaweedfs/seaweed-block/core/transport" ) @@ -51,28 +44,7 @@ import ( // exclusive to this test. Returns the store + a cleanup func. type storageFactory func(t *testing.T, dir, label string, blocks uint32, blockSize int) (storage.LogicalStorage, func()) -// smartwalFactory is the sign-bearing substrate. -func smartwalFactory(t *testing.T, dir, label string, blocks uint32, blockSize int) (storage.LogicalStorage, func()) { - t.Helper() - path := filepath.Join(dir, label+".smartwal") - s, err := smartwal.CreateStore(path, blocks, blockSize) - if err != nil { - t.Fatalf("%s: CreateStore: %v", label, err) - } - cleanup := func() { - _ = s.Close() - _ = os.Remove(path) - } - return s, cleanup -} - -// walstoreFactory is the second matrix row. Both rows are currently -// gating — T4a-6 follow-up (QA finding #4) removed the earlier -// "non-gating" fiction since Go's testing framework has no clean -// demote-subtest-failure API and the previous defer-based harness -// didn't actually demote. Both backends pass today; if walstore -// regresses under BUG-007 the test fails honestly and we invest in -// a real demotion harness then. +// walstoreFactory is the gating matrix row. func walstoreFactory(t *testing.T, dir, label string, blocks uint32, blockSize int) (storage.LogicalStorage, func()) { t.Helper() path := filepath.Join(dir, label+".walstore") @@ -87,18 +59,10 @@ func walstoreFactory(t *testing.T, dir, label string, blocks uint32, blockSize i return s, cleanup } -// runMatrix runs the given scenario against each storage backend. -// Both rows are gating in the current harness — see walstoreFactory -// comment for the QA-review history on the earlier non-gating -// fiction. T4a close requires smartwal to pass; walstore is -// expected to pass today (BUG-007 doesn't affect the best-effort -// write path T4a-6 exercises) but any regression will fail the -// test honestly. +// runMatrix runs the given scenario against each storage backend +// (walstore); any regression fails the test honestly. func runMatrix(t *testing.T, scenario func(t *testing.T, newStorage storageFactory)) { t.Helper() - t.Run("smartwal", func(t *testing.T) { - scenario(t, smartwalFactory) - }) t.Run("walstore", func(t *testing.T) { scenario(t, walstoreFactory) }) diff --git a/seaweed-block/core/replication/replica_next_lsn_test.go b/seaweed-block/core/replication/replica_next_lsn_test.go index af96a1921e..8816baee85 100644 --- a/seaweed-block/core/replication/replica_next_lsn_test.go +++ b/seaweed-block/core/replication/replica_next_lsn_test.go @@ -10,7 +10,6 @@ import ( "time" "github.com/seaweedfs/seaweed-block/core/storage" - "github.com/seaweedfs/seaweed-block/core/storage/smartwal" "github.com/seaweedfs/seaweed-block/core/transport" ) @@ -85,13 +84,6 @@ func newNextLSNReplica(t *testing.T, kind string, gate bool) *nextLSNReplica { } t.Cleanup(func() { _ = s.Close() }) base = s - case "smartwal": - s, err := smartwal.CreateStore(filepath.Join(dir, "r.smartwal"), 64, blockSize) - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { _ = s.Close() }) - base = s default: t.Fatalf("store kind %q", kind) } @@ -204,7 +196,6 @@ var nextLSNRows = []struct { gate bool }{ {"walstore", true}, - {"smartwal", true}, {"walstore", false}, } diff --git a/seaweed-block/core/storage/contract_test.go b/seaweed-block/core/storage/contract_test.go index 8c1fccbc09..d498a1b441 100644 --- a/seaweed-block/core/storage/contract_test.go +++ b/seaweed-block/core/storage/contract_test.go @@ -7,7 +7,6 @@ import ( "github.com/seaweedfs/seaweed-block/core/storage" "github.com/seaweedfs/seaweed-block/core/storage/memorywal" - "github.com/seaweedfs/seaweed-block/core/storage/parallelwal" ) // LogicalStorage is re-aliased for brevity inside this _test package. @@ -63,25 +62,6 @@ func implementations() []implFactory { return memorywal.NewStore(numBlocks, blockSize) }, }, - { - name: "ParallelWAL", - fresh: func(t *testing.T, dir string, numBlocks uint32, blockSize int) LogicalStorage { - path := filepath.Join(dir, "parallelwal.bin") - s, err := parallelwal.CreateStoreWithConfig(path, parallelwal.Config{ - NumBlocks: numBlocks, - BlockSize: blockSize, - LaneCount: 4, - StripeBlocks: 1, - SlotsPerLane: 128, - QueueDepth: 64, - }) - if err != nil { - t.Fatalf("Create parallelwal: %v", err) - } - t.Cleanup(func() { _ = s.Close() }) - return s - }, - }, } } diff --git a/seaweed-block/core/storage/logical_storage.go b/seaweed-block/core/storage/logical_storage.go index 9fb9a4176d..11fc0d74d5 100644 --- a/seaweed-block/core/storage/logical_storage.go +++ b/seaweed-block/core/storage/logical_storage.go @@ -26,7 +26,6 @@ type ContextReader interface { // Implementations expected behind this seam: // - in-memory (BlockStore) — fast, no persistence // - WAL+extent (WALStore) — single-file crash-safe backend -// - smartwal.Store — experimental backend in core/storage/smartwal/ // // What the contract guarantees (single-node): // diff --git a/seaweed-block/core/storage/memorywal/store.go b/seaweed-block/core/storage/memorywal/store.go index 4651dc8999..45c163126b 100644 --- a/seaweed-block/core/storage/memorywal/store.go +++ b/seaweed-block/core/storage/memorywal/store.go @@ -25,7 +25,6 @@ // // - core/storage (BlockStore): minimal in-memory current-state map. // - core/storage (WALStore): on-disk WAL+extent. -// - core/storage/smartwal (Store): on-disk extent + ring metadata. // - core/storage/memorywal (this package): in-memory append-only // WAL log with V2-faithful per-LSN replay. package memorywal diff --git a/seaweed-block/core/storage/parallelwal/README.md b/seaweed-block/core/storage/parallelwal/README.md deleted file mode 100644 index ddcd5abc99..0000000000 --- a/seaweed-block/core/storage/parallelwal/README.md +++ /dev/null @@ -1,193 +0,0 @@ -# Parallel WAL Candidate - -`parallelwal` is the explicit Phase 167 `LogicalStorage` candidate selected -with: - -```text ---durable-impl=parallel-walstore -``` - -It is not the default backend. `smartwal` and `walstore` keep their existing -formats and behavior. - -## Problem - -The legacy WAL path assigns a global LSN and appends every write through one -whole-volume critical section. That gives simple ordering, but concurrent -independent-LBA writers still contend on one append owner. - -This candidate separates physical append ownership from logical publication: - -- an LBA maps deterministically to one lane; -- each lane owns a non-overlapping WAL region; -- lanes may execute positioned writes concurrently; -- a global completion ledger publishes only the contiguous LSN prefix. - -Physical completion out of order is allowed. Logical success over an LSN hole -is not. - -## File Format - -One preallocated file contains: - -```text -[4 KiB header A] -[4 KiB header B] -[lane 0 WAL ring] -... -[lane N WAL ring] -[block extent A] -[block extent B] -``` - -Each WAL record contains a 32-byte header followed by one complete block. The -record stores its global LSN, LBA, flags, payload length, data CRC, and record -CRC. Each lane's logical head and tail are monotonic; physical slot selection -uses `sequence % slotsPerLane`. - -The alternating headers are CRC protected and include: - -- generation; -- block and volume geometry; -- lane count, stripe mapping, record size, and ring capacity; -- global durable and checkpoint LSNs; -- global retained-WAL floor; -- durable head and tail for every lane. -- the currently authoritative extent. - -Open chooses the highest valid generation. A damaged latest header may fall -back to the prior valid generation; a torn or CRC-invalid committed record -fails with typed `storage.ErrWALIntegrityFault`. - -## Write And Publication - -The store allocates global LSN and lane sequence under one short metadata lock. -Execution then moves to the LBA's lane: - -1. same-lane requests enter one bounded, sequence-ordered queue; -2. one drainer combines adjacent physical ring slots into positioned writes - no larger than 1 MiB, splitting at ring wrap; -3. completion enters the global ledger; -4. the ledger publishes consecutive completed LSNs from `H+1`; -5. the caller returns only after its LSN is published. - -If LSN `N` fails, the store enters a terminal error state. A physically -completed `N+1` cannot return success or advance `H`. - -`WriteBatch` reserves one contiguous global LSN range and queues requests by -lane. Same-LBA writes always map to the same lane and remain ordered. A failed -later ring chunk terminal-faults the store: an earlier physical chunk may be -reported as a partial in-process result, but it cannot become durable because -the covering `Sync` fails and the durable header does not advance. - -## Sync And Checkpoint - -`Sync` first fences the highest LSN admitted when the call acquires the store -lock. It waits until that prefix is contiguously published or a terminal append -failure is known, then snapshots `H` and the per-lane published heads. It then: - -1. fsyncs WAL writes; -2. writes the alternate header with `R=H`; -3. fsyncs the header; -4. returns without checkpointing when every lane remains below pressure. - -When a lane exceeds its retained-slot threshold, `Sync` additionally: - -1. writes only latest blocks with `LSN <= R` to the shared extent, coalescing - contiguous LBAs into bounded 1 MiB positioned writes; -2. fsyncs the extent; -3. advances checkpoint and lane tails in the alternate header; -4. fsyncs that header; -5. advances `S` to the first LSN still honestly scannable. - -Before advancing a lane tail, recycle verification reads adjacent WAL records -in bounded 1 MiB chunks. Every record is still decoded and CRC checked; the -optimization removes one-`pread`-per-record amplification, not integrity -validation. - -No unstable record is copied into the checkpoint. No slot is reused before -the extent is durable and both header slots have been sealed with the recycled -tails, so fallback cannot scan a physical slot after it has been reused. - -Rebuild BASE installation uses the inactive extent as a copy-on-write stage. -Before reusing that extent, a guard generation makes both valid headers point -at the current active extent, preserving header fallback. The stage is then -cleared, BASE blocks are written there, and any session-live WAL blocks are -overlaid before durability. The final alternate header switches -`ActiveExtent` only after the staged extent is fsynced. A crash or final-header -failure therefore leaves the prior header and prior acknowledged extent -authoritative. Normal WAL-pressure checkpoints keep using the active extent -because the WAL-first header preserves replay data. - -`WriteExtentDirect` remains immediately readable as required by the shared -`LogicalStorage` contract; COW controls which extent recovery treats as -durable, not in-process visibility inside a rebuilding replica. The recovery -and authority layers must keep that replica non-ready until the terminal -barrier succeeds. A failed session is never evidence that the staged extent is -serviceable, and the next session resets it before reuse. - -## Recovery - -Recovery reads only records inside the durable lane head/tail ranges from the -selected header, validates every retained record, and merges lanes by global -LSN. It rejects: - -- record CRC or data CRC mismatch; -- invalid LBA-to-lane mapping; -- duplicate committed LSN; -- record LSN above `R`; -- a hole in the required contiguous interval - `[max(checkpoint + 1, S), R]`. - -Extent data supplies checkpointed blocks. Recovery validates all retained WAL -records, but records at or below the checkpoint remain catch-up history only; -they cannot replace newer BASE bytes installed directly into the extent. -Retained records above the checkpoint rebuild the live overlay and all -retained records remain eligible for `ScanLBAs`. Requests below `S` return -typed `storage.ErrWALRecycled`. - -`ApplyEntry` honors the source LSN from `LogicalStorage`, including a first -entry above LSN 1. Such a jump is published only after the entry append -succeeds. It advances the retained-WAL floor `S`, not the checkpoint: recovery -still replays every physically retained record, while the unrepresented LSN -interval is not falsely advertised as catch-up history. `AdvanceFrontier` is -reserved for the rebuild path after direct extent installation and moves `S` -beyond that BASE frontier. - -## Frontend Concurrency - -Removing whole-volume serialization exposed an existing partial-write hazard: -two `Read -> overlay -> Write` operations against different byte ranges of one -block could lose one update. `StorageBackend` therefore serializes every write -to an LBA through striped locks: partial RMW, single full-block writes, and -full-block batches all share the same exclusion boundary. Full-block writes -still skip the read. - -## Current Evidence And Limit - -Run: - -```bash -scripts/run-phase167-parallel-wal-candidate-gate.sh -``` - -The gate stress-tests header fallback, Sync admission fencing, out-of-order -completion, terminal lower-LSN failure and append drain, source-frontier -jumps, unsynced-tail discard, CRC failure, ring wrap, recovery merge, -BASE-versus-retained-WAL precedence, failed BASE commit rollback, abandoned -BASE-stage reset, direct-frontier retention, and adapter integration. It also -runs the canonical `LogicalStorage` contract and compares 1/2/4/8-writer -throughput against legacy `walstore`. - -The exact-commit Linux gate at `a5b687f` passed race, recovery stress, and -external syscall validation. The deterministic syscall probes observed five -`pwrite64` calls for eight concurrent same-lane writes and three `pread64` -calls while recycling 224 records. In the same 3000-iteration run, four-writer -16-block batches reached `116.95 MiB/s` versus legacy `80.00 MiB/s`, but 4 KiB -writes reached only `49.79 MiB/s` for one writer and `39.25 MiB/s` for four, -versus legacy `107.85 MiB/s` and `104.08 MiB/s`. - -The batch path therefore improved, but the candidate did not meet the -single-writer or four-writer scaling thresholds: -`performance_claim_allowed=false`. `parallel-walstore` remains opt-in and must -not be described as a default-backend or general performance improvement. diff --git a/seaweed-block/core/storage/parallelwal/benchmark_test.go b/seaweed-block/core/storage/parallelwal/benchmark_test.go deleted file mode 100644 index a73c2d659e..0000000000 --- a/seaweed-block/core/storage/parallelwal/benchmark_test.go +++ /dev/null @@ -1,330 +0,0 @@ -package parallelwal - -import ( - "fmt" - "path/filepath" - "sort" - "sync" - "testing" - "time" - - "github.com/seaweedfs/seaweed-block/core/storage" -) - -func BenchmarkPhase167ParallelWALContention(b *testing.B) { - const ( - blockSize = 4096 - numBlocks = 16384 - ) - for _, writers := range []int{1, 2, 4, 8} { - b.Run(fmt.Sprintf("writers_%d", writers), func(b *testing.B) { - s, err := CreateStoreWithConfig(filepath.Join(b.TempDir(), "store.bin"), Config{ - NumBlocks: numBlocks, - BlockSize: blockSize, - LaneCount: 4, - StripeBlocks: 1, - SlotsPerLane: 4096, - RetainPerLane: 64, - QueueDepth: 256, - }) - if err != nil { - b.Fatal(err) - } - b.Cleanup(func() { _ = s.Close() }) - - data := make([][]byte, writers) - for i := range data { - data[i] = make([]byte, blockSize) - data[i][0] = byte(i + 1) - } - latencies := make([]int64, b.N) - workerOps := make([]int, writers) - var firstErr error - var errOnce sync.Once - start := make(chan struct{}) - var wg sync.WaitGroup - - b.SetBytes(blockSize) - b.ResetTimer() - wallStart := time.Now() - for worker := 0; worker < writers; worker++ { - wg.Add(1) - go func(worker int) { - defer wg.Done() - <-start - for idx := worker; idx < b.N; idx += writers { - opStart := time.Now() - _, writeErr := s.Write(uint32(idx%numBlocks), data[worker]) - latencies[idx] = time.Since(opStart).Nanoseconds() - if writeErr != nil { - errOnce.Do(func() { firstErr = writeErr }) - return - } - workerOps[worker]++ - } - }(worker) - } - close(start) - wg.Wait() - if firstErr == nil { - _, firstErr = s.Sync() - } - wallDuration := time.Since(wallStart) - b.StopTimer() - if firstErr != nil { - b.Fatal(firstErr) - } - if b.N >= writers { - for worker, ops := range workerOps { - if ops == 0 { - b.Fatalf("worker %d completed zero writes", worker) - } - } - } - activeLanes := 0 - s.mu.RLock() - for laneID := 0; laneID < int(s.hdr.LaneCount); laneID++ { - if s.publishedHeads[laneID] > 0 { - activeLanes++ - } - } - s.mu.RUnlock() - _, walTail, _ := s.Boundaries() - s.mu.RLock() - checkpointWriteOps := s.checkpointWriteOps - recycleReadOps := s.recycleReadOps - walWriteOps := s.walWriteOps - s.mu.RUnlock() - reportParallelLatencyPercentiles(b, latencies) - b.ReportMetric(float64(activeLanes), "active_lanes") - b.ReportMetric(float64(checkpointWriteOps), "checkpoint_write_ops") - b.ReportMetric(float64(recycleReadOps), "recycle_read_ops") - b.ReportMetric(float64(walWriteOps), "wal_write_ops") - b.ReportMetric(float64(walTail), "wal_tail") - b.ReportMetric(float64(b.N)/wallDuration.Seconds(), "write_ops/s") - }) - } -} - -func BenchmarkPhase167ParallelWALBatchContention(b *testing.B) { - const ( - blockSize = 4096 - numBlocks = 16384 - batchBlocks = 16 - ) - for _, writers := range []int{1, 4} { - b.Run(fmt.Sprintf("writers_%d", writers), func(b *testing.B) { - s, err := CreateStoreWithConfig(filepath.Join(b.TempDir(), "store.bin"), Config{ - NumBlocks: numBlocks, - BlockSize: blockSize, - LaneCount: 4, - StripeBlocks: 1, - SlotsPerLane: 32768, - RetainPerLane: 64, - QueueDepth: 256, - }) - if err != nil { - b.Fatal(err) - } - b.Cleanup(func() { _ = s.Close() }) - - data := make([][][]byte, writers) - for worker := range data { - data[worker] = make([][]byte, batchBlocks) - for block := range data[worker] { - data[worker][block] = make([]byte, blockSize) - data[worker][block][0] = byte(worker + block + 1) - } - } - latencies := make([]int64, b.N) - var firstErr error - var errOnce sync.Once - start := make(chan struct{}) - var wg sync.WaitGroup - - b.SetBytes(blockSize * batchBlocks) - b.ResetTimer() - wallStart := time.Now() - for worker := 0; worker < writers; worker++ { - wg.Add(1) - go func(worker int) { - defer wg.Done() - <-start - for idx := worker; idx < b.N; idx += writers { - startLBA := uint32((idx * batchBlocks) % (numBlocks - batchBlocks)) - opStart := time.Now() - _, writeErr := s.WriteBatch(startLBA, data[worker]) - latencies[idx] = time.Since(opStart).Nanoseconds() - if writeErr != nil { - errOnce.Do(func() { firstErr = writeErr }) - return - } - } - }(worker) - } - close(start) - wg.Wait() - if firstErr == nil { - _, firstErr = s.Sync() - } - wallDuration := time.Since(wallStart) - b.StopTimer() - if firstErr != nil { - b.Fatal(firstErr) - } - s.mu.RLock() - checkpointWriteOps := s.checkpointWriteOps - recycleReadOps := s.recycleReadOps - walWriteOps := s.walWriteOps - s.mu.RUnlock() - reportParallelLatencyPercentiles(b, latencies) - b.ReportMetric(batchBlocks, "batch_blocks") - b.ReportMetric(float64(checkpointWriteOps), "checkpoint_write_ops") - b.ReportMetric(float64(recycleReadOps), "recycle_read_ops") - b.ReportMetric(float64(walWriteOps), "wal_write_ops") - b.ReportMetric(float64(b.N*batchBlocks)/wallDuration.Seconds(), "block_ops/s") - }) - } -} - -func BenchmarkPhase167LegacyWALBatchContentionControl(b *testing.B) { - const ( - blockSize = 4096 - numBlocks = 16384 - batchBlocks = 16 - ) - for _, writers := range []int{1, 4} { - b.Run(fmt.Sprintf("writers_%d", writers), func(b *testing.B) { - s, err := storage.CreateWALStore(filepath.Join(b.TempDir(), "store.bin"), numBlocks, blockSize) - if err != nil { - b.Fatal(err) - } - b.Cleanup(func() { _ = s.Close() }) - - data := make([][][]byte, writers) - for worker := range data { - data[worker] = make([][]byte, batchBlocks) - for block := range data[worker] { - data[worker][block] = make([]byte, blockSize) - data[worker][block][0] = byte(worker + block + 1) - } - } - latencies := make([]int64, b.N) - var firstErr error - var errOnce sync.Once - start := make(chan struct{}) - var wg sync.WaitGroup - - b.SetBytes(blockSize * batchBlocks) - b.ResetTimer() - wallStart := time.Now() - for worker := 0; worker < writers; worker++ { - wg.Add(1) - go func(worker int) { - defer wg.Done() - <-start - for idx := worker; idx < b.N; idx += writers { - startLBA := uint32((idx * batchBlocks) % (numBlocks - batchBlocks)) - opStart := time.Now() - _, writeErr := s.WriteBatch(startLBA, data[worker]) - latencies[idx] = time.Since(opStart).Nanoseconds() - if writeErr != nil { - errOnce.Do(func() { firstErr = writeErr }) - return - } - } - }(worker) - } - close(start) - wg.Wait() - if firstErr == nil { - _, firstErr = s.Sync() - } - wallDuration := time.Since(wallStart) - b.StopTimer() - if firstErr != nil { - b.Fatal(firstErr) - } - reportParallelLatencyPercentiles(b, latencies) - b.ReportMetric(batchBlocks, "batch_blocks") - b.ReportMetric(float64(b.N*batchBlocks)/wallDuration.Seconds(), "block_ops/s") - }) - } -} - -func BenchmarkPhase167LegacyWALContentionControl(b *testing.B) { - const ( - blockSize = 4096 - numBlocks = 16384 - ) - for _, writers := range []int{1, 2, 4, 8} { - b.Run(fmt.Sprintf("writers_%d", writers), func(b *testing.B) { - s, err := storage.CreateWALStore(filepath.Join(b.TempDir(), "store.bin"), numBlocks, blockSize) - if err != nil { - b.Fatal(err) - } - b.Cleanup(func() { _ = s.Close() }) - - data := make([][]byte, writers) - for i := range data { - data[i] = make([]byte, blockSize) - data[i][0] = byte(i + 1) - } - latencies := make([]int64, b.N) - start := make(chan struct{}) - var firstErr error - var errOnce sync.Once - var wg sync.WaitGroup - - b.SetBytes(blockSize) - b.ResetTimer() - wallStart := time.Now() - for worker := 0; worker < writers; worker++ { - wg.Add(1) - go func(worker int) { - defer wg.Done() - <-start - for idx := worker; idx < b.N; idx += writers { - opStart := time.Now() - _, writeErr := s.Write(uint32(idx%numBlocks), data[worker]) - latencies[idx] = time.Since(opStart).Nanoseconds() - if writeErr != nil { - errOnce.Do(func() { firstErr = writeErr }) - return - } - } - }(worker) - } - close(start) - wg.Wait() - if firstErr == nil { - _, firstErr = s.Sync() - } - wallDuration := time.Since(wallStart) - b.StopTimer() - if firstErr != nil { - b.Fatal(firstErr) - } - reportParallelLatencyPercentiles(b, latencies) - b.ReportMetric(float64(b.N)/wallDuration.Seconds(), "write_ops/s") - }) - } -} - -func reportParallelLatencyPercentiles(b *testing.B, samples []int64) { - b.Helper() - if len(samples) == 0 { - return - } - sort.Slice(samples, func(i, j int) bool { return samples[i] < samples[j] }) - at := func(percent int) float64 { - idx := (len(samples)*percent + 99) / 100 - if idx > 0 { - idx-- - } - return float64(samples[idx]) - } - b.ReportMetric(at(50), "p50_ns") - b.ReportMetric(at(95), "p95_ns") - b.ReportMetric(at(99), "p99_ns") -} diff --git a/seaweed-block/core/storage/parallelwal/codec_fuzz_test.go b/seaweed-block/core/storage/parallelwal/codec_fuzz_test.go deleted file mode 100644 index 4bdce21876..0000000000 --- a/seaweed-block/core/storage/parallelwal/codec_fuzz_test.go +++ /dev/null @@ -1,131 +0,0 @@ -package parallelwal - -import ( - "bytes" - "encoding/binary" - "hash/crc32" - "reflect" - "testing" -) - -var fuzzBlockSizes = []int{1, 16, 512, 4096} - -func fuzzBlockSize(sel uint8) int { return fuzzBlockSizes[int(sel)%len(fuzzBlockSizes)] } - -// FuzzParallelWALDecodeRecord: decodeRecord never panics; a rejected record -// is the zero value; an accepted one re-encodes to exactly its bytes (every -// header byte is a defined field). -func FuzzParallelWALDecodeRecord(f *testing.F) { - for _, bs := range fuzzBlockSizes { - rec := walRecord{LSN: 9, LBA: 2, Flags: flagWrite, Data: bytes.Repeat([]byte{0xA5}, bs)} - buf, err := encodeRecord(rec, bs) - if err != nil { - f.Fatal(err) - } - sel := uint8(0) - for i, v := range fuzzBlockSizes { - if v == bs { - sel = uint8(i) - } - } - f.Add(buf, sel) - torn := append([]byte(nil), buf...) - torn[len(torn)-1] ^= 1 - f.Add(torn, sel) - } - f.Fuzz(func(t *testing.T, buf []byte, sel uint8) { - bs := fuzzBlockSize(sel) - rec, err := decodeRecord(buf, bs) - if err != nil { - if !reflect.DeepEqual(rec, walRecord{}) { - t.Fatalf("error %v with a partial record %+v", err, rec) - } - return - } - re, err := encodeRecord(rec, bs) - if err != nil { - t.Fatalf("re-encode of an accepted record: %v", err) - } - if !bytes.Equal(re, buf) { - t.Fatalf("accepted record does not re-encode to its bytes") - } - }) -} - -// FuzzParallelWALRecordRoundTrip: every record the encoder accepts decodes -// back to itself. -func FuzzParallelWALRecordRoundTrip(f *testing.F) { - f.Add(uint64(9), uint32(2), uint16(flagWrite), []byte("payload!"), uint8(1)) - f.Fuzz(func(t *testing.T, lsn uint64, lba uint32, flags uint16, data []byte, sel uint8) { - bs := fuzzBlockSize(sel) - block := make([]byte, bs) - copy(block, data) - rec := walRecord{LSN: lsn, LBA: lba, Flags: flags, Data: block} - buf, err := encodeRecord(rec, bs) - if err != nil { - t.Fatalf("encode: %v", err) - } - got, err := decodeRecord(buf, bs) - if err != nil || !reflect.DeepEqual(got, rec) { - t.Fatalf("round trip: %+v err %v, want %+v", got, err, rec) - } - }) -} - -func seedHeader() fileHeader { - h := fileHeader{Generation: 3, CreatedAt: 1, BlockSize: 4096, NumBlocks: 64, LaneCount: 2, StripeBlocks: 8, - RecordSize: recordHeaderSize + 4096, SlotsPerLane: 32, DurableLSN: 10, CheckpointLSN: 4, WALTail: 2, - RetainPerLane: 4, ActiveExtent: 1} - h.LaneHeads[0], h.LaneTails[0] = 5, 1 - h.LaneHeads[1], h.LaneTails[1] = 6, 2 - return h -} - -// headerFromFuzz builds a 4096-byte header slot from fuzz bytes with a valid -// magic, version, size and CRC, so the fuzzer exercises field validation. -func headerFromFuzz(data []byte) []byte { - buf := make([]byte, headerSize) - copy(buf, data) - copy(buf[0:4], headerMagic) - binary.LittleEndian.PutUint16(buf[4:6], headerVersion) - binary.LittleEndian.PutUint16(buf[6:8], headerSize) - binary.LittleEndian.PutUint32(buf[headerCRCOffset:], crc32.ChecksumIEEE(buf[:headerCRCOffset])) - return buf -} - -// FuzzParallelWALDecodeHeader: decodeHeader never panics on any bytes; on a -// CRC-valid slot a rejection is the zero header, and an accepted header is -// valid and survives an encode/decode round trip unchanged. -func FuzzParallelWALDecodeHeader(f *testing.F) { - good, err := encodeHeader(seedHeader()) - if err != nil { - f.Fatal(err) - } - f.Add(good[:], false) - f.Add(good[:100], true) - f.Add([]byte{}, true) - f.Fuzz(func(t *testing.T, data []byte, fixup bool) { - buf := data - if fixup { - buf = headerFromFuzz(data) - } - h, err := decodeHeader(buf) - if err != nil { - if !reflect.DeepEqual(h, fileHeader{}) { - t.Fatalf("error %v with a partial header", err) - } - return - } - if err := h.validate(); err != nil { - t.Fatalf("accepted header is invalid: %v", err) - } - re, err := encodeHeader(h) - if err != nil { - t.Fatalf("re-encode of an accepted header: %v", err) - } - got, err := decodeHeader(re[:]) - if err != nil || !reflect.DeepEqual(got, h) { - t.Fatalf("header round trip: %+v err %v", got, err) - } - }) -} diff --git a/seaweed-block/core/storage/parallelwal/header.go b/seaweed-block/core/storage/parallelwal/header.go deleted file mode 100644 index 7f2d843a1f..0000000000 --- a/seaweed-block/core/storage/parallelwal/header.go +++ /dev/null @@ -1,211 +0,0 @@ -package parallelwal - -import ( - "encoding/binary" - "errors" - "fmt" - "hash/crc32" - "io" - "os" -) - -const ( - headerSize = 4096 - headerSlots = 2 - headerMagic = "SWPW" - headerVersion = 1 - maxLaneCount = 16 - laneHeadsOffset = 128 - laneTailsOffset = laneHeadsOffset + maxLaneCount*8 - headerCRCOffset = headerSize - 4 - defaultLaneCount = 4 - defaultLaneSlots = 4096 -) - -var ( - errBadMagic = errors.New("parallelwal: bad magic") - errBadVersion = errors.New("parallelwal: unsupported version") - errBadHeader = errors.New("parallelwal: invalid header") - errBadGeometry = errors.New("parallelwal: invalid geometry") -) - -type fileHeader struct { - Generation uint64 - CreatedAt uint64 - BlockSize uint32 - NumBlocks uint32 - LaneCount uint16 - StripeBlocks uint16 - RecordSize uint32 - SlotsPerLane uint64 - DurableLSN uint64 - CheckpointLSN uint64 - WALTail uint64 - RetainPerLane uint64 - ActiveExtent uint8 - LaneHeads [maxLaneCount]uint64 - LaneTails [maxLaneCount]uint64 -} - -func (h fileHeader) validate() error { - if h.BlockSize == 0 || h.NumBlocks == 0 { - return fmt.Errorf("%w: blockSize=%d numBlocks=%d", errBadGeometry, h.BlockSize, h.NumBlocks) - } - maxBlockSize := uint32(maxWALIOBytes - recordHeaderSize) - if h.BlockSize > maxBlockSize { - return fmt.Errorf("%w: blockSize=%d exceeds maximum=%d", - errBadGeometry, h.BlockSize, maxBlockSize) - } - if h.LaneCount == 0 || h.LaneCount > maxLaneCount { - return fmt.Errorf("%w: laneCount=%d", errBadGeometry, h.LaneCount) - } - if h.StripeBlocks == 0 || h.SlotsPerLane == 0 { - return fmt.Errorf("%w: stripeBlocks=%d slotsPerLane=%d", errBadGeometry, h.StripeBlocks, h.SlotsPerLane) - } - wantRecordSize := uint64(recordHeaderSize) + uint64(h.BlockSize) - if wantRecordSize > uint64(^uint32(0)) || uint64(h.RecordSize) != wantRecordSize { - return fmt.Errorf("%w: recordSize=%d want=%d", errBadGeometry, h.RecordSize, wantRecordSize) - } - if h.CheckpointLSN > h.DurableLSN { - return fmt.Errorf("%w: checkpoint=%d durable=%d", errBadHeader, h.CheckpointLSN, h.DurableLSN) - } - for i := 0; i < int(h.LaneCount); i++ { - if h.LaneTails[i] > h.LaneHeads[i] || h.LaneHeads[i]-h.LaneTails[i] > h.SlotsPerLane { - return fmt.Errorf("%w: lane=%d tail=%d head=%d slots=%d", - errBadHeader, i, h.LaneTails[i], h.LaneHeads[i], h.SlotsPerLane) - } - } - if h.RetainPerLane == 0 || h.RetainPerLane >= h.SlotsPerLane { - return fmt.Errorf("%w: retainPerLane=%d slotsPerLane=%d", errBadGeometry, h.RetainPerLane, h.SlotsPerLane) - } - if h.ActiveExtent > 1 { - return fmt.Errorf("%w: activeExtent=%d", errBadGeometry, h.ActiveExtent) - } - return nil -} - -func encodeHeader(h fileHeader) ([headerSize]byte, error) { - var buf [headerSize]byte - copy(buf[0:4], headerMagic) - binary.LittleEndian.PutUint16(buf[4:6], headerVersion) - binary.LittleEndian.PutUint16(buf[6:8], headerSize) - binary.LittleEndian.PutUint64(buf[8:16], h.Generation) - binary.LittleEndian.PutUint64(buf[16:24], h.CreatedAt) - binary.LittleEndian.PutUint32(buf[24:28], h.BlockSize) - binary.LittleEndian.PutUint32(buf[28:32], h.NumBlocks) - binary.LittleEndian.PutUint16(buf[32:34], h.LaneCount) - binary.LittleEndian.PutUint16(buf[34:36], h.StripeBlocks) - binary.LittleEndian.PutUint32(buf[36:40], h.RecordSize) - binary.LittleEndian.PutUint64(buf[40:48], h.SlotsPerLane) - binary.LittleEndian.PutUint64(buf[48:56], h.DurableLSN) - binary.LittleEndian.PutUint64(buf[56:64], h.CheckpointLSN) - binary.LittleEndian.PutUint64(buf[64:72], h.WALTail) - binary.LittleEndian.PutUint64(buf[72:80], h.RetainPerLane) - buf[80] = h.ActiveExtent - for i := 0; i < maxLaneCount; i++ { - binary.LittleEndian.PutUint64(buf[laneHeadsOffset+i*8:], h.LaneHeads[i]) - binary.LittleEndian.PutUint64(buf[laneTailsOffset+i*8:], h.LaneTails[i]) - } - if err := h.validate(); err != nil { - return buf, err - } - binary.LittleEndian.PutUint32(buf[headerCRCOffset:], crc32.ChecksumIEEE(buf[:headerCRCOffset])) - return buf, nil -} - -func decodeHeader(buf []byte) (fileHeader, error) { - if len(buf) != headerSize { - return fileHeader{}, fmt.Errorf("%w: size=%d", errBadHeader, len(buf)) - } - if string(buf[0:4]) != headerMagic { - return fileHeader{}, errBadMagic - } - if got := binary.LittleEndian.Uint16(buf[4:6]); got != headerVersion { - return fileHeader{}, fmt.Errorf("%w: got=%d want=%d", errBadVersion, got, headerVersion) - } - if got := binary.LittleEndian.Uint16(buf[6:8]); got != headerSize { - return fileHeader{}, fmt.Errorf("%w: headerSize=%d", errBadHeader, got) - } - gotCRC := binary.LittleEndian.Uint32(buf[headerCRCOffset:]) - wantCRC := crc32.ChecksumIEEE(buf[:headerCRCOffset]) - if gotCRC != wantCRC { - return fileHeader{}, fmt.Errorf("%w: CRC got=%08x want=%08x", errBadHeader, gotCRC, wantCRC) - } - h := fileHeader{ - Generation: binary.LittleEndian.Uint64(buf[8:16]), - CreatedAt: binary.LittleEndian.Uint64(buf[16:24]), - BlockSize: binary.LittleEndian.Uint32(buf[24:28]), - NumBlocks: binary.LittleEndian.Uint32(buf[28:32]), - LaneCount: binary.LittleEndian.Uint16(buf[32:34]), - StripeBlocks: binary.LittleEndian.Uint16(buf[34:36]), - RecordSize: binary.LittleEndian.Uint32(buf[36:40]), - SlotsPerLane: binary.LittleEndian.Uint64(buf[40:48]), - DurableLSN: binary.LittleEndian.Uint64(buf[48:56]), - CheckpointLSN: binary.LittleEndian.Uint64(buf[56:64]), - WALTail: binary.LittleEndian.Uint64(buf[64:72]), - RetainPerLane: binary.LittleEndian.Uint64(buf[72:80]), - ActiveExtent: buf[80], - } - for i := 0; i < maxLaneCount; i++ { - h.LaneHeads[i] = binary.LittleEndian.Uint64(buf[laneHeadsOffset+i*8:]) - h.LaneTails[i] = binary.LittleEndian.Uint64(buf[laneTailsOffset+i*8:]) - } - if err := h.validate(); err != nil { - return fileHeader{}, err - } - return h, nil -} - -func readBestHeader(f *os.File) (fileHeader, int, error) { - var best fileHeader - bestSlot := -1 - var errs [headerSlots]error - for slot := 0; slot < headerSlots; slot++ { - buf := make([]byte, headerSize) - if _, err := f.ReadAt(buf, int64(slot*headerSize)); err != nil && !errors.Is(err, io.EOF) { - errs[slot] = err - continue - } - h, err := decodeHeader(buf) - if err != nil { - errs[slot] = err - continue - } - if bestSlot == -1 || h.Generation > best.Generation { - best = h - bestSlot = slot - } - } - if bestSlot == -1 { - return fileHeader{}, -1, fmt.Errorf("parallelwal: no valid header: slot0=%v slot1=%v", errs[0], errs[1]) - } - return best, bestSlot, nil -} - -// ProbeStore validates that path has at least one usable parallelwal header. -// It intentionally applies the same dual-header selection as OpenStore. -func ProbeStore(path string) error { - f, err := os.Open(path) - if err != nil { - return fmt.Errorf("parallelwal: probe open %s: %w", path, err) - } - defer f.Close() - if _, _, err := readBestHeader(f); err != nil { - return err - } - return nil -} - -func writeHeaderAt(f *os.File, slot int, h fileHeader) error { - if slot < 0 || slot >= headerSlots { - return fmt.Errorf("parallelwal: header slot %d out of range", slot) - } - buf, err := encodeHeader(h) - if err != nil { - return err - } - if _, err := f.WriteAt(buf[:], int64(slot*headerSize)); err != nil { - return fmt.Errorf("parallelwal: write header slot %d: %w", slot, err) - } - return nil -} diff --git a/seaweed-block/core/storage/parallelwal/record.go b/seaweed-block/core/storage/parallelwal/record.go deleted file mode 100644 index d46e198d44..0000000000 --- a/seaweed-block/core/storage/parallelwal/record.go +++ /dev/null @@ -1,84 +0,0 @@ -package parallelwal - -import ( - "encoding/binary" - "fmt" - "hash/crc32" -) - -const ( - recordHeaderSize = 32 - recordMagic = "PWR1" - recordVersion = 1 - flagWrite = uint16(1) -) - -type walRecord struct { - LSN uint64 - LBA uint32 - Flags uint16 - Data []byte -} - -func encodeRecord(rec walRecord, blockSize int) ([]byte, error) { - buf := make([]byte, recordHeaderSize+blockSize) - if err := encodeRecordInto(buf, rec, blockSize); err != nil { - return nil, err - } - return buf, nil -} - -func encodeRecordInto(buf []byte, rec walRecord, blockSize int) error { - if len(rec.Data) != blockSize { - return fmt.Errorf("parallelwal: record data size %d != block size %d", len(rec.Data), blockSize) - } - if len(buf) != recordHeaderSize+blockSize { - return fmt.Errorf("parallelwal: encode buffer size %d != record size %d", len(buf), recordHeaderSize+blockSize) - } - clear(buf) - copy(buf[0:4], recordMagic) - binary.LittleEndian.PutUint16(buf[4:6], recordVersion) - binary.LittleEndian.PutUint16(buf[6:8], rec.Flags) - binary.LittleEndian.PutUint64(buf[8:16], rec.LSN) - binary.LittleEndian.PutUint32(buf[16:20], rec.LBA) - binary.LittleEndian.PutUint32(buf[20:24], uint32(blockSize)) - binary.LittleEndian.PutUint32(buf[24:28], crc32.ChecksumIEEE(rec.Data)) - copy(buf[recordHeaderSize:], rec.Data) - recordCRC := crc32.NewIEEE() - _, _ = recordCRC.Write(buf[:28]) - _, _ = recordCRC.Write(buf[recordHeaderSize : recordHeaderSize+blockSize]) - binary.LittleEndian.PutUint32(buf[28:32], recordCRC.Sum32()) - return nil -} - -func decodeRecord(buf []byte, blockSize int) (walRecord, error) { - if len(buf) != recordHeaderSize+blockSize { - return walRecord{}, fmt.Errorf("parallelwal: record size %d != %d", len(buf), recordHeaderSize+blockSize) - } - if string(buf[0:4]) != recordMagic { - return walRecord{}, fmt.Errorf("parallelwal: record bad magic") - } - if version := binary.LittleEndian.Uint16(buf[4:6]); version != recordVersion { - return walRecord{}, fmt.Errorf("parallelwal: record version %d", version) - } - if size := binary.LittleEndian.Uint32(buf[20:24]); size != uint32(blockSize) { - return walRecord{}, fmt.Errorf("parallelwal: record payload size %d != %d", size, blockSize) - } - data := make([]byte, blockSize) - copy(data, buf[recordHeaderSize:recordHeaderSize+blockSize]) - if got, want := crc32.ChecksumIEEE(data), binary.LittleEndian.Uint32(buf[24:28]); got != want { - return walRecord{}, fmt.Errorf("parallelwal: data CRC got=%08x want=%08x", got, want) - } - recordCRC := crc32.NewIEEE() - _, _ = recordCRC.Write(buf[:28]) - _, _ = recordCRC.Write(data) - if got, want := recordCRC.Sum32(), binary.LittleEndian.Uint32(buf[28:32]); got != want { - return walRecord{}, fmt.Errorf("parallelwal: record CRC got=%08x want=%08x", got, want) - } - return walRecord{ - LSN: binary.LittleEndian.Uint64(buf[8:16]), - LBA: binary.LittleEndian.Uint32(buf[16:20]), - Flags: binary.LittleEndian.Uint16(buf[6:8]), - Data: data, - }, nil -} diff --git a/seaweed-block/core/storage/parallelwal/store.go b/seaweed-block/core/storage/parallelwal/store.go deleted file mode 100644 index 7c3139a956..0000000000 --- a/seaweed-block/core/storage/parallelwal/store.go +++ /dev/null @@ -1,1430 +0,0 @@ -// Package parallelwal provides an opt-in single-file LogicalStorage backend -// with deterministic LBA-to-lane ownership and a global contiguous LSN -// publication frontier. -package parallelwal - -import ( - "bytes" - "errors" - "fmt" - "io" - "os" - "path/filepath" - "sort" - "sync" - "time" - - "github.com/seaweedfs/seaweed-block/core/geometry" - "github.com/seaweedfs/seaweed-block/core/storage" -) - -const ( - defaultQueueDepth = 128 - maxCheckpointWriteBytes = 1 << 20 - maxWALIOBytes = 1 << 20 -) - -var ( - ErrNotRecovered = errors.New("parallelwal: store must be recovered before use") - ErrQueueFull = errors.New("parallelwal: lane queue full") - ErrWALFull = errors.New("parallelwal: lane WAL full") -) - -type Config struct { - NumBlocks uint32 - BlockSize int - LaneCount int - StripeBlocks int - SlotsPerLane uint64 - RetainPerLane uint64 - QueueDepth int -} - -type blockVersion struct { - lsn uint64 - data []byte -} - -type writeRequest struct { - lsn uint64 - lba uint32 - flags uint16 - data []byte - lane int - laneSeq uint64 - publicationBaseLSN uint64 - done bool - delivered bool - err error - result chan error -} - -type lane struct { - id int - base int64 - nextSeq uint64 - - mu sync.Mutex - completedSeq uint64 - queueDepth uint64 - queue []*writeRequest - draining bool - buffer []byte - beforeWrite func(*writeRequest) -} - -type Store struct { - path string - fd *os.File - hdr fileHeader - headerSlot int - extentBases [2]int64 - activeExtent int - - numBlocks uint32 - blockSize uint32 - laneCount int - stripeBlocks uint32 - recordSize uint32 - slotsPerLane uint64 - retainPerLane uint64 - - mu sync.RWMutex - cond *sync.Cond - syncMu sync.Mutex - closed bool - closing bool - recovered bool - terminalErr error - reuseFence bool - nextLSN uint64 - stableLSN uint64 - checkpointLSN uint64 - pendingBaseLSN uint64 - baseCommitPending bool - walTail uint64 - publishedLSN uint64 - publishedHeads [maxLaneCount]uint64 - inflightAppends int - pending map[uint64]*writeRequest - latest map[uint32]blockVersion - applied map[uint32]uint64 - history map[uint64]walRecord - baseStageActive bool - baseStageSlot int - baseStage map[uint32][]byte - checkpointWriteOps uint64 - walWriteOps uint64 - recycleReadOps uint64 - - lanes []*lane - extentLocks [256]sync.RWMutex -} - -func CreateStore(path string, numBlocks uint32, blockSize int) (*Store, error) { - return CreateStoreWithConfig(path, Config{ - NumBlocks: numBlocks, - BlockSize: blockSize, - LaneCount: defaultLaneCount, - StripeBlocks: 1, - SlotsPerLane: defaultLaneSlots, - RetainPerLane: defaultLaneSlots / 2, - QueueDepth: defaultQueueDepth, - }) -} - -func CreateStoreWithConfig(path string, cfg Config) (*Store, error) { - cfg = normalizeConfig(cfg) - if err := geometry.ValidateBlockGeometry(uint64(cfg.NumBlocks), uint64(cfg.BlockSize)); err != nil { - return nil, err - } - h, err := headerForConfig(cfg) - if err != nil { - return nil, err - } - if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { - return nil, fmt.Errorf("parallelwal: mkdir %s: %w", filepath.Dir(path), err) - } - f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0o644) - if err != nil { - return nil, fmt.Errorf("parallelwal: create %s: %w", path, err) - } - totalSize, err := fileSize(h) - if err != nil { - _ = f.Close() - return nil, err - } - if err := f.Truncate(totalSize); err != nil { - _ = f.Close() - return nil, fmt.Errorf("parallelwal: preallocate %d bytes: %w", totalSize, err) - } - if err := writeHeaderAt(f, 0, h); err != nil { - _ = f.Close() - return nil, err - } - if err := f.Sync(); err != nil { - _ = f.Close() - return nil, fmt.Errorf("parallelwal: fsync create: %w", err) - } - return newStore(path, f, h, 0, cfg.QueueDepth, true), nil -} - -func OpenStore(path string) (*Store, error) { - f, err := os.OpenFile(path, os.O_RDWR, 0o644) - if err != nil { - return nil, fmt.Errorf("parallelwal: open %s: %w", path, err) - } - h, slot, err := readBestHeader(f) - if err != nil { - _ = f.Close() - return nil, err - } - required, err := fileSize(h) - if err != nil { - _ = f.Close() - return nil, err - } - st, err := f.Stat() - if err != nil { - _ = f.Close() - return nil, fmt.Errorf("parallelwal: stat %s: %w", path, err) - } - if st.Size() < required { - _ = f.Close() - return nil, fmt.Errorf("%w: truncated file size=%d required=%d", errBadGeometry, st.Size(), required) - } - return newStore(path, f, h, slot, defaultQueueDepth, false), nil -} - -func normalizeConfig(cfg Config) Config { - if cfg.BlockSize == 0 { - cfg.BlockSize = storage.DefaultBlockSize - } - if cfg.LaneCount == 0 { - cfg.LaneCount = defaultLaneCount - } - if cfg.StripeBlocks == 0 { - cfg.StripeBlocks = 1 - } - if cfg.SlotsPerLane == 0 { - cfg.SlotsPerLane = defaultLaneSlots - } - if cfg.RetainPerLane == 0 { - cfg.RetainPerLane = cfg.SlotsPerLane / 2 - if cfg.RetainPerLane == 0 { - cfg.RetainPerLane = 1 - } - } - if cfg.QueueDepth == 0 { - cfg.QueueDepth = defaultQueueDepth - } - return cfg -} - -func headerForConfig(cfg Config) (fileHeader, error) { - if cfg.NumBlocks == 0 || cfg.BlockSize <= 0 { - return fileHeader{}, fmt.Errorf("%w: numBlocks=%d blockSize=%d", errBadGeometry, cfg.NumBlocks, cfg.BlockSize) - } - if uint64(cfg.BlockSize) > uint64(^uint32(0))-recordHeaderSize || - uint64(cfg.StripeBlocks) > uint64(^uint16(0)) { - return fileHeader{}, fmt.Errorf("%w: blockSize=%d stripeBlocks=%d exceed persisted field width", - errBadGeometry, cfg.BlockSize, cfg.StripeBlocks) - } - if cfg.LaneCount <= 0 || cfg.LaneCount > maxLaneCount || cfg.StripeBlocks <= 0 || - cfg.SlotsPerLane < 2 || cfg.RetainPerLane == 0 || cfg.RetainPerLane >= cfg.SlotsPerLane || - cfg.QueueDepth <= 0 { - return fileHeader{}, fmt.Errorf("%w: lanes=%d stripes=%d slots=%d retain=%d queue=%d", - errBadGeometry, cfg.LaneCount, cfg.StripeBlocks, cfg.SlotsPerLane, cfg.RetainPerLane, cfg.QueueDepth) - } - h := fileHeader{ - Generation: 1, - CreatedAt: uint64(time.Now().UnixNano()), - BlockSize: uint32(cfg.BlockSize), - NumBlocks: cfg.NumBlocks, - LaneCount: uint16(cfg.LaneCount), - StripeBlocks: uint16(cfg.StripeBlocks), - RecordSize: uint32(recordHeaderSize + cfg.BlockSize), - SlotsPerLane: cfg.SlotsPerLane, - RetainPerLane: cfg.RetainPerLane, - WALTail: 1, - } - return h, h.validate() -} - -func fileSize(h fileHeader) (int64, error) { - const maxSize = uint64(^uint64(0) >> 1) - walRecords, ok := checkedMul(uint64(h.LaneCount), h.SlotsPerLane, maxSize) - if !ok { - return 0, fmt.Errorf("%w: WAL record count overflow", errBadGeometry) - } - walBytes, ok := checkedMul(walRecords, uint64(h.RecordSize), maxSize) - if !ok { - return 0, fmt.Errorf("%w: WAL size overflow", errBadGeometry) - } - extentBytes, ok := checkedMul(uint64(h.NumBlocks), uint64(h.BlockSize), maxSize) - if !ok { - return 0, fmt.Errorf("%w: extent size overflow", errBadGeometry) - } - allExtentBytes, ok := checkedMul(extentBytes, 2, maxSize) - if !ok { - return 0, fmt.Errorf("%w: dual extent size overflow", errBadGeometry) - } - total := uint64(headerSlots * headerSize) - if walBytes > maxSize-total { - return 0, fmt.Errorf("%w: file size overflow", errBadGeometry) - } - total += walBytes - if allExtentBytes > maxSize-total { - return 0, fmt.Errorf("%w: file size overflow", errBadGeometry) - } - total += allExtentBytes - return int64(total), nil -} - -func checkedMul(a, b, limit uint64) (uint64, bool) { - if a != 0 && b > limit/a { - return 0, false - } - return a * b, true -} - -func newStore(path string, f *os.File, h fileHeader, headerSlot, queueDepth int, recovered bool) *Store { - walBase := int64(headerSlots * headerSize) - extentBase := walBase + int64(h.LaneCount)*int64(h.SlotsPerLane)*int64(h.RecordSize) - extentBytes := int64(h.NumBlocks) * int64(h.BlockSize) - s := &Store{ - path: path, - fd: f, - hdr: h, - headerSlot: headerSlot, - extentBases: [2]int64{extentBase, extentBase + extentBytes}, - activeExtent: int(h.ActiveExtent), - numBlocks: h.NumBlocks, - blockSize: h.BlockSize, - laneCount: int(h.LaneCount), - stripeBlocks: uint32(h.StripeBlocks), - recordSize: h.RecordSize, - slotsPerLane: h.SlotsPerLane, - retainPerLane: h.RetainPerLane, - recovered: recovered, - nextLSN: h.DurableLSN + 1, - stableLSN: h.DurableLSN, - checkpointLSN: h.CheckpointLSN, - walTail: h.WALTail, - publishedLSN: h.DurableLSN, - pending: make(map[uint64]*writeRequest), - latest: make(map[uint32]blockVersion), - applied: make(map[uint32]uint64), - history: make(map[uint64]walRecord), - baseStageSlot: 1 - int(h.ActiveExtent), - } - if s.nextLSN == 0 { - s.nextLSN = 1 - } - s.cond = sync.NewCond(&s.mu) - s.lanes = make([]*lane, int(h.LaneCount)) - laneBytes := int64(h.SlotsPerLane) * int64(h.RecordSize) - for i := range s.lanes { - l := &lane{ - id: i, - base: walBase + int64(i)*laneBytes, - nextSeq: h.LaneHeads[i], - completedSeq: h.LaneHeads[i], - queueDepth: uint64(queueDepth), - buffer: make([]byte, h.RecordSize), - } - s.publishedHeads[i] = h.LaneHeads[i] - s.lanes[i] = l - } - return s -} - -func (s *Store) queueRequest(l *lane, req *writeRequest) bool { - l.mu.Lock() - defer l.mu.Unlock() - l.queue = append(l.queue, req) - if l.draining { - return false - } - l.draining = true - return true -} - -func (s *Store) drainLane(l *lane, handoffAfterBatch bool) { - for { - l.mu.Lock() - if len(l.queue) == 0 { - l.queue = nil - l.draining = false - l.mu.Unlock() - return - } - firstSeq := l.queue[0].laneSeq - slot := firstSeq % s.slotsPerLane - maxRecords := maxWALIOBytes / int(s.recordSize) - if maxRecords < 1 { - maxRecords = 1 - } - if untilWrap := int(s.slotsPerLane - slot); maxRecords > untilWrap { - maxRecords = untilWrap - } - if maxRecords > len(l.queue) { - maxRecords = len(l.queue) - } - batch := append([]*writeRequest(nil), l.queue[:maxRecords]...) - for i := 0; i < maxRecords; i++ { - l.queue[i] = nil - } - l.queue = l.queue[maxRecords:] - beforeWrite := l.beforeWrite - l.mu.Unlock() - - for _, req := range batch { - if beforeWrite != nil { - beforeWrite(req) - } - } - bytesNeeded := len(batch) * int(s.recordSize) - if cap(l.buffer) < bytesNeeded { - l.buffer = make([]byte, bytesNeeded) - } - buf := l.buffer[:bytesNeeded] - var err error - for i, req := range batch { - recordBuf := buf[i*int(s.recordSize) : (i+1)*int(s.recordSize)] - err = encodeRecordInto(recordBuf, - walRecord{LSN: req.lsn, LBA: req.lba, Flags: req.flags, Data: req.data}, - int(s.blockSize)) - if err != nil { - break - } - } - if err == nil { - off := l.base + int64(slot)*int64(s.recordSize) - _, err = s.fd.WriteAt(buf, off) - s.mu.Lock() - s.walWriteOps++ - s.mu.Unlock() - if err != nil { - err = fmt.Errorf("parallelwal: lane %d append LSN range [%d,%d]: %w", - l.id, batch[0].lsn, batch[len(batch)-1].lsn, err) - } - } - - l.mu.Lock() - l.completedSeq += uint64(len(batch)) - l.mu.Unlock() - for _, req := range batch { - s.complete(req, err) - } - if err != nil { - s.failQueuedLane(l, err) - return - } - if handoffAfterBatch { - l.mu.Lock() - if len(l.queue) == 0 { - l.draining = false - l.mu.Unlock() - } else { - l.mu.Unlock() - go s.drainLane(l, false) - } - return - } - } -} - -func (s *Store) failQueuedLane(l *lane, err error) { - l.mu.Lock() - queued := l.queue - l.queue = nil - l.completedSeq += uint64(len(queued)) - l.draining = false - l.mu.Unlock() - for _, req := range queued { - s.complete(req, err) - } -} - -func (s *Store) complete(req *writeRequest, err error) { - s.mu.Lock() - defer s.mu.Unlock() - s.inflightAppends-- - req.done = true - req.err = err - if err != nil && s.terminalErr == nil { - s.terminalErr = err - } - if s.terminalErr != nil { - for _, pending := range s.pending { - s.deliverLocked(pending, s.terminalErr) - } - s.cond.Broadcast() - return - } - if req.publicationBaseLSN > s.publishedLSN { - s.publishedLSN = req.publicationBaseLSN - s.walTail = req.publicationBaseLSN + 1 - for historyLSN := range s.history { - if historyLSN <= req.publicationBaseLSN { - delete(s.history, historyLSN) - } - } - } - for { - next := s.pending[s.publishedLSN+1] - if next == nil || !next.done { - break - } - if next.err != nil { - s.terminalErr = next.err - for _, pending := range s.pending { - s.deliverLocked(pending, s.terminalErr) - } - break - } - data := next.data - s.latest[next.lba] = blockVersion{lsn: next.lsn, data: data} - if next.lsn > s.applied[next.lba] { - s.applied[next.lba] = next.lsn - } - s.history[next.lsn] = walRecord{LSN: next.lsn, LBA: next.lba, Flags: next.flags, Data: data} - s.publishedLSN = next.lsn - s.publishedHeads[next.lane] = next.laneSeq + 1 - s.deliverLocked(next, nil) - } - s.cond.Broadcast() -} - -func (s *Store) deliverLocked(req *writeRequest, err error) { - if req.delivered { - return - } - req.delivered = true - delete(s.pending, req.lsn) - req.result <- err - close(req.result) -} - -func (s *Store) laneFor(lba uint32) int { - return int((lba / s.stripeBlocks) % uint32(s.laneCount)) -} - -func (s *Store) submit(lba uint32, data []byte, sourceLSN uint64) (uint64, error) { - if lba >= s.numBlocks { - return 0, fmt.Errorf("parallelwal: LBA %d out of range", lba) - } - if len(data) != int(s.blockSize) { - return 0, fmt.Errorf("parallelwal: data size %d != block size %d", len(data), s.blockSize) - } - cp := append([]byte(nil), data...) - s.mu.Lock() - for s.reuseFence && s.terminalErr == nil && !s.closed && !s.closing { - s.cond.Wait() - } - if s.closed || s.closing { - s.mu.Unlock() - return 0, errors.New("parallelwal: write after Close") - } - if !s.recovered { - s.mu.Unlock() - return 0, ErrNotRecovered - } - if s.terminalErr != nil { - err := s.terminalErr - s.mu.Unlock() - return 0, err - } - lsn := s.nextLSN - var publicationBaseLSN uint64 - if sourceLSN != 0 { - if sourceLSN <= s.publishedLSN { - if s.applied[lba] >= sourceLSN { - s.mu.Unlock() - return sourceLSN, nil - } - s.mu.Unlock() - return 0, fmt.Errorf("parallelwal: apply LSN %d is behind published frontier %d", sourceLSN, s.publishedLSN) - } - if sourceLSN < s.nextLSN { - s.mu.Unlock() - return 0, fmt.Errorf("parallelwal: apply LSN %d collides with an in-flight LSN", sourceLSN) - } - if sourceLSN > s.nextLSN { - if s.inflightAppends != 0 { - s.mu.Unlock() - return 0, fmt.Errorf("parallelwal: cannot jump apply frontier with writes in flight") - } - // LogicalStorage permits a replica stream to begin above LSN 1. - // The unrepresented interval is an explicit retention gap, not - // an extent checkpoint; it is not catch-up eligible. - publicationBaseLSN = sourceLSN - 1 - s.nextLSN = sourceLSN - } - lsn = sourceLSN - } - laneID := s.laneFor(lba) - l := s.lanes[laneID] - if l.nextSeq-s.hdr.LaneTails[laneID] >= s.slotsPerLane { - s.mu.Unlock() - return 0, ErrWALFull - } - l.mu.Lock() - completedSeq := l.completedSeq - l.mu.Unlock() - if l.nextSeq-completedSeq >= l.queueDepth { - s.mu.Unlock() - return 0, ErrQueueFull - } - req := &writeRequest{ - lsn: lsn, - lba: lba, - flags: flagWrite, - data: cp, - lane: laneID, - laneSeq: l.nextSeq, - publicationBaseLSN: publicationBaseLSN, - result: make(chan error, 1), - } - l.nextSeq++ - s.nextLSN = lsn + 1 - s.pending[lsn] = req - s.inflightAppends++ - startDrainer := s.queueRequest(l, req) - s.mu.Unlock() - if startDrainer { - s.drainLane(l, true) - } - if err := <-req.result; err != nil { - return 0, err - } - return lsn, nil -} - -func (s *Store) Write(lba uint32, data []byte) (uint64, error) { - return s.submit(lba, data, 0) -} - -func (s *Store) WriteBatch(startLBA uint32, blocks [][]byte) ([]uint64, error) { - if len(blocks) == 0 { - return nil, nil - } - if uint64(startLBA)+uint64(len(blocks)) > uint64(s.numBlocks) { - return nil, fmt.Errorf("parallelwal: batch [%d,%d) out of range (max %d)", - startLBA, uint64(startLBA)+uint64(len(blocks)), s.numBlocks) - } - copies := make([][]byte, len(blocks)) - for i, data := range blocks { - if len(data) != int(s.blockSize) { - return nil, fmt.Errorf("parallelwal: batch block %d data size %d != block size %d", - i, len(data), s.blockSize) - } - copies[i] = append([]byte(nil), data...) - } - - s.mu.Lock() - for s.reuseFence && s.terminalErr == nil && !s.closed && !s.closing { - s.cond.Wait() - } - if s.closed || s.closing { - s.mu.Unlock() - return nil, errors.New("parallelwal: WriteBatch after Close") - } - if !s.recovered { - s.mu.Unlock() - return nil, ErrNotRecovered - } - if s.terminalErr != nil { - err := s.terminalErr - s.mu.Unlock() - return nil, err - } - perLane := make([]int, len(s.lanes)) - for i := range copies { - perLane[s.laneFor(startLBA+uint32(i))]++ - } - for laneID, count := range perLane { - l := s.lanes[laneID] - if l.nextSeq+uint64(count)-s.hdr.LaneTails[laneID] > s.slotsPerLane { - s.mu.Unlock() - return nil, ErrWALFull - } - l.mu.Lock() - completedSeq := l.completedSeq - l.mu.Unlock() - if l.nextSeq+uint64(count)-completedSeq > l.queueDepth { - s.mu.Unlock() - return nil, ErrQueueFull - } - } - - reqs := make([]*writeRequest, len(copies)) - lsns := make([]uint64, len(copies)) - for i, data := range copies { - lba := startLBA + uint32(i) - lsn := s.nextLSN + uint64(i) - laneID := s.laneFor(lba) - l := s.lanes[laneID] - req := &writeRequest{ - lsn: lsn, - lba: lba, - flags: flagWrite, - data: data, - lane: laneID, - laneSeq: l.nextSeq, - result: make(chan error, 1), - } - l.nextSeq++ - s.pending[lsn] = req - reqs[i] = req - lsns[i] = lsn - } - s.nextLSN += uint64(len(reqs)) - s.inflightAppends += len(reqs) - startDrainers := make([]bool, len(s.lanes)) - for _, req := range reqs { - if s.queueRequest(s.lanes[req.lane], req) { - startDrainers[req.lane] = true - } - } - s.mu.Unlock() - - for laneID, start := range startDrainers { - if start { - go s.drainLane(s.lanes[laneID], false) - } - } - for i, req := range reqs { - if err := <-req.result; err != nil { - return lsns[:i], err - } - } - return lsns, nil -} - -func (s *Store) Read(lba uint32) ([]byte, error) { - if lba >= s.numBlocks { - return nil, fmt.Errorf("parallelwal: LBA %d out of range", lba) - } - s.mu.RLock() - if s.closed { - s.mu.RUnlock() - return nil, errors.New("parallelwal: Read after Close") - } - if !s.recovered { - s.mu.RUnlock() - return nil, ErrNotRecovered - } - if latest, ok := s.latest[lba]; ok { - out := append([]byte(nil), latest.data...) - s.mu.RUnlock() - return out, nil - } - if staged, ok := s.baseStage[lba]; ok { - out := append([]byte(nil), staged...) - s.mu.RUnlock() - return out, nil - } - activeExtent := s.activeExtent - s.mu.RUnlock() - lock := &s.extentLocks[lba%uint32(len(s.extentLocks))] - lock.RLock() - defer lock.RUnlock() - data := make([]byte, s.blockSize) - if _, err := s.fd.ReadAt(data, s.extentOffsetFor(activeExtent, lba)); err != nil { - return nil, fmt.Errorf("parallelwal: read extent LBA %d: %w", lba, err) - } - return data, nil -} - -func (s *Store) Sync() (uint64, error) { - s.syncMu.Lock() - defer s.syncMu.Unlock() - - s.mu.Lock() - if s.closed { - s.mu.Unlock() - return 0, errors.New("parallelwal: Sync after Close") - } - if !s.recovered { - s.mu.Unlock() - return 0, ErrNotRecovered - } - fence := s.nextLSN - 1 - for s.publishedLSN < fence && s.terminalErr == nil { - s.cond.Wait() - } - if s.terminalErr != nil { - err := s.terminalErr - s.mu.Unlock() - return 0, err - } - target := s.publishedLSN - heads := s.publishedHeads - checkpoint := s.checkpointLSN - tails := s.hdr.LaneTails - walTail := s.walTail - activeExtent := s.activeExtent - needsBaseCheckpoint := s.baseCommitPending - needsCheckpoint := needsBaseCheckpoint - checkpointExtent := activeExtent - if needsBaseCheckpoint { - if !s.baseStageActive { - s.mu.Unlock() - return 0, errors.New("parallelwal: BASE frontier has no prepared extent") - } - checkpointExtent = s.baseStageSlot - } - for laneID := 0; laneID < s.laneCount; laneID++ { - if heads[laneID]-tails[laneID] > s.retainPerLane { - needsCheckpoint = true - } - } - var blocks map[uint32][]byte - if needsCheckpoint { - blocks = make(map[uint32][]byte) - for lba, latest := range s.latest { - if latest.lsn <= target { - blocks[lba] = append([]byte(nil), latest.data...) - } - } - } - s.mu.Unlock() - - if err := s.fd.Sync(); err != nil { - return 0, fmt.Errorf("parallelwal: sync lane WAL: %w", err) - } - if !needsBaseCheckpoint { - if err := s.persistHeader(target, checkpoint, heads, tails, walTail, activeExtent); err != nil { - return 0, err - } - s.mu.Lock() - if target > s.stableLSN { - s.stableLSN = target - } - s.mu.Unlock() - } - if !needsCheckpoint { - return target, nil - } - - checkpointWriteOps, err := s.writeCheckpointBlocks(checkpointExtent, blocks) - if err != nil { - return 0, err - } - if err := s.fd.Sync(); err != nil { - return 0, fmt.Errorf("parallelwal: sync checkpoint extent: %w", err) - } - newTails, newWALTail, recycleReadOps, err := s.recycleStablePrefix(heads) - if err != nil { - return 0, err - } - s.mu.Lock() - s.reuseFence = true - s.mu.Unlock() - if err := s.persistHeader(target, target, heads, newTails, newWALTail, checkpointExtent); err != nil { - s.mu.Lock() - s.reuseFence = false - s.cond.Broadcast() - s.mu.Unlock() - return 0, err - } - sealErr := s.persistHeader(target, target, heads, newTails, newWALTail, checkpointExtent) - s.mu.Lock() - if target > s.checkpointLSN { - s.checkpointLSN = target - } - if s.pendingBaseLSN <= target { - s.pendingBaseLSN = 0 - } - s.baseCommitPending = false - s.checkpointWriteOps = uint64(checkpointWriteOps) - s.recycleReadOps = uint64(recycleReadOps) - if target > s.stableLSN { - s.stableLSN = target - } - if needsBaseCheckpoint { - s.activeExtent = checkpointExtent - s.baseStageActive = false - s.baseStageSlot = 1 - checkpointExtent - s.baseStage = nil - } - s.walTail = newWALTail - for lsn := range s.history { - if lsn < newWALTail { - delete(s.history, lsn) - } - } - if sealErr != nil && s.terminalErr == nil { - s.terminalErr = fmt.Errorf("parallelwal: seal recycled checkpoint header: %w", sealErr) - } - s.reuseFence = false - s.cond.Broadcast() - s.mu.Unlock() - if sealErr != nil { - return 0, fmt.Errorf("parallelwal: seal recycled checkpoint header: %w", sealErr) - } - return target, nil -} - -func (s *Store) writeCheckpointBlocks(extent int, blocks map[uint32][]byte) (int, error) { - if len(blocks) == 0 { - return 0, nil - } - lbas := make([]uint32, 0, len(blocks)) - for lba := range blocks { - lbas = append(lbas, lba) - } - sort.Slice(lbas, func(i, j int) bool { return lbas[i] < lbas[j] }) - - maxBlocks := maxCheckpointWriteBytes / int(s.blockSize) - if maxBlocks < 1 { - maxBlocks = 1 - } - writeOps := 0 - for first := 0; first < len(lbas); { - last := first + 1 - for last < len(lbas) && - last-first < maxBlocks && - lbas[last] == lbas[last-1]+1 { - last++ - } - - lockIDs := make([]int, 0, last-first) - seenLocks := make(map[int]struct{}, last-first) - for _, lba := range lbas[first:last] { - lockID := int(lba % uint32(len(s.extentLocks))) - if _, exists := seenLocks[lockID]; !exists { - seenLocks[lockID] = struct{}{} - lockIDs = append(lockIDs, lockID) - } - } - sort.Ints(lockIDs) - for _, lockID := range lockIDs { - s.extentLocks[lockID].Lock() - } - - buf := make([]byte, (last-first)*int(s.blockSize)) - for i, lba := range lbas[first:last] { - copy(buf[i*int(s.blockSize):], blocks[lba]) - } - _, err := s.fd.WriteAt(buf, s.extentOffsetFor(extent, lbas[first])) - for i := len(lockIDs) - 1; i >= 0; i-- { - s.extentLocks[lockIDs[i]].Unlock() - } - if err != nil { - return writeOps, fmt.Errorf("parallelwal: checkpoint extent LBA range [%d,%d]: %w", - lbas[first], lbas[last-1], err) - } - writeOps++ - first = last - } - return writeOps, nil -} - -func (s *Store) persistHeader( - durable, checkpoint uint64, - heads, tails [maxLaneCount]uint64, - walTail uint64, - activeExtent int, -) error { - s.mu.Lock() - h := s.hdr - h.Generation++ - h.DurableLSN = durable - h.CheckpointLSN = checkpoint - h.WALTail = walTail - h.LaneHeads = heads - h.LaneTails = tails - h.ActiveExtent = uint8(activeExtent) - nextSlot := 1 - s.headerSlot - s.mu.Unlock() - if err := writeHeaderAt(s.fd, nextSlot, h); err != nil { - return err - } - if err := s.fd.Sync(); err != nil { - return fmt.Errorf("parallelwal: fsync header generation %d: %w", h.Generation, err) - } - s.mu.Lock() - s.hdr = h - s.headerSlot = nextSlot - s.mu.Unlock() - return nil -} - -func (s *Store) recycleStablePrefix(heads [maxLaneCount]uint64) ([maxLaneCount]uint64, uint64, int, error) { - s.mu.RLock() - h := s.hdr - walTail := s.walTail - s.mu.RUnlock() - tails := h.LaneTails - maxRecords := maxWALIOBytes / int(h.RecordSize) - if maxRecords < 1 { - maxRecords = 1 - } - buf := make([]byte, maxRecords*int(h.RecordSize)) - readOps := 0 - for laneID := 0; laneID < int(h.LaneCount); laneID++ { - head := heads[laneID] - keep := h.RetainPerLane - if head-tails[laneID] <= keep { - continue - } - newTail := head - keep - for seq := tails[laneID]; seq < newTail; { - slot := seq % h.SlotsPerLane - count := maxRecords - if untilWrap := int(h.SlotsPerLane - slot); count > untilWrap { - count = untilWrap - } - if remaining := int(newTail - seq); count > remaining { - count = remaining - } - chunk := buf[:count*int(h.RecordSize)] - off := s.lanes[laneID].base + int64(slot)*int64(h.RecordSize) - n, err := s.fd.ReadAt(chunk, off) - readOps++ - if err != nil && !errors.Is(err, io.EOF) { - return tails, walTail, readOps, storage.NewSubstrateIOFailure(err, - fmt.Sprintf("recycle read lane=%d seq-range=[%d,%d)", laneID, seq, seq+uint64(count))) - } - if n != len(chunk) { - return tails, walTail, readOps, storage.NewSubstrateIOFailure(io.ErrUnexpectedEOF, - fmt.Sprintf("recycle short read lane=%d seq-range=[%d,%d) bytes=%d", - laneID, seq, seq+uint64(count), n)) - } - for i := 0; i < count; i++ { - recordBuf := chunk[i*int(h.RecordSize) : (i+1)*int(h.RecordSize)] - rec, err := decodeRecord(recordBuf, int(h.BlockSize)) - if err != nil { - return tails, walTail, readOps, storage.NewWALIntegrityFailure(nil, - fmt.Sprintf("recycle decode lane=%d seq=%d: %v", laneID, seq+uint64(i), err)) - } - if rec.LSN+1 > walTail { - walTail = rec.LSN + 1 - } - } - seq += uint64(count) - } - tails[laneID] = newTail - } - return tails, walTail, readOps, nil -} - -func (s *Store) Recover() (uint64, error) { - s.syncMu.Lock() - defer s.syncMu.Unlock() - s.mu.Lock() - defer s.mu.Unlock() - if s.closed || s.closing { - return 0, errors.New("parallelwal: Recover after Close") - } - if len(s.pending) != 0 || s.inflightAppends != 0 { - return 0, errors.New("parallelwal: Recover with writes in flight") - } - records, err := s.scanDurableRecords() - if err != nil { - return 0, err - } - s.latest = make(map[uint32]blockVersion) - s.applied = make(map[uint32]uint64) - s.history = make(map[uint64]walRecord) - seen := make(map[uint64]struct{}, len(records)) - for _, rec := range records { - if rec.LSN == 0 || rec.LSN > s.hdr.DurableLSN { - return 0, storage.NewWALIntegrityFailure(nil, - fmt.Sprintf("record LSN=%d outside durable frontier=%d", rec.LSN, s.hdr.DurableLSN)) - } - if _, exists := seen[rec.LSN]; exists { - return 0, storage.NewWALIntegrityFailure(nil, fmt.Sprintf("duplicate committed LSN=%d", rec.LSN)) - } - seen[rec.LSN] = struct{}{} - s.history[rec.LSN] = rec - // Records at or below the checkpoint are retained only for - // catch-up. Their bytes are already represented by the extent - // and must not override a later BASE rebuild written there. - if rec.LSN > s.hdr.CheckpointLSN && rec.LSN > s.applied[rec.LBA] { - s.applied[rec.LBA] = rec.LSN - s.latest[rec.LBA] = blockVersion{lsn: rec.LSN, data: append([]byte(nil), rec.Data...)} - } - } - if s.hdr.CheckpointLSN < s.hdr.DurableLSN { - replayFloor := s.hdr.CheckpointLSN + 1 - if s.hdr.WALTail > replayFloor { - replayFloor = s.hdr.WALTail - } - if replayFloor <= s.hdr.DurableLSN { - for lsn := replayFloor; ; lsn++ { - if _, ok := seen[lsn]; !ok { - return 0, storage.NewWALIntegrityFailure(nil, - fmt.Sprintf("committed WAL hole LSN=%d checkpoint=%d durable=%d", - lsn, s.hdr.CheckpointLSN, s.hdr.DurableLSN)) - } - if lsn == s.hdr.DurableLSN { - break - } - } - } - } - s.nextLSN = s.hdr.DurableLSN + 1 - s.stableLSN = s.hdr.DurableLSN - s.checkpointLSN = s.hdr.CheckpointLSN - s.pendingBaseLSN = 0 - s.baseCommitPending = false - s.walTail = s.hdr.WALTail - s.publishedLSN = s.hdr.DurableLSN - s.publishedHeads = s.hdr.LaneHeads - s.activeExtent = int(s.hdr.ActiveExtent) - s.baseStageActive = false - s.baseStageSlot = 1 - s.activeExtent - s.baseStage = nil - for i, l := range s.lanes { - l.nextSeq = s.hdr.LaneHeads[i] - l.mu.Lock() - l.completedSeq = s.hdr.LaneHeads[i] - l.mu.Unlock() - } - s.recovered = true - return s.stableLSN, nil -} - -func (s *Store) scanDurableRecords() ([]walRecord, error) { - records := make([]walRecord, 0) - buf := make([]byte, s.hdr.RecordSize) - for laneID := 0; laneID < int(s.hdr.LaneCount); laneID++ { - l := s.lanes[laneID] - for seq := s.hdr.LaneTails[laneID]; seq < s.hdr.LaneHeads[laneID]; seq++ { - slot := seq % s.hdr.SlotsPerLane - off := l.base + int64(slot)*int64(s.hdr.RecordSize) - n, err := s.fd.ReadAt(buf, off) - if err != nil && !errors.Is(err, io.EOF) { - return nil, storage.NewSubstrateIOFailure(err, - fmt.Sprintf("read lane=%d seq=%d", laneID, seq)) - } - if n != len(buf) { - return nil, storage.NewSubstrateIOFailure(io.ErrUnexpectedEOF, - fmt.Sprintf("short read lane=%d seq=%d bytes=%d want=%d", laneID, seq, n, len(buf))) - } - rec, err := decodeRecord(buf, int(s.hdr.BlockSize)) - if err != nil { - return nil, storage.NewWALIntegrityFailure(nil, - fmt.Sprintf("decode lane=%d seq=%d: %v", laneID, seq, err)) - } - if rec.LBA >= s.numBlocks { - return nil, storage.NewWALIntegrityFailure(nil, - fmt.Sprintf("record LSN=%d LBA=%d outside numBlocks=%d", rec.LSN, rec.LBA, s.numBlocks)) - } - if rec.Flags != flagWrite { - return nil, storage.NewWALIntegrityFailure(nil, - fmt.Sprintf("record LSN=%d has unsupported flags=%d", rec.LSN, rec.Flags)) - } - if want := s.laneFor(rec.LBA); want != laneID { - return nil, storage.NewWALIntegrityFailure(nil, - fmt.Sprintf("lane mapping mismatch LSN=%d LBA=%d got=%d want=%d", rec.LSN, rec.LBA, laneID, want)) - } - records = append(records, rec) - } - } - sort.Slice(records, func(i, j int) bool { return records[i].LSN < records[j].LSN }) - return records, nil -} - -func (s *Store) Boundaries() (R, S, H uint64) { - s.mu.RLock() - defer s.mu.RUnlock() - if s.publishedLSN == 0 { - return s.stableLSN, 0, 0 - } - return s.stableLSN, s.walTail, s.publishedLSN -} - -func (s *Store) NextLSN() uint64 { - s.mu.RLock() - defer s.mu.RUnlock() - return s.nextLSN -} - -func (s *Store) NumBlocks() uint32 { return s.numBlocks } -func (s *Store) BlockSize() int { return int(s.blockSize) } - -func (s *Store) AdvanceFrontier(lsn uint64) { - s.syncMu.Lock() - defer s.syncMu.Unlock() - - s.mu.Lock() - defer s.mu.Unlock() - for (len(s.pending) != 0 || s.inflightAppends != 0) && s.terminalErr == nil { - s.cond.Wait() - } - if s.terminalErr != nil { - return - } - if lsn == ^uint64(0) { - s.terminalErr = errors.New("parallelwal: BASE frontier overflows next LSN") - s.cond.Broadcast() - return - } - if lsn > s.publishedLSN { - s.publishedLSN = lsn - s.nextLSN = lsn + 1 - } - committingBase := s.baseStageActive - if committingBase { - s.pendingBaseLSN = lsn - s.baseCommitPending = true - } - if lsn+1 > s.walTail { - s.walTail = lsn + 1 - } - for historyLSN := range s.history { - if historyLSN <= lsn { - delete(s.history, historyLSN) - } - } - if committingBase { - for lba, latest := range s.latest { - if latest.lsn <= lsn { - delete(s.latest, lba) - } - } - for lba, appliedLSN := range s.applied { - if appliedLSN <= lsn { - delete(s.applied, lba) - } - } - } -} - -func (s *Store) AdvanceWALTail(newTail uint64) { - s.mu.Lock() - defer s.mu.Unlock() - if newTail > s.walTail { - s.walTail = newTail - } -} - -func (s *Store) ApplyEntry(lba uint32, data []byte, lsn uint64) error { - _, err := s.submit(lba, data, lsn) - return err -} - -// BeginBaseStage resets the inactive extent used for the next rebuild. -// The active extent remains authoritative until Sync publishes a header that -// atomically switches ActiveExtent. -func (s *Store) BeginBaseStage() error { - s.syncMu.Lock() - defer s.syncMu.Unlock() - return s.resetBaseStageUnderSync() -} - -func (s *Store) WriteExtentDirect(lba uint32, data []byte) error { - if lba >= s.numBlocks { - return fmt.Errorf("parallelwal: WriteExtentDirect LBA %d out of range", lba) - } - if len(data) != int(s.blockSize) { - return fmt.Errorf("parallelwal: WriteExtentDirect data size %d != block size %d", len(data), s.blockSize) - } - s.syncMu.Lock() - defer s.syncMu.Unlock() - if err := s.ensureBaseStageUnderSync(); err != nil { - return err - } - s.mu.RLock() - if s.closed || s.closing { - s.mu.RUnlock() - return errors.New("parallelwal: WriteExtentDirect after Close") - } - if !s.recovered { - s.mu.RUnlock() - return ErrNotRecovered - } - stageSlot := s.baseStageSlot - s.mu.RUnlock() - lock := &s.extentLocks[lba%uint32(len(s.extentLocks))] - lock.Lock() - defer lock.Unlock() - if _, err := s.fd.WriteAt(data, s.extentOffsetFor(stageSlot, lba)); err != nil { - return fmt.Errorf("parallelwal: WriteExtentDirect LBA %d: %w", lba, err) - } - s.mu.Lock() - s.baseStage[lba] = append([]byte(nil), data...) - delete(s.latest, lba) - delete(s.applied, lba) - s.mu.Unlock() - return nil -} - -func (s *Store) ensureBaseStageUnderSync() error { - s.mu.RLock() - active := s.baseStageActive - s.mu.RUnlock() - if active { - return nil - } - return s.resetBaseStageUnderSync() -} - -func (s *Store) resetBaseStageUnderSync() error { - s.mu.RLock() - if s.closed || s.closing { - s.mu.RUnlock() - return errors.New("parallelwal: BeginBaseInstall after Close") - } - if !s.recovered { - s.mu.RUnlock() - return ErrNotRecovered - } - if s.terminalErr != nil { - err := s.terminalErr - s.mu.RUnlock() - return err - } - stageSlot := 1 - s.activeExtent - stageBase := s.extentBases[stageSlot] - extentBytes := int64(s.numBlocks) * int64(s.blockSize) - h := s.hdr - activeExtent := s.activeExtent - s.mu.RUnlock() - - // Make both valid header generations reference the current active extent - // before reusing the inactive one. This preserves dual-header fallback if - // the newest header is later damaged while the next BASE stage is partial. - if err := s.persistHeader( - h.DurableLSN, - h.CheckpointLSN, - h.LaneHeads, - h.LaneTails, - h.WALTail, - activeExtent, - ); err != nil { - return fmt.Errorf("parallelwal: seal active extent before BASE stage: %w", err) - } - - s.mu.Lock() - s.baseStageActive = false - s.baseStage = nil - s.mu.Unlock() - - const zeroChunkSize = 1 << 20 - chunkSize := int64(zeroChunkSize) - if extentBytes < chunkSize { - chunkSize = extentBytes - } - zero := make([]byte, int(chunkSize)) - for offset := int64(0); offset < extentBytes; offset += chunkSize { - n := chunkSize - if remaining := extentBytes - offset; remaining < n { - n = remaining - } - if _, err := s.fd.WriteAt(zero[:int(n)], stageBase+offset); err != nil { - return fmt.Errorf("parallelwal: reset BASE stage at offset %d: %w", offset, err) - } - } - - s.mu.Lock() - s.baseStageActive = true - s.baseStageSlot = stageSlot - s.baseStage = make(map[uint32][]byte) - s.mu.Unlock() - return nil -} - -func (s *Store) AllBlocks() (map[uint32][]byte, error) { - out := make(map[uint32][]byte) - zero := make([]byte, s.blockSize) - for lba := uint32(0); lba < s.numBlocks; lba++ { - data, err := s.Read(lba) - if err != nil { - return nil, fmt.Errorf("snapshot LBA %d: %w", lba, err) - } - if !bytes.Equal(data, zero) { - out[lba] = data - } - } - return out, nil -} - -func (s *Store) ScanLBAs(fromLSN uint64, fn func(storage.RecoveryEntry) error) error { - if fn == nil { - return errors.New("parallelwal: ScanLBAs nil callback") - } - s.mu.RLock() - if fromLSN+1 < s.walTail { - floor := s.walTail - s.mu.RUnlock() - return storage.NewWALRecycledFailure(nil, - fmt.Sprintf("fromLSN=%d walTail=%d", fromLSN, floor)) - } - head := s.publishedLSN - records := make([]walRecord, 0, len(s.history)) - for lsn, rec := range s.history { - if lsn > fromLSN && lsn <= head { - records = append(records, walRecord{ - LSN: rec.LSN, LBA: rec.LBA, Flags: rec.Flags, Data: append([]byte(nil), rec.Data...), - }) - } - } - s.mu.RUnlock() - sort.Slice(records, func(i, j int) bool { return records[i].LSN < records[j].LSN }) - for _, rec := range records { - if err := fn(storage.RecoveryEntry{ - LSN: rec.LSN, LBA: rec.LBA, Flags: storage.RecoveryEntryWrite, Data: rec.Data, - }); err != nil { - return err - } - } - return nil -} - -func (s *Store) RecoveryMode() storage.RecoveryMode { - return storage.RecoveryModeWALReplay -} - -func (s *Store) AppliedLSNs() (map[uint32]uint64, error) { - s.mu.RLock() - defer s.mu.RUnlock() - out := make(map[uint32]uint64, len(s.applied)) - for lba, lsn := range s.applied { - out[lba] = lsn - } - return out, nil -} - -func (s *Store) Close() error { - s.mu.Lock() - if s.closed { - s.mu.Unlock() - return nil - } - if s.closing { - for !s.closed { - s.cond.Wait() - } - s.mu.Unlock() - return nil - } - s.closing = true - for len(s.pending) != 0 || s.inflightAppends != 0 { - s.cond.Wait() - } - s.mu.Unlock() - - _, syncErr := s.Sync() - s.mu.Lock() - s.closed = true - s.closing = false - s.cond.Broadcast() - s.mu.Unlock() - closeErr := s.fd.Close() - return errors.Join(syncErr, closeErr) -} - -func (s *Store) extentOffsetFor(extent int, lba uint32) int64 { - return s.extentBases[extent] + int64(lba)*int64(s.blockSize) -} - -var ( - _ storage.LogicalStorage = (*Store)(nil) - _ storage.BaseStager = (*Store)(nil) -) diff --git a/seaweed-block/core/storage/parallelwal/store_test.go b/seaweed-block/core/storage/parallelwal/store_test.go deleted file mode 100644 index b3afd5b6f0..0000000000 --- a/seaweed-block/core/storage/parallelwal/store_test.go +++ /dev/null @@ -1,1428 +0,0 @@ -package parallelwal - -import ( - "errors" - "fmt" - "os" - "path/filepath" - "sync" - "testing" - "time" - - "github.com/seaweedfs/seaweed-block/core/storage" -) - -func testConfig() Config { - return Config{ - NumBlocks: 32, - BlockSize: 512, - LaneCount: 4, - StripeBlocks: 1, - SlotsPerLane: 16, - QueueDepth: 8, - } -} - -func testBlock(fill byte, size int) []byte { - out := make([]byte, size) - for i := range out { - out[i] = fill - } - return out -} - -func createTestStore(t *testing.T) (*Store, string) { - t.Helper() - path := filepath.Join(t.TempDir(), "parallelwal.bin") - s, err := CreateStoreWithConfig(path, testConfig()) - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { - if !s.closed { - _ = s.Close() - } - }) - return s, path -} - -func crashStore(t *testing.T, s *Store) { - t.Helper() - s.mu.Lock() - if len(s.pending) != 0 { - s.mu.Unlock() - t.Fatal("crashStore called with writes in flight") - } - s.closed = true - s.mu.Unlock() - if err := s.fd.Close(); err != nil { - t.Fatal(err) - } -} - -func TestCreateSyncRecoverAndScan(t *testing.T) { - s, path := createTestStore(t) - for lba := uint32(0); lba < 4; lba++ { - lsn, err := s.Write(lba, testBlock(byte(lba+1), s.BlockSize())) - if err != nil { - t.Fatal(err) - } - if want := uint64(lba + 1); lsn != want { - t.Fatalf("Write(%d) LSN=%d want=%d", lba, lsn, want) - } - } - if got, err := s.Sync(); err != nil || got != 4 { - t.Fatalf("Sync=(%d,%v) want=(4,nil)", got, err) - } - if R, S, H := s.Boundaries(); R != 4 || S != 1 || H != 4 { - t.Fatalf("Boundaries=(%d,%d,%d) want=(4,1,4)", R, S, H) - } - crashStore(t, s) - - reopened, err := OpenStore(path) - if err != nil { - t.Fatal(err) - } - defer reopened.Close() - if got, err := reopened.Recover(); err != nil || got != 4 { - t.Fatalf("Recover=(%d,%v) want=(4,nil)", got, err) - } - for lba := uint32(0); lba < 4; lba++ { - got, err := reopened.Read(lba) - if err != nil { - t.Fatal(err) - } - if want := testBlock(byte(lba+1), reopened.BlockSize()); string(got) != string(want) { - t.Fatalf("Read(%d) mismatch", lba) - } - } - var gotLSNs []uint64 - if err := reopened.ScanLBAs(0, func(entry storage.RecoveryEntry) error { - gotLSNs = append(gotLSNs, entry.LSN) - return nil - }); err != nil { - t.Fatal(err) - } - if len(gotLSNs) != 4 { - t.Fatalf("ScanLBAs emitted %v", gotLSNs) - } - for i, got := range gotLSNs { - if want := uint64(i + 1); got != want { - t.Fatalf("ScanLBAs[%d]=%d want=%d", i, got, want) - } - } -} - -func TestCrossLaneCompletionPublishesContiguousLSNs(t *testing.T) { - s, _ := createTestStore(t) - entered := make(chan struct{}) - release := make(chan struct{}) - s.lanes[0].beforeWrite = func(*writeRequest) { - close(entered) - <-release - } - - type result struct { - lsn uint64 - err error - } - first := make(chan result, 1) - second := make(chan result, 1) - go func() { - lsn, err := s.Write(0, testBlock(1, s.BlockSize())) - first <- result{lsn: lsn, err: err} - }() - <-entered - go func() { - lsn, err := s.Write(1, testBlock(2, s.BlockSize())) - second <- result{lsn: lsn, err: err} - }() - - select { - case got := <-second: - t.Fatalf("higher LSN returned before lower lane completed: %+v", got) - case <-time.After(50 * time.Millisecond): - } - if _, _, H := s.Boundaries(); H != 0 { - t.Fatalf("H=%d while LSN 1 is incomplete", H) - } - close(release) - if got := <-first; got.err != nil || got.lsn != 1 { - t.Fatalf("first=%+v", got) - } - if got := <-second; got.err != nil || got.lsn != 2 { - t.Fatalf("second=%+v", got) - } - if _, _, H := s.Boundaries(); H != 2 { - t.Fatalf("H=%d want=2", H) - } -} - -func TestSyncFencesWritesAdmittedBeforeCall(t *testing.T) { - s, path := createTestStore(t) - entered := make(chan struct{}) - release := make(chan struct{}) - s.lanes[0].beforeWrite = func(*writeRequest) { - close(entered) - <-release - } - - writeDone := make(chan error, 1) - go func() { - _, err := s.Write(0, testBlock(0x41, s.BlockSize())) - writeDone <- err - }() - <-entered - syncDone := make(chan error, 1) - go func() { - stable, err := s.Sync() - if err == nil && stable != 1 { - err = fmt.Errorf("stable=%d want=1", stable) - } - syncDone <- err - }() - select { - case err := <-syncDone: - t.Fatalf("Sync returned before admitted append completed: %v", err) - case <-time.After(50 * time.Millisecond): - } - close(release) - if err := <-writeDone; err != nil { - t.Fatal(err) - } - if err := <-syncDone; err != nil { - t.Fatal(err) - } - crashStore(t, s) - - reopened, err := OpenStore(path) - if err != nil { - t.Fatal(err) - } - defer reopened.Close() - if _, err := reopened.Recover(); err != nil { - t.Fatal(err) - } - got, err := reopened.Read(0) - if err != nil { - t.Fatal(err) - } - if got[0] != 0x41 { - t.Fatalf("recovered byte=%02x want=41", got[0]) - } -} - -func TestLowerLSNFailureBlocksCompletedHigherLane(t *testing.T) { - s, _ := createTestStore(t) - entered := make(chan struct{}) - release := make(chan struct{}) - s.lanes[0].beforeWrite = func(*writeRequest) { - close(entered) - <-release - s.lanes[0].base = -int64(s.hdr.RecordSize) - } - - first := make(chan error, 1) - second := make(chan error, 1) - go func() { - _, err := s.Write(0, testBlock(1, s.BlockSize())) - first <- err - }() - <-entered - go func() { - _, err := s.Write(1, testBlock(2, s.BlockSize())) - second <- err - }() - time.Sleep(20 * time.Millisecond) - close(release) - - if err := <-first; err == nil { - t.Fatal("lower LSN unexpectedly succeeded") - } - if err := <-second; err == nil { - t.Fatal("higher LSN escaped lower-LSN terminal failure") - } - if _, _, H := s.Boundaries(); H != 0 { - t.Fatalf("H=%d after terminal lower-LSN failure", H) - } - if _, err := s.Sync(); err == nil { - t.Fatal("Sync succeeded after terminal lane failure") - } -} - -func TestCloseDrainsActiveAppenderAfterTerminalFailure(t *testing.T) { - s, _ := createTestStore(t) - entered := make(chan struct{}) - release := make(chan struct{}) - s.lanes[0].beforeWrite = func(*writeRequest) { - close(entered) - <-release - } - - first := make(chan error, 1) - go func() { - _, err := s.Write(0, testBlock(1, s.BlockSize())) - first <- err - }() - <-entered - s.lanes[1].base = -int64(s.recordSize) - if _, err := s.Write(1, testBlock(2, s.BlockSize())); err == nil { - t.Fatal("terminal append unexpectedly succeeded") - } - - closeDone := make(chan error, 1) - go func() { closeDone <- s.Close() }() - select { - case err := <-closeDone: - t.Fatalf("Close returned while an appender still owned the fd: %v", err) - case <-time.After(50 * time.Millisecond): - } - close(release) - if err := <-first; err == nil { - t.Fatal("blocked append did not receive terminal failure") - } - if err := <-closeDone; err == nil { - t.Fatal("Close after terminal append failure returned nil") - } -} - -func TestRecoverRejectsActiveAppender(t *testing.T) { - s, _ := createTestStore(t) - entered := make(chan struct{}) - release := make(chan struct{}) - s.lanes[0].beforeWrite = func(*writeRequest) { - close(entered) - <-release - } - writeDone := make(chan error, 1) - go func() { - _, err := s.Write(0, testBlock(1, s.BlockSize())) - writeDone <- err - }() - <-entered - if _, err := s.Recover(); err == nil { - t.Fatal("Recover accepted an active appender") - } - close(release) - if err := <-writeDone; err != nil { - t.Fatal(err) - } -} - -func TestUnsyncedTailIgnoredAfterCrash(t *testing.T) { - s, path := createTestStore(t) - if _, err := s.Write(0, testBlock(1, s.BlockSize())); err != nil { - t.Fatal(err) - } - if _, err := s.Sync(); err != nil { - t.Fatal(err) - } - if _, err := s.Write(1, testBlock(2, s.BlockSize())); err != nil { - t.Fatal(err) - } - crashStore(t, s) - - reopened, err := OpenStore(path) - if err != nil { - t.Fatal(err) - } - defer reopened.Close() - if got, err := reopened.Recover(); err != nil || got != 1 { - t.Fatalf("Recover=(%d,%v) want=(1,nil)", got, err) - } - got, err := reopened.Read(1) - if err != nil { - t.Fatal(err) - } - if string(got) != string(make([]byte, reopened.BlockSize())) { - t.Fatal("unsynced tail became visible after recovery") - } - if lsn, err := reopened.Write(1, testBlock(3, reopened.BlockSize())); err != nil || lsn != 2 { - t.Fatalf("replacement Write=(%d,%v) want=(2,nil)", lsn, err) - } -} - -func TestOpenFallsBackFromCorruptLatestHeader(t *testing.T) { - s, path := createTestStore(t) - if _, err := s.Write(0, testBlock(1, s.BlockSize())); err != nil { - t.Fatal(err) - } - if _, err := s.Sync(); err != nil { - t.Fatal(err) - } - // Publish the same durable frontier into the alternate header so the - // fallback retains the acknowledged state after corrupting the latest one. - if _, err := s.Sync(); err != nil { - t.Fatal(err) - } - latestSlot := s.headerSlot - crashStore(t, s) - - f, err := os.OpenFile(path, os.O_RDWR, 0o644) - if err != nil { - t.Fatal(err) - } - if _, err := f.WriteAt([]byte{0xff}, int64(latestSlot*headerSize+100)); err != nil { - t.Fatal(err) - } - if err := f.Close(); err != nil { - t.Fatal(err) - } - reopened, err := OpenStore(path) - if err != nil { - t.Fatal(err) - } - defer reopened.Close() - if _, err := reopened.Recover(); err != nil { - t.Fatalf("Recover from prior header: %v", err) - } - got, err := reopened.Read(0) - if err != nil { - t.Fatal(err) - } - if string(got) != string(testBlock(1, reopened.BlockSize())) { - t.Fatal("prior valid header did not recover committed data") - } -} - -func TestCommittedRecordCorruptionFailsClosed(t *testing.T) { - s, path := createTestStore(t) - if _, err := s.Write(0, testBlock(1, s.BlockSize())); err != nil { - t.Fatal(err) - } - if _, err := s.Sync(); err != nil { - t.Fatal(err) - } - recordOffset := s.lanes[0].base + recordHeaderSize - crashStore(t, s) - - f, err := os.OpenFile(path, os.O_RDWR, 0o644) - if err != nil { - t.Fatal(err) - } - var one [1]byte - if _, err := f.ReadAt(one[:], recordOffset); err != nil { - t.Fatal(err) - } - one[0] ^= 0xff - if _, err := f.WriteAt(one[:], recordOffset); err != nil { - t.Fatal(err) - } - if err := f.Close(); err != nil { - t.Fatal(err) - } - reopened, err := OpenStore(path) - if err != nil { - t.Fatal(err) - } - defer crashStore(t, reopened) - if _, err := reopened.Recover(); !errors.Is(err, storage.ErrWALIntegrityFault) { - t.Fatalf("Recover error=%v, want WAL integrity fault", err) - } -} - -func TestRecoveryRejectsInvalidCommittedRecordSemantics(t *testing.T) { - tests := []struct { - name string - lba uint32 - flags uint16 - }{ - {name: "out-of-range LBA", lba: testConfig().NumBlocks, flags: flagWrite}, - {name: "unknown flags", lba: 0, flags: 0x7fff}, - } - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - s, path := createTestStore(t) - if _, err := s.Write(0, testBlock(1, s.BlockSize())); err != nil { - t.Fatal(err) - } - if _, err := s.Sync(); err != nil { - t.Fatal(err) - } - replacement, err := encodeRecord(walRecord{ - LSN: 1, - LBA: tc.lba, - Flags: tc.flags, - Data: testBlock(1, s.BlockSize()), - }, s.BlockSize()) - if err != nil { - t.Fatal(err) - } - recordOffset := s.lanes[0].base - crashStore(t, s) - f, err := os.OpenFile(path, os.O_RDWR, 0o644) - if err != nil { - t.Fatal(err) - } - if _, err := f.WriteAt(replacement, recordOffset); err != nil { - _ = f.Close() - t.Fatal(err) - } - if err := f.Close(); err != nil { - t.Fatal(err) - } - reopened, err := OpenStore(path) - if err != nil { - t.Fatal(err) - } - defer crashStore(t, reopened) - if _, err := reopened.Recover(); !errors.Is(err, storage.ErrWALIntegrityFault) { - t.Fatalf("Recover error=%v want WAL integrity fault", err) - } - }) - } -} - -func TestApplyEntryAcceptsSourceFrontierJump(t *testing.T) { - s, _ := createTestStore(t) - if err := s.ApplyEntry(0, testBlock(1, s.BlockSize()), 100); err != nil { - t.Fatal(err) - } - if _, _, head := s.Boundaries(); head != 100 { - t.Fatalf("head=%d want=100", head) - } - if lsn, err := s.Write(1, testBlock(2, s.BlockSize())); err != nil || lsn != 101 { - t.Fatalf("Write=(%d,%v) want=(101,nil)", lsn, err) - } -} - -func TestFailedApplyEntryDoesNotPublishSourceFrontierJump(t *testing.T) { - s, _ := createTestStore(t) - s.lanes[0].base = -int64(s.recordSize) - if err := s.ApplyEntry(0, testBlock(1, s.BlockSize()), 100); err == nil { - t.Fatal("ApplyEntry unexpectedly succeeded") - } - if _, _, head := s.Boundaries(); head != 0 { - t.Fatalf("failed ApplyEntry published head=%d want=0", head) - } -} - -func TestSourceFrontierJumpPersistsWithoutFalseCheckpoint(t *testing.T) { - s, path := createTestStore(t) - if _, err := s.Write(0, testBlock(0x11, s.BlockSize())); err != nil { - t.Fatal(err) - } - if _, err := s.Sync(); err != nil { - t.Fatal(err) - } - if err := s.ApplyEntry(1, testBlock(0x77, s.BlockSize()), 100); err != nil { - t.Fatal(err) - } - if got, err := s.Sync(); err != nil || got != 100 { - t.Fatalf("Sync=(%d,%v) want=(100,nil)", got, err) - } - if s.hdr.CheckpointLSN != 0 || s.hdr.WALTail != 100 { - t.Fatalf("header checkpoint=%d walTail=%d want=0/100", s.hdr.CheckpointLSN, s.hdr.WALTail) - } - crashStore(t, s) - - reopened, err := OpenStore(path) - if err != nil { - t.Fatal(err) - } - defer reopened.Close() - if got, err := reopened.Recover(); err != nil || got != 100 { - t.Fatalf("Recover=(%d,%v) want frontier 100", got, err) - } - for lba, want := range []byte{0x11, 0x77} { - data, err := reopened.Read(uint32(lba)) - if err != nil { - t.Fatal(err) - } - if data[0] != want { - t.Fatalf("LBA %d byte=%02x want=%02x", lba, data[0], want) - } - } -} - -func TestConcurrentSameLBAWritesRemainOrdered(t *testing.T) { - s, _ := createTestStore(t) - const writes = 8 - var wg sync.WaitGroup - results := make(chan uint64, writes) - for i := 0; i < writes; i++ { - wg.Add(1) - go func(fill byte) { - defer wg.Done() - lsn, err := s.Write(7, testBlock(fill, s.BlockSize())) - if err != nil { - t.Errorf("Write: %v", err) - return - } - results <- lsn - }(byte(i + 1)) - } - wg.Wait() - close(results) - seen := make(map[uint64]bool) - for lsn := range results { - seen[lsn] = true - } - for lsn := uint64(1); lsn <= writes; lsn++ { - if !seen[lsn] { - t.Fatalf("missing LSN %d", lsn) - } - } - applied, err := s.AppliedLSNs() - if err != nil { - t.Fatal(err) - } - if applied[7] != writes { - t.Fatalf("applied LSN=%d want=%d", applied[7], writes) - } -} - -func TestWriteBatchDispatchesAcrossLanesBeforePublishing(t *testing.T) { - s, _ := createTestStore(t) - entered := []chan struct{}{make(chan struct{}), make(chan struct{})} - release := make(chan struct{}) - for laneID := 0; laneID < 2; laneID++ { - id := laneID - s.lanes[laneID].beforeWrite = func(*writeRequest) { - close(entered[id]) - <-release - } - } - result := make(chan error, 1) - go func() { - _, err := s.WriteBatch(0, [][]byte{ - testBlock(1, s.BlockSize()), - testBlock(2, s.BlockSize()), - }) - result <- err - }() - for _, ch := range entered { - select { - case <-ch: - case <-time.After(time.Second): - t.Fatal("batch did not dispatch to both lanes") - } - } - if _, _, H := s.Boundaries(); H != 0 { - t.Fatalf("H=%d before either lane was released", H) - } - close(release) - if err := <-result; err != nil { - t.Fatal(err) - } - if _, _, H := s.Boundaries(); H != 2 { - t.Fatalf("H=%d want=2", H) - } -} - -func TestConcurrentSameLaneWritesCoalesceWALAppends(t *testing.T) { - path := filepath.Join(t.TempDir(), "coalesce.bin") - s, err := CreateStoreWithConfig(path, Config{ - NumBlocks: 32, - BlockSize: 512, - LaneCount: 1, - StripeBlocks: 1, - SlotsPerLane: 32, - RetainPerLane: 8, - QueueDepth: 16, - }) - if err != nil { - t.Fatal(err) - } - defer s.Close() - - entered := make(chan struct{}) - release := make(chan struct{}) - var blockFirst sync.Once - s.lanes[0].beforeWrite = func(*writeRequest) { - blockFirst.Do(func() { - close(entered) - <-release - }) - } - - const writes = 8 - errs := make(chan error, writes) - go func() { - _, writeErr := s.Write(0, testBlock(1, s.BlockSize())) - errs <- writeErr - }() - <-entered - for i := 1; i < writes; i++ { - go func(lba uint32) { - _, writeErr := s.Write(lba, testBlock(byte(lba+1), s.BlockSize())) - errs <- writeErr - }(uint32(i)) - } - deadline := time.Now().Add(time.Second) - for { - s.mu.RLock() - inflight := s.inflightAppends - s.mu.RUnlock() - if inflight == writes { - break - } - if time.Now().After(deadline) { - t.Fatalf("inflight=%d want=%d", inflight, writes) - } - time.Sleep(time.Millisecond) - } - close(release) - for i := 0; i < writes; i++ { - if err := <-errs; err != nil { - t.Fatal(err) - } - } - s.mu.RLock() - writeOps := s.walWriteOps - s.mu.RUnlock() - if writeOps != 2 { - t.Fatalf("WAL write ops=%d want=2", writeOps) - } - if _, err := s.Sync(); err != nil { - t.Fatal(err) - } -} - -func TestWriteBatchSplitsWALAppendAtRingWrap(t *testing.T) { - path := filepath.Join(t.TempDir(), "wrap-batch.bin") - s, err := CreateStoreWithConfig(path, Config{ - NumBlocks: 64, - BlockSize: 512, - LaneCount: 1, - StripeBlocks: 1, - SlotsPerLane: 8, - RetainPerLane: 2, - QueueDepth: 8, - }) - if err != nil { - t.Fatal(err) - } - defer s.Close() - - for lba := uint32(0); lba < 7; lba++ { - if _, err := s.Write(lba, testBlock(byte(lba+1), s.BlockSize())); err != nil { - t.Fatal(err) - } - if _, err := s.Sync(); err != nil { - t.Fatal(err) - } - } - s.mu.RLock() - before := s.walWriteOps - s.mu.RUnlock() - if _, err := s.WriteBatch(7, [][]byte{ - testBlock(0xa1, s.BlockSize()), - testBlock(0xa2, s.BlockSize()), - testBlock(0xa3, s.BlockSize()), - }); err != nil { - t.Fatal(err) - } - s.mu.RLock() - writeOps := s.walWriteOps - before - s.mu.RUnlock() - if writeOps != 2 { - t.Fatalf("wrapped batch WAL write ops=%d want=2", writeOps) - } - if _, err := s.Sync(); err != nil { - t.Fatal(err) - } - crashStore(t, s) - - reopened, err := OpenStore(path) - if err != nil { - t.Fatal(err) - } - defer reopened.Close() - if got, err := reopened.Recover(); err != nil || got != 10 { - t.Fatalf("Recover=(%d,%v) want=(10,nil)", got, err) - } - for i, want := range []byte{0xa1, 0xa2, 0xa3} { - got, err := reopened.Read(uint32(7 + i)) - if err != nil { - t.Fatal(err) - } - if got[0] != want { - t.Fatalf("recovered LBA %d byte=%02x want=%02x", 7+i, got[0], want) - } - } -} - -func TestWriteBatchRingWrapSecondChunkFailureIsNotDurable(t *testing.T) { - path := filepath.Join(t.TempDir(), "wrap-batch-failure.bin") - s, err := CreateStoreWithConfig(path, Config{ - NumBlocks: 64, - BlockSize: 512, - LaneCount: 1, - StripeBlocks: 1, - SlotsPerLane: 8, - RetainPerLane: 2, - QueueDepth: 8, - }) - if err != nil { - t.Fatal(err) - } - defer s.Close() - - for lba := uint32(0); lba < 7; lba++ { - if _, err := s.Write(lba, testBlock(byte(lba+1), s.BlockSize())); err != nil { - t.Fatal(err) - } - if _, err := s.Sync(); err != nil { - t.Fatal(err) - } - } - s.lanes[0].beforeWrite = func(req *writeRequest) { - if req.laneSeq == 8 { - s.lanes[0].base = -int64(s.recordSize) - } - } - lsns, err := s.WriteBatch(7, [][]byte{ - testBlock(0xa1, s.BlockSize()), - testBlock(0xa2, s.BlockSize()), - testBlock(0xa3, s.BlockSize()), - }) - if err == nil { - t.Fatal("wrapped batch unexpectedly succeeded after second-chunk failure") - } - if len(lsns) != 1 || lsns[0] != 8 { - t.Fatalf("partial LSNs=%v want=[8]", lsns) - } - if R, _, H := s.Boundaries(); R != 7 || H != 8 { - t.Fatalf("Boundaries R=%d H=%d want R=7 H=8", R, H) - } - if _, err := s.Sync(); err == nil { - t.Fatal("Sync succeeded after terminal wrapped-batch failure") - } - crashStore(t, s) - - reopened, err := OpenStore(path) - if err != nil { - t.Fatal(err) - } - defer reopened.Close() - if got, err := reopened.Recover(); err != nil || got != 7 { - t.Fatalf("Recover=(%d,%v) want=(7,nil)", got, err) - } - for lba := uint32(7); lba < 10; lba++ { - got, err := reopened.Read(lba) - if err != nil { - t.Fatal(err) - } - if got[0] != 0 { - t.Fatalf("failed batch LBA %d became durable: %02x", lba, got[0]) - } - } -} - -func TestRecycleStablePrefixCoalescesIntegrityReads(t *testing.T) { - path := filepath.Join(t.TempDir(), "recycle-read.bin") - s, err := CreateStoreWithConfig(path, Config{ - NumBlocks: 256, - BlockSize: 512, - LaneCount: 1, - StripeBlocks: 1, - SlotsPerLane: 512, - RetainPerLane: 32, - QueueDepth: 512, - }) - if err != nil { - t.Fatal(err) - } - defer s.Close() - - for lba := uint32(0); lba < 256; lba++ { - if _, err := s.Write(lba, testBlock(byte(lba+1), s.BlockSize())); err != nil { - t.Fatal(err) - } - } - if _, err := s.Sync(); err != nil { - t.Fatal(err) - } - s.mu.RLock() - readOps := s.recycleReadOps - s.mu.RUnlock() - if readOps != 1 { - t.Fatalf("recycle read ops=%d want=1", readOps) - } -} - -func TestRecycleBatchedReadDetectsCorruptRecord(t *testing.T) { - path := filepath.Join(t.TempDir(), "recycle-corrupt.bin") - s, err := CreateStoreWithConfig(path, Config{ - NumBlocks: 64, - BlockSize: 512, - LaneCount: 1, - StripeBlocks: 1, - SlotsPerLane: 64, - RetainPerLane: 8, - QueueDepth: 64, - }) - if err != nil { - t.Fatal(err) - } - defer s.Close() - - for lba := uint32(0); lba < 32; lba++ { - if _, err := s.Write(lba, testBlock(byte(lba+1), s.BlockSize())); err != nil { - t.Fatal(err) - } - } - off := s.lanes[0].base + 10*int64(s.recordSize) + recordHeaderSize - var corrupt [1]byte - if _, err := s.fd.ReadAt(corrupt[:], off); err != nil { - t.Fatal(err) - } - corrupt[0] ^= 0xff - if _, err := s.fd.WriteAt(corrupt[:], off); err != nil { - t.Fatal(err) - } - if _, err := s.Sync(); !errors.Is(err, storage.ErrWALIntegrityFault) { - t.Fatalf("Sync error=%v want WAL integrity failure", err) - } -} - -func TestRingWrapRecyclesOnlyCheckpointedPrefix(t *testing.T) { - path := filepath.Join(t.TempDir(), "wrap.bin") - s, err := CreateStoreWithConfig(path, Config{ - NumBlocks: 8, - BlockSize: 512, - LaneCount: 1, - StripeBlocks: 1, - SlotsPerLane: 4, - RetainPerLane: 2, - QueueDepth: 4, - }) - if err != nil { - t.Fatal(err) - } - for i := 1; i <= 10; i++ { - if _, err := s.Write(0, testBlock(byte(i), s.BlockSize())); err != nil { - t.Fatalf("Write %d: %v", i, err) - } - if got, err := s.Sync(); err != nil || got != uint64(i) { - t.Fatalf("Sync %d=(%d,%v)", i, got, err) - } - } - R, S, H := s.Boundaries() - if R != 10 || H != 10 || S != 9 { - t.Fatalf("Boundaries=(%d,%d,%d) want=(10,9,10)", R, S, H) - } - crashStore(t, s) - - reopened, err := OpenStore(path) - if err != nil { - t.Fatal(err) - } - defer reopened.Close() - if got, err := reopened.Recover(); err != nil || got != 10 { - t.Fatalf("Recover=(%d,%v)", got, err) - } - data, err := reopened.Read(0) - if err != nil { - t.Fatal(err) - } - if data[0] != 10 { - t.Fatalf("latest byte=%d want=10", data[0]) - } - if err := reopened.ScanLBAs(7, func(storage.RecoveryEntry) error { return nil }); !errors.Is(err, storage.ErrWALRecycled) { - t.Fatalf("ScanLBAs below S error=%v want WAL recycled", err) - } - var lsns []uint64 - if err := reopened.ScanLBAs(8, func(entry storage.RecoveryEntry) error { - lsns = append(lsns, entry.LSN) - return nil - }); err != nil { - t.Fatal(err) - } - if len(lsns) != 2 || lsns[0] != 9 || lsns[1] != 10 { - t.Fatalf("retained LSNs=%v want=[9 10]", lsns) - } -} - -func TestAdvancedWALTailBeyondHeadSurvivesRecovery(t *testing.T) { - s, path := createTestStore(t) - for lba := uint32(0); lba < 2; lba++ { - if _, err := s.Write(lba, testBlock(byte(lba+1), s.BlockSize())); err != nil { - t.Fatal(err) - } - } - if _, err := s.Sync(); err != nil { - t.Fatal(err) - } - s.AdvanceWALTail(20) - if _, err := s.Sync(); err != nil { - t.Fatal(err) - } - crashStore(t, s) - - reopened, err := OpenStore(path) - if err != nil { - t.Fatal(err) - } - defer reopened.Close() - if got, err := reopened.Recover(); err != nil || got != 2 { - t.Fatalf("Recover=(%d,%v) want=(2,nil)", got, err) - } - for lba := uint32(0); lba < 2; lba++ { - data, err := reopened.Read(lba) - if err != nil { - t.Fatal(err) - } - if data[0] != byte(lba+1) { - t.Fatalf("LBA %d byte=%02x want=%02x", lba, data[0], byte(lba+1)) - } - } -} - -func TestRecoverReplaysDurableWALBeforeCheckpoint(t *testing.T) { - s, path := createTestStore(t) - if _, err := s.Write(3, testBlock(0x7a, s.BlockSize())); err != nil { - t.Fatal(err) - } - s.mu.RLock() - heads := s.publishedHeads - tails := s.hdr.LaneTails - s.mu.RUnlock() - if err := s.fd.Sync(); err != nil { - t.Fatal(err) - } - if err := s.persistHeader(1, 0, heads, tails, 1, s.activeExtent); err != nil { - t.Fatal(err) - } - crashStore(t, s) - - reopened, err := OpenStore(path) - if err != nil { - t.Fatal(err) - } - defer reopened.Close() - if got, err := reopened.Recover(); err != nil || got != 1 { - t.Fatalf("Recover=(%d,%v)", got, err) - } - data, err := reopened.Read(3) - if err != nil { - t.Fatal(err) - } - if data[0] != 0x7a { - t.Fatalf("replayed byte=%02x want=7a", data[0]) - } -} - -func TestDirectExtentFrontierPersistsWithoutSyntheticWAL(t *testing.T) { - s, path := createTestStore(t) - if err := s.WriteExtentDirect(5, testBlock(0x5a, s.BlockSize())); err != nil { - t.Fatal(err) - } - s.AdvanceFrontier(100) - if got, err := s.Sync(); err != nil || got != 100 { - t.Fatalf("Sync=(%d,%v) want=(100,nil)", got, err) - } - crashStore(t, s) - - reopened, err := OpenStore(path) - if err != nil { - t.Fatal(err) - } - defer reopened.Close() - if got, err := reopened.Recover(); err != nil || got != 100 { - t.Fatalf("Recover=(%d,%v) want=(100,nil)", got, err) - } - data, err := reopened.Read(5) - if err != nil { - t.Fatal(err) - } - if data[0] != 0x5a { - t.Fatalf("direct extent byte=%02x want=5a", data[0]) - } - if err := reopened.ScanLBAs(0, func(storage.RecoveryEntry) error { return nil }); !errors.Is(err, storage.ErrWALRecycled) { - t.Fatalf("ScanLBAs below rebuilt frontier error=%v want WAL recycled", err) - } -} - -func TestRetainedPreCheckpointWALDoesNotOverrideRebuiltExtent(t *testing.T) { - s, path := createTestStore(t) - if _, err := s.Write(5, testBlock(0x11, s.BlockSize())); err != nil { - t.Fatal(err) - } - if _, err := s.Sync(); err != nil { - t.Fatal(err) - } - if err := s.WriteExtentDirect(5, testBlock(0x77, s.BlockSize())); err != nil { - t.Fatal(err) - } - s.AdvanceFrontier(100) - if _, err := s.Sync(); err != nil { - t.Fatal(err) - } - crashStore(t, s) - - reopened, err := OpenStore(path) - if err != nil { - t.Fatal(err) - } - defer reopened.Close() - if _, err := reopened.Recover(); err != nil { - t.Fatal(err) - } - data, err := reopened.Read(5) - if err != nil { - t.Fatal(err) - } - if data[0] != 0x77 { - t.Fatalf("retained WAL overrode rebuilt extent: byte=%02x want=77", data[0]) - } -} - -func TestBaseExtentHeaderFailureKeepsPriorAcknowledgedExtent(t *testing.T) { - path := filepath.Join(t.TempDir(), "parallelwal.bin") - cfg := testConfig() - cfg.LaneCount = 1 - cfg.SlotsPerLane = 4 - cfg.RetainPerLane = 1 - s, err := CreateStoreWithConfig(path, cfg) - if err != nil { - t.Fatal(err) - } - if _, err := s.Write(0, testBlock(0x11, s.BlockSize())); err != nil { - t.Fatal(err) - } - if _, err := s.Sync(); err != nil { - t.Fatal(err) - } - if _, err := s.Write(0, testBlock(0x22, s.BlockSize())); err != nil { - t.Fatal(err) - } - if _, err := s.Sync(); err != nil { - t.Fatal(err) - } - if s.checkpointLSN != 2 || s.activeExtent != 0 { - t.Fatalf("baseline checkpoint=%d activeExtent=%d want=(2,0)", s.checkpointLSN, s.activeExtent) - } - - if err := s.BeginBaseStage(); err != nil { - t.Fatal(err) - } - if err := s.WriteExtentDirect(0, testBlock(0x77, s.BlockSize())); err != nil { - t.Fatal(err) - } - s.AdvanceFrontier(100) - s.mu.Lock() - s.headerSlot = headerSlots - s.mu.Unlock() - if _, err := s.Sync(); err == nil { - t.Fatal("Sync succeeded with invalid final header slot") - } - crashStore(t, s) - - reopened, err := OpenStore(path) - if err != nil { - t.Fatal(err) - } - defer reopened.Close() - if got, err := reopened.Recover(); err != nil || got != 2 { - t.Fatalf("Recover=(%d,%v) want=(2,nil)", got, err) - } - data, err := reopened.Read(0) - if err != nil { - t.Fatal(err) - } - if data[0] != 0x22 { - t.Fatalf("failed BASE commit changed acknowledged extent: byte=%02x want=22", data[0]) - } - if reopened.activeExtent != 0 { - t.Fatalf("activeExtent=%d want old extent 0", reopened.activeExtent) - } -} - -func TestBeginBaseInstallClearsAbortedStage(t *testing.T) { - s, path := createTestStore(t) - if err := s.BeginBaseStage(); err != nil { - t.Fatal(err) - } - if err := s.WriteExtentDirect(3, testBlock(0x55, s.BlockSize())); err != nil { - t.Fatal(err) - } - if err := s.BeginBaseStage(); err != nil { - t.Fatal(err) - } - s.AdvanceFrontier(10) - if _, err := s.Sync(); err != nil { - t.Fatal(err) - } - data, err := s.Read(3) - if err != nil { - t.Fatal(err) - } - if data[0] != 0 { - t.Fatalf("aborted BASE stage leaked into next session: byte=%02x", data[0]) - } - crashStore(t, s) - - reopened, err := OpenStore(path) - if err != nil { - t.Fatal(err) - } - defer reopened.Close() - if _, err := reopened.Recover(); err != nil { - t.Fatal(err) - } - data, err = reopened.Read(3) - if err != nil { - t.Fatal(err) - } - if data[0] != 0 { - t.Fatalf("aborted BASE stage persisted after recovery: byte=%02x", data[0]) - } -} - -func TestAdvanceFrontierWithoutBaseStageKeepsExistingData(t *testing.T) { - s, path := createTestStore(t) - if _, err := s.Write(2, testBlock(0x44, s.BlockSize())); err != nil { - t.Fatal(err) - } - if _, err := s.Sync(); err != nil { - t.Fatal(err) - } - s.AdvanceFrontier(100) - if _, err := s.Sync(); err != nil { - t.Fatal(err) - } - if s.hdr.CheckpointLSN != 0 || s.hdr.ActiveExtent != 0 { - t.Fatalf("metadata-only frontier checkpoint=%d activeExtent=%d want=(0,0)", - s.hdr.CheckpointLSN, s.hdr.ActiveExtent) - } - crashStore(t, s) - - reopened, err := OpenStore(path) - if err != nil { - t.Fatal(err) - } - defer reopened.Close() - if got, err := reopened.Recover(); err != nil || got != 100 { - t.Fatalf("Recover=(%d,%v) want=(100,nil)", got, err) - } - data, err := reopened.Read(2) - if err != nil { - t.Fatal(err) - } - if data[0] != 0x44 { - t.Fatalf("metadata-only frontier lost existing data: byte=%02x want=44", data[0]) - } -} - -func TestNextBaseStagePreservesHeaderFallbackToCurrentExtent(t *testing.T) { - s, path := createTestStore(t) - if err := s.BeginBaseStage(); err != nil { - t.Fatal(err) - } - if err := s.WriteExtentDirect(4, testBlock(0x66, s.BlockSize())); err != nil { - t.Fatal(err) - } - s.AdvanceFrontier(20) - if _, err := s.Sync(); err != nil { - t.Fatal(err) - } - if s.activeExtent != 1 { - t.Fatalf("first BASE activeExtent=%d want=1", s.activeExtent) - } - - if err := s.BeginBaseStage(); err != nil { - t.Fatal(err) - } - s.mu.RLock() - latestHeaderSlot := s.headerSlot - s.mu.RUnlock() - crashStore(t, s) - - f, err := os.OpenFile(path, os.O_RDWR, 0o644) - if err != nil { - t.Fatal(err) - } - if _, err := f.WriteAt([]byte{0}, int64(latestHeaderSlot*headerSize)); err != nil { - _ = f.Close() - t.Fatal(err) - } - if err := f.Close(); err != nil { - t.Fatal(err) - } - - reopened, err := OpenStore(path) - if err != nil { - t.Fatal(err) - } - defer reopened.Close() - if got, err := reopened.Recover(); err != nil || got != 20 { - t.Fatalf("Recover=(%d,%v) want=(20,nil)", got, err) - } - data, err := reopened.Read(4) - if err != nil { - t.Fatal(err) - } - if data[0] != 0x66 { - t.Fatalf("fallback header referenced reused extent: byte=%02x want=66", data[0]) - } - if reopened.activeExtent != 1 { - t.Fatalf("fallback activeExtent=%d want current extent 1", reopened.activeExtent) - } -} - -func TestRecycledSlotsRemainRecoverableThroughHeaderFallback(t *testing.T) { - path := filepath.Join(t.TempDir(), "parallelwal.bin") - cfg := testConfig() - cfg.LaneCount = 1 - cfg.SlotsPerLane = 4 - cfg.RetainPerLane = 1 - s, err := CreateStoreWithConfig(path, cfg) - if err != nil { - t.Fatal(err) - } - for lba, fill := range []byte{0x11, 0x22} { - if _, err := s.Write(uint32(lba), testBlock(fill, s.BlockSize())); err != nil { - t.Fatal(err) - } - if _, err := s.Sync(); err != nil { - t.Fatal(err) - } - } - if s.hdr.LaneTails[0] != 1 || s.checkpointLSN != 2 { - t.Fatalf("checkpoint tail=%d checkpoint=%d want=(1,2)", s.hdr.LaneTails[0], s.checkpointLSN) - } - - // Fill through sequence 4 without Sync. Sequence 4 reuses physical slot 0, - // which the pre-recycle header would still scan as committed LSN 1. - for lba := uint32(2); lba <= 4; lba++ { - if _, err := s.Write(lba, testBlock(byte(0x30+lba), s.BlockSize())); err != nil { - t.Fatal(err) - } - } - s.mu.RLock() - latestHeaderSlot := s.headerSlot - s.mu.RUnlock() - crashStore(t, s) - - f, err := os.OpenFile(path, os.O_RDWR, 0o644) - if err != nil { - t.Fatal(err) - } - if _, err := f.WriteAt([]byte{0}, int64(latestHeaderSlot*headerSize)); err != nil { - _ = f.Close() - t.Fatal(err) - } - if err := f.Close(); err != nil { - t.Fatal(err) - } - - reopened, err := OpenStore(path) - if err != nil { - t.Fatal(err) - } - defer reopened.Close() - if got, err := reopened.Recover(); err != nil || got != 2 { - t.Fatalf("Recover=(%d,%v) want=(2,nil)", got, err) - } - for lba, want := range []byte{0x11, 0x22} { - data, err := reopened.Read(uint32(lba)) - if err != nil { - t.Fatal(err) - } - if data[0] != want { - t.Fatalf("LBA %d byte=%02x want=%02x", lba, data[0], want) - } - } -} - -func TestCheckpointWritesCoalesceContiguousLBAs(t *testing.T) { - path := filepath.Join(t.TempDir(), "parallelwal.bin") - cfg := testConfig() - cfg.NumBlocks = 1024 - cfg.BlockSize = 4096 - s, err := CreateStoreWithConfig(path, cfg) - if err != nil { - t.Fatal(err) - } - defer s.Close() - - blocks := make(map[uint32][]byte) - for lba := uint32(0); lba < 600; lba++ { - blocks[lba] = testBlock(byte(lba%251+1), s.BlockSize()) - } - blocks[700] = testBlock(0xee, s.BlockSize()) - writeOps, err := s.writeCheckpointBlocks(s.activeExtent, blocks) - if err != nil { - t.Fatal(err) - } - if writeOps != 4 { - t.Fatalf("checkpoint write ops=%d want=4 (three bounded contiguous writes plus one gap)", writeOps) - } - for _, lba := range []uint32{0, 255, 256, 599, 700} { - data := make([]byte, s.BlockSize()) - if _, err := s.fd.ReadAt(data, s.extentOffsetFor(s.activeExtent, lba)); err != nil { - t.Fatal(err) - } - if want := blocks[lba][0]; data[0] != want { - t.Fatalf("LBA %d byte=%02x want=%02x", lba, data[0], want) - } - } -} - -func TestHeaderForConfigRejectsPersistedGeometryOverflow(t *testing.T) { - tests := []Config{ - { - NumBlocks: 1, - BlockSize: maxWALIOBytes - recordHeaderSize + 1, - LaneCount: 1, - StripeBlocks: 1, - SlotsPerLane: 2, - QueueDepth: 1, - }, - { - NumBlocks: 1, - BlockSize: int(uint64(^uint32(0)) + 1), - LaneCount: 1, - StripeBlocks: 1, - SlotsPerLane: 2, - QueueDepth: 1, - }, - { - NumBlocks: 1, - BlockSize: 512, - LaneCount: 1, - StripeBlocks: int(^uint16(0)) + 1, - SlotsPerLane: 2, - QueueDepth: 1, - }, - } - for i, cfg := range tests { - if _, err := headerForConfig(normalizeConfig(cfg)); !errors.Is(err, errBadGeometry) { - t.Fatalf("case %d error=%v want invalid geometry", i, err) - } - } -} - -func TestFileSizeRejectsMultiplicationOverflow(t *testing.T) { - h := fileHeader{ - BlockSize: 512, - NumBlocks: 1, - LaneCount: maxLaneCount, - StripeBlocks: 1, - RecordSize: 512 + recordHeaderSize, - SlotsPerLane: ^uint64(0), - RetainPerLane: 1, - WALTail: 1, - } - if _, err := fileSize(h); !errors.Is(err, errBadGeometry) { - t.Fatalf("fileSize error=%v want invalid geometry", err) - } -} - -func TestHeaderValidationRejectsWrappedRecordSize(t *testing.T) { - h := fileHeader{ - BlockSize: ^uint32(0), - NumBlocks: 1, - LaneCount: 1, - StripeBlocks: 1, - RecordSize: recordHeaderSize - 1, - SlotsPerLane: 2, - RetainPerLane: 1, - WALTail: 1, - } - if err := h.validate(); !errors.Is(err, errBadGeometry) { - t.Fatalf("validate error=%v want invalid geometry", err) - } -} diff --git a/seaweed-block/core/storage/parallelwal/volume_size_limit_test.go b/seaweed-block/core/storage/parallelwal/volume_size_limit_test.go deleted file mode 100644 index 13efe63057..0000000000 --- a/seaweed-block/core/storage/parallelwal/volume_size_limit_test.go +++ /dev/null @@ -1,23 +0,0 @@ -package parallelwal - -import ( - "os" - "path/filepath" - "strings" - "testing" -) - -func TestCreateCapacityBeforeFilesystem(t *testing.T) { - parent := filepath.Join(t.TempDir(), "file") - if err := os.WriteFile(parent, []byte("unchanged"), 0600); err != nil { - t.Fatal(err) - } - s, err := CreateStore(filepath.Join(parent, "volume"), ^uint32(0), 8192) - if s != nil { - s.Close() - t.Fatal("created oversized image") - } - if err == nil || !strings.Contains(err.Error(), "16 TiB - 4 KiB") { - t.Fatalf("capacity must precede filesystem: %v", err) - } -} diff --git a/seaweed-block/core/storage/recovery_contract.go b/seaweed-block/core/storage/recovery_contract.go index 7569d7f5ab..f4cee7f9d7 100644 --- a/seaweed-block/core/storage/recovery_contract.go +++ b/seaweed-block/core/storage/recovery_contract.go @@ -4,7 +4,7 @@ import "errors" // T4c-2 recovery contract — unified `RecoveryEntry` + `ScanLBAs` // surface across substrate impls. Promoted from T4c-pre-A POC code -// (`walstore_recovery_poc.go` + `smartwal/recovery_poc.go`); see +// (`walstore_recovery_poc.go` + the removed smartwal POC); see // `feedback_g1_pre_code_review.md` for the discipline that produced // it. Each substrate emits entries under its own sub-mode semantic // (memo §13.0a, §5.1): diff --git a/seaweed-block/core/storage/smartwal/README.md b/seaweed-block/core/storage/smartwal/README.md deleted file mode 100644 index 86ab410634..0000000000 --- a/seaweed-block/core/storage/smartwal/README.md +++ /dev/null @@ -1,114 +0,0 @@ -# smartwal — experimental persistence backend - -Experimental implementation of `core/storage.LogicalStorage` using a -metadata-only WAL with extent-direct writes. - -**Status: experimental.** Not the default backend, not advertised in -the sparrow scope statement, not exercised by `--persist-demo`. The -default crash-safe backend is `core/storage.WALStore`. SmartWAL lives -in this subpackage so the contract surface (LogicalStorage) is shown -to admit more than one implementation, and so this code can be -removed or extracted without touching the main storage API. - -## When this design wins - -| Compared to the default `WALStore` | smartwal benefit | -|---|---| -| WAL space per record | 32 bytes vs ~4138 bytes — **128× denser** | -| Read path | extent direct vs dirty-map → WAL or extent — fewer hops | -| In-memory state | no dirty map needed for reads — lower steady-state RAM | -| Compaction pressure | extent IS the destination — no draining required | - -Trade-offs: - -- Slightly more recovery work (extent CRC verification per surviving - record, vs a flat WAL replay) -- Slightly more per-write IOPS (extent pwrite + ring append vs one - WAL append) -- Failure-atomicity rollback runs on WAL append errors so an - unsynced extent write cannot become "untracked durable" via a - later Sync (atomic 4KB-on-4KB pwrites cover the device-level - torn-write case) - -## How it differs from `WALStore` - -| Concern | WALStore | smartwal | -|---|---|---| -| Where data lives at write time | WAL | Extent | -| Where data lives at read time | WAL via dirty map, fall back to extent | Always extent | -| WAL record contents | full data + header + trailer (variable size) | 32-byte metadata | -| Recovery | replay WAL records into dirty map | scan ring, last-writer-wins per LBA, verify extent CRC | -| Single fsync covers both | yes (one file) | yes (one file) | -| Bounded WAL size | yes (circular) | yes (slot-based ring) | - -Both implementations satisfy the same `LogicalStorage` contract. -The 11 contract assertions in `core/storage/contract_test.go` are -mirrored here in `store_test.go` so this subpackage is -self-contained. - -## On-disk layout - -``` -[0 .. headerSize) 4KB header (magic, geometry) -[headerSize .. extentBase) ring buffer (WALSlots × 32 bytes) -[extentBase .. extentBase + numBlocks*BS) extent (block-indexed) -``` - -Slot index = LSN % WALSlots. After WALSlots distinct LSNs, older -records are overwritten. The extent retains the data; only the -metadata pointer is lost. Recovery handles this gracefully: LBAs -whose metadata is gone read as whatever extent currently holds. - -## How to use - -```go -import "github.com/seaweedfs/seaweed-block/core/storage/smartwal" - -// Create -s, err := smartwal.CreateStore("/tmp/store.bin", 1024, 4096) - -// Open existing -s, err := smartwal.OpenStore("/tmp/store.bin") -_, err = s.Recover() - -// Use as LogicalStorage -var ls storage.LogicalStorage = s -``` - -`smartwal.Store` satisfies `storage.LogicalStorage` (compile-time -assertion in `store.go`). Anything that takes a `LogicalStorage` -takes a smartwal.Store too. - -## Tests - -```bash -go test ./core/storage/smartwal/ -v -``` - -Coverage: - -- LogicalStorage contract: 11 round-trip / boundary / lifecycle tests -- SmartWAL-specific: - - `TestSmartWAL_WriteSyncCloseReopenRead` — clean round trip - - `TestSmartWAL_AckedWritesSurviveSimulatedCrash` — drops the - file handle without going through Close; acked data still - recoverable - - `TestSmartWAL_RecoverIsIdempotent` - - `TestSmartWAL_OpenRejectsBadMagic` - - `TestSmartWAL_RingWrapPreservesLatestPerLBA` — proves that - extent retains all data even when ring slots are recycled - -## What this implementation does NOT do - -- **Compaction / checkpointing.** No background flusher trims old - ring records (other than via natural wrap). Long-running stores - with sparse working sets may need it later. -- **Per-block extent CRC.** CRC is in the WAL record only. If a ring - record is overwritten before recovery, the extent block has no - external CRC to check against. -- **Multi-block writes.** Each Write is one block. Larger writes - must be split by the caller. -- **Coexistence with `WALStore`.** Different magic byte; the two - cannot read each other's files. This is intentional — they are - alternative implementations, not interchangeable on the same - bytes. diff --git a/seaweed-block/core/storage/smartwal/bench_test.go b/seaweed-block/core/storage/smartwal/bench_test.go deleted file mode 100644 index 8ff74f29a4..0000000000 --- a/seaweed-block/core/storage/smartwal/bench_test.go +++ /dev/null @@ -1,281 +0,0 @@ -package smartwal - -import ( - "path/filepath" - "testing" - "time" - - "github.com/seaweedfs/seaweed-block/core/storage" -) - -// Benchmarks comparing the three LogicalStorage implementations -// across the same workload shapes: -// -// - BlockStore: in-memory baseline, no fsync, no on-disk format -// - WALStore: regular WAL+extent backend, group-committed fsync -// - SmartWAL: experimental extent-direct backend, single fsync per Sync -// -// Run with: -// go test -bench=. -benchmem -run=^$ ./core/storage/smartwal/ -// -// The "smart vs regular" question reduces to: -// 1. Are SmartWAL writes faster, slower, or comparable to WALStore? -// 2. Are SmartWAL reads faster after the WALStore flusher has drained? -// 3. Does group commit help WALStore under concurrent writers? -// -// All benchmarks use 4096-byte blocks. Stores are sized for 262144 -// LBAs (1 GiB extent) so writes don't all land on the same LBA, and -// both backends get a 64 MiB WAL region (WALStore default; SmartWAL -// sized via CreateStoreWithSlots = 64 MiB / 32 B per slot). - -const ( - benchBlockSize = 4096 - benchNumBlocks = 262144 // 1 GiB extent - benchSmartWALSlots = uint64(64 * 1024 * 1024 / 32) // 64 MiB ring -) - -// makeBenchData returns a single fixed-content block — content -// matters less than size for these benchmarks. -func makeBenchData() []byte { - b := make([]byte, benchBlockSize) - for i := range b { - b[i] = 0x42 - } - return b -} - -// --- Setup helpers --- - -type backendSetup struct { - name string - build func(b *testing.B) storage.LogicalStorage -} - -func backends(b *testing.B) []backendSetup { - return []backendSetup{ - { - name: "BlockStore", - build: func(b *testing.B) storage.LogicalStorage { - return storage.NewBlockStore(benchNumBlocks, benchBlockSize) - }, - }, - { - name: "WALStore", - build: func(b *testing.B) storage.LogicalStorage { - dir := b.TempDir() - path := filepath.Join(dir, "store.bin") - s, err := storage.CreateWALStore(path, benchNumBlocks, benchBlockSize) - if err != nil { - b.Fatal(err) - } - b.Cleanup(func() { _ = s.Close() }) - return s - }, - }, - { - name: "SmartWAL", - build: func(b *testing.B) storage.LogicalStorage { - dir := b.TempDir() - path := filepath.Join(dir, "store.bin") - s, err := CreateStoreWithSlots(path, benchNumBlocks, benchBlockSize, benchSmartWALSlots) - if err != nil { - b.Fatal(err) - } - b.Cleanup(func() { _ = s.Close() }) - return s - }, - }, - } -} - -// --- Write-only (no Sync) --- -// -// Measures the raw write path: encode + WAL append (or extent -// pwrite + ring append). NO fsync, NO durability guarantee. - -func BenchmarkWriteNoSync(b *testing.B) { - for _, bk := range backends(b) { - b.Run(bk.name, func(b *testing.B) { - s := bk.build(b) - data := makeBenchData() - b.ResetTimer() - b.SetBytes(int64(benchBlockSize)) - for i := 0; i < b.N; i++ { - lba := uint32(i % benchNumBlocks) - if _, err := s.Write(lba, data); err != nil { - b.Fatal(err) - } - } - }) - } -} - -// --- Write + Sync per op --- -// -// Worst-case durability: every write is followed by Sync. This is -// where group commit and the per-write IOPS differences show up. - -func BenchmarkWriteSyncEach(b *testing.B) { - for _, bk := range backends(b) { - b.Run(bk.name, func(b *testing.B) { - s := bk.build(b) - data := makeBenchData() - b.ResetTimer() - b.SetBytes(int64(benchBlockSize)) - for i := 0; i < b.N; i++ { - lba := uint32(i % benchNumBlocks) - if _, err := s.Write(lba, data); err != nil { - b.Fatal(err) - } - if _, err := s.Sync(); err != nil { - b.Fatal(err) - } - } - }) - } -} - -// --- Write batched, Sync every 64 --- -// -// Realistic mid-load durability: writers buffer for a small batch -// before Sync. WALStore's group commit benefits multiple concurrent -// callers but here we test the single-writer batch case. - -func BenchmarkWriteSyncBatch64(b *testing.B) { - const batch = 64 - for _, bk := range backends(b) { - b.Run(bk.name, func(b *testing.B) { - s := bk.build(b) - data := makeBenchData() - b.ResetTimer() - b.SetBytes(int64(benchBlockSize)) - for i := 0; i < b.N; i++ { - lba := uint32(i % benchNumBlocks) - if _, err := s.Write(lba, data); err != nil { - b.Fatal(err) - } - if (i+1)%batch == 0 { - if _, err := s.Sync(); err != nil { - b.Fatal(err) - } - } - } - }) - } -} - -// --- Concurrent write + Sync --- -// -// 16 goroutines each writing-then-Syncing in a loop, sharing one -// store. Group commit on WALStore should batch fsyncs; SmartWAL's -// single-fsync-covers-both should also benefit; BlockStore has no -// fsync so it just measures lock contention. - -func BenchmarkWriteSyncConcurrent16(b *testing.B) { - const writers = 16 - for _, bk := range backends(b) { - b.Run(bk.name, func(b *testing.B) { - s := bk.build(b) - data := makeBenchData() - b.ResetTimer() - b.SetBytes(int64(benchBlockSize)) - b.SetParallelism(writers) - b.RunParallel(func(pb *testing.PB) { - lba := uint32(0) - for pb.Next() { - if _, err := s.Write(lba%benchNumBlocks, data); err != nil { - b.Fatal(err) - } - if _, err := s.Sync(); err != nil { - b.Fatal(err) - } - lba++ - } - }) - }) - } -} - -// --- Sequential read (post-write, pre-flush) --- -// -// Pre-populates the store with one block per LBA, then reads them -// all sequentially. For WALStore: reads check the dirty map first -// → WAL data path. For SmartWAL: extent direct, no dirty-map -// lookup. The difference here is the SmartWAL claim about reads. - -func BenchmarkReadSequentialPreFlush(b *testing.B) { - for _, bk := range backends(b) { - b.Run(bk.name, func(b *testing.B) { - s := bk.build(b) - data := makeBenchData() - // Populate every LBA we'll read from. - const populated = 1024 - for lba := uint32(0); lba < populated; lba++ { - if _, err := s.Write(lba, data); err != nil { - b.Fatal(err) - } - } - // NOTE: deliberately NO Sync and NO sleep — we want the - // dirty map to still be hot for WALStore. - b.ResetTimer() - b.SetBytes(int64(benchBlockSize)) - for i := 0; i < b.N; i++ { - lba := uint32(i % populated) - if _, err := s.Read(lba); err != nil { - b.Fatal(err) - } - } - }) - } -} - -// --- Sequential read (post-flush) --- -// -// Same as above, but waits for the WALStore flusher to drain the -// dirty map (so reads come from the extent). For SmartWAL there's -// no flush concept; reads come from extent either way. -// BlockStore: no flusher; reads come from in-memory map either way. - -func BenchmarkReadSequentialPostFlush(b *testing.B) { - for _, bk := range backends(b) { - b.Run(bk.name, func(b *testing.B) { - s := bk.build(b) - data := makeBenchData() - const populated = 1024 - for lba := uint32(0); lba < populated; lba++ { - if _, err := s.Write(lba, data); err != nil { - b.Fatal(err) - } - } - if _, err := s.Sync(); err != nil { - b.Fatal(err) - } - - // For WALStore, wait for the background flusher to drain - // the dirty map. Up to ~500ms is plenty for 1024 entries - // on the default 100ms flusher tick. Other backends: - // no-op (sleep doesn't hurt). - deadline := time.Now().Add(2 * time.Second) - for time.Now().Before(deadline) { - type cpr interface{ CheckpointLSN() uint64 } - if c, ok := s.(cpr); ok { - if c.CheckpointLSN() >= uint64(populated) { - break - } - time.Sleep(50 * time.Millisecond) - } else { - break - } - } - - b.ResetTimer() - b.SetBytes(int64(benchBlockSize)) - for i := 0; i < b.N; i++ { - lba := uint32(i % populated) - if _, err := s.Read(lba); err != nil { - b.Fatal(err) - } - } - }) - } -} diff --git a/seaweed-block/core/storage/smartwal/layout.go b/seaweed-block/core/storage/smartwal/layout.go deleted file mode 100644 index b605ffe861..0000000000 --- a/seaweed-block/core/storage/smartwal/layout.go +++ /dev/null @@ -1,161 +0,0 @@ -package smartwal - -import ( - "encoding/hex" - "fmt" - "io" - "os" - "sort" -) - -// Layout describes the on-disk SmartWAL geometry parsed from the file header. -// It is intentionally read-only; fault injection must use these offsets instead -// of legacy WALStore constants. -type Layout struct { - HeaderSize int64 - RecordSize int64 - WALOffset int64 - WALLength int64 - WALEnd int64 - ExtentStart int64 - ExtentBytes int64 - FileSize int64 - - BlockSize uint32 - NumBlocks uint32 - WALSlots uint64 - ImplKind uint8 - 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) { - f, err := os.Open(path) - if err != nil { - return Layout{}, fmt.Errorf("smartwal: inspect open %s: %w", path, err) - } - defer f.Close() - - hdr, err := readHeader(f) - if err != nil { - return Layout{}, err - } - if err := hdr.validate(); err != nil { - return Layout{}, err - } - st, err := f.Stat() - if err != nil { - return Layout{}, fmt.Errorf("smartwal: inspect stat %s: %w", path, err) - } - - walOffset := int64(headerSize) - walLength := int64(hdr.WALSlots) * int64(recordSize) - extentStart := walOffset + walLength - extentBytes := int64(hdr.NumBlocks) * int64(hdr.BlockSize) - required := extentStart + extentBytes - if st.Size() < required { - return Layout{}, fmt.Errorf("smartwal: truncated file: size=%d required=%d", st.Size(), required) - } - - return Layout{ - HeaderSize: int64(headerSize), - RecordSize: int64(recordSize), - WALOffset: walOffset, - WALLength: walLength, - WALEnd: walOffset + walLength, - ExtentStart: extentStart, - ExtentBytes: extentBytes, - FileSize: st.Size(), - BlockSize: hdr.BlockSize, - NumBlocks: hdr.NumBlocks, - WALSlots: hdr.WALSlots, - ImplKind: hdr.ImplKind, - ImplVersion: hdr.ImplVersion, - }, nil -} - -// RecordOffset returns the absolute file offset for the slot used by lsn. -func (l Layout) RecordOffset(lsn uint64) (int64, error) { - if l.WALSlots == 0 || l.RecordSize == 0 { - return 0, fmt.Errorf("smartwal: invalid layout: WALSlots=%d RecordSize=%d", l.WALSlots, l.RecordSize) - } - slot := lsn % l.WALSlots - return l.WALOffset + int64(slot)*l.RecordSize, nil -} - -// ContainsWALOffset reports whether off lands inside the SmartWAL ring. -func (l Layout) ContainsWALOffset(off int64) bool { - return off >= l.WALOffset && off < l.WALEnd -} - -// ContainsExtentOffset reports whether off lands inside the extent region. -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 deleted file mode 100644 index e54f0ac186..0000000000 --- a/seaweed-block/core/storage/smartwal/layout_test.go +++ /dev/null @@ -1,140 +0,0 @@ -package smartwal - -import ( - "os" - "path/filepath" - "testing" -) - -func TestInspectLayoutReadsSmartWALGeometry(t *testing.T) { - dir := t.TempDir() - path := filepath.Join(dir, "store.sw") - s, err := CreateStoreWithSlots(path, 4, 4096, 8) - if err != nil { - t.Fatalf("CreateStoreWithSlots: %v", err) - } - if err := s.Close(); err != nil { - t.Fatalf("Close: %v", err) - } - - layout, err := InspectLayout(path) - if err != nil { - t.Fatalf("InspectLayout: %v", err) - } - - if layout.HeaderSize != 4096 { - t.Fatalf("HeaderSize=%d want 4096", layout.HeaderSize) - } - if layout.RecordSize != 32 { - t.Fatalf("RecordSize=%d want 32", layout.RecordSize) - } - if layout.WALOffset != 4096 { - t.Fatalf("WALOffset=%d want 4096", layout.WALOffset) - } - if layout.WALLength != 8*32 { - t.Fatalf("WALLength=%d want %d", layout.WALLength, 8*32) - } - if layout.ExtentStart != 4096+8*32 { - t.Fatalf("ExtentStart=%d want %d", layout.ExtentStart, 4096+8*32) - } - if layout.ExtentBytes != 4*4096 { - t.Fatalf("ExtentBytes=%d want %d", layout.ExtentBytes, 4*4096) - } - if layout.FileSize != layout.ExtentStart+layout.ExtentBytes { - t.Fatalf("FileSize=%d want %d", layout.FileSize, layout.ExtentStart+layout.ExtentBytes) - } - - off, err := layout.RecordOffset(9) - if err != nil { - t.Fatalf("RecordOffset: %v", err) - } - // slot = 9 % 8 = 1 - if off != layout.WALOffset+layout.RecordSize { - t.Fatalf("RecordOffset(9)=%d want %d", off, layout.WALOffset+layout.RecordSize) - } - if !layout.ContainsWALOffset(off) { - t.Fatalf("record offset %d should be inside WAL ring", off) - } - if !layout.ContainsExtentOffset(layout.ExtentStart) { - t.Fatalf("extent start should be inside extent") - } -} - -func TestInspectLayoutRejectsNonSmartWAL(t *testing.T) { - dir := t.TempDir() - path := filepath.Join(dir, "not-smartwal.bin") - if err := os.WriteFile(path, []byte("not a smartwal file"), 0o644); err != nil { - t.Fatalf("WriteFile: %v", err) - } - if _, err := InspectLayout(path); err == nil { - t.Fatal("InspectLayout should reject non-SmartWAL files") - } -} - -func TestInspectLayoutRejectsTruncatedFile(t *testing.T) { - dir := t.TempDir() - path := filepath.Join(dir, "store.sw") - s, err := CreateStoreWithSlots(path, 4, 4096, 8) - if err != nil { - t.Fatalf("CreateStoreWithSlots: %v", err) - } - if err := s.Close(); err != nil { - t.Fatalf("Close: %v", err) - } - if err := os.Truncate(path, 4096+8*32+1); err != nil { - t.Fatalf("Truncate: %v", err) - } - if _, err := InspectLayout(path); err == nil { - 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/core/storage/smartwal/record.go b/seaweed-block/core/storage/smartwal/record.go deleted file mode 100644 index 2dcaf4c979..0000000000 --- a/seaweed-block/core/storage/smartwal/record.go +++ /dev/null @@ -1,108 +0,0 @@ -// Package smartwal is an experimental LogicalStorage implementation -// where the WAL holds 32-byte metadata records only and data lives -// directly in the extent. -// -// EXPERIMENTAL. Not advertised in the sparrow scope statement; not -// the default backend. Reach for it explicitly via -// smartwal.CreateStore / smartwal.OpenStore. The default crash-safe -// backend is core/storage.WALStore. -// -// Why a separate package: this implementation has different on-disk -// layout, different read/write/recover algorithms, and a smaller -// established blast radius from the rest of the codebase. Living in -// a subpackage signals that the contract surface (LogicalStorage) -// admits more than one implementation and that this one is opt-in. -// -// Design summary: -// -// - Single preallocated file: [superblock | slot ring | extent] -// - Each WAL slot is exactly 32 bytes (magic + LSN + LBA + dataCRC + recCRC) -// - Writes go directly to the extent; only the metadata is logged -// - Reads always come from the extent — no in-memory dirty map -// required for the read path -// - One fsync per Sync covers BOTH the extent pwrite and the WAL -// append because they live in the same file -// - Recovery scans the ring, picks the highest-LSN record per LBA, -// and verifies the extent block's CRC against the record. CRC -// mismatch (torn pre-Sync write) skips that record so the LBA's -// prior bytes remain authoritative. -// - Failure atomicity for WAL-append errors: pre-write extent bytes -// are saved and rolled back if the metadata append fails, so -// untracked data never becomes durable through a later Sync. -package smartwal - -import ( - "encoding/binary" - "hash/crc32" -) - -// recordSize is the on-disk size of one WAL slot. -const recordSize = 32 - -// Record flag bits. -const ( - flagWrite uint8 = 0x01 - flagTrim uint8 = 0x02 - flagBarrier uint8 = 0x04 -) - -// recordMagic distinguishes a populated slot from a zero-filled one. -// On a fresh WAL the file is zero, so magic byte 0 means "empty slot" -// for the recovery scanner. -const recordMagic uint8 = 0xAC - -// record is the metadata-only WAL entry. Encoded layout (32 bytes): -// -// [0:1] magic (0xAC) -// [1:2] flags -// [2:4] reserved (zeroed, available for a future implementation -// field without bumping a format version) -// [4:8] LBA (uint32, little-endian) -// [8:16] LSN (uint64, little-endian) -// [16:24] reserved2 (zeroed; was Epoch in the V2 prototype — -// dropped because the engine owns fencing in V3) -// [24:28] dataCRC32 (CRC32-IEEE of the 4KB extent block) -// [28:32] recCRC32 (CRC32-IEEE of bytes 0..27) -type record struct { - LSN uint64 - LBA uint32 - Flags uint8 - DataCRC32 uint32 -} - -// encode serializes a record into exactly recordSize bytes. -func encode(r record) [recordSize]byte { - var buf [recordSize]byte - buf[0] = recordMagic - buf[1] = r.Flags - // buf[2:4] reserved (zeros) - binary.LittleEndian.PutUint32(buf[4:8], r.LBA) - binary.LittleEndian.PutUint64(buf[8:16], r.LSN) - // buf[16:24] reserved2 (zeros — was Epoch, dropped for V3) - binary.LittleEndian.PutUint32(buf[24:28], r.DataCRC32) - rcrc := crc32.ChecksumIEEE(buf[:28]) - binary.LittleEndian.PutUint32(buf[28:32], rcrc) - return buf -} - -// decode parses one slot. Returns ok=false for an empty slot -// (magic != 0xAC) or a torn slot (record CRC mismatch). -func decode(buf []byte) (record, bool) { - if len(buf) < recordSize { - return record{}, false - } - if buf[0] != recordMagic { - return record{}, false - } - stored := binary.LittleEndian.Uint32(buf[28:32]) - expected := crc32.ChecksumIEEE(buf[:28]) - if stored != expected { - return record{}, false - } - return record{ - Flags: buf[1], - LBA: binary.LittleEndian.Uint32(buf[4:8]), - LSN: binary.LittleEndian.Uint64(buf[8:16]), - DataCRC32: binary.LittleEndian.Uint32(buf[24:28]), - }, true -} diff --git a/seaweed-block/core/storage/smartwal/record_fuzz_test.go b/seaweed-block/core/storage/smartwal/record_fuzz_test.go deleted file mode 100644 index b9c2714570..0000000000 --- a/seaweed-block/core/storage/smartwal/record_fuzz_test.go +++ /dev/null @@ -1,96 +0,0 @@ -package smartwal - -import ( - "bytes" - "encoding/binary" - "hash/crc32" - "testing" -) - -// FuzzSmartWALDecode: decode never panics; a rejected slot yields the zero -// record; an accepted slot re-encodes to the same record and to the same -// bytes outside the reserved fields. -func FuzzSmartWALDecode(f *testing.F) { - good := encode(record{LSN: 7, LBA: 3, Flags: flagWrite, DataCRC32: 0xDEADBEEF}) - f.Add(good[:]) - f.Add(make([]byte, recordSize)) - f.Add(good[:recordSize-1]) - torn := good - torn[9] ^= 1 - f.Add(torn[:]) - f.Fuzz(func(t *testing.T, buf []byte) { - r, ok := decode(buf) - if !ok { - if r != (record{}) { - t.Fatalf("rejected slot with a partial record %+v", r) - } - return - } - re := encode(r) - if got, ok := decode(re[:]); !ok || got != r { - t.Fatalf("re-encode of %+v decodes to %+v (ok %t)", r, got, ok) - } - if gap := knownSmartWALDecodeGap(buf); gap != "" { - return // pinned below - } - if !bytes.Equal(re[:], buf[:recordSize]) { - t.Fatalf("accepted slot does not re-encode to its bytes: %x vs %x", re, buf[:recordSize]) - } - }) -} - -// FuzzSmartWALRecordFields: slots with a valid magic and record CRC but -// arbitrary fields, including the reserved bytes. -func FuzzSmartWALRecordFields(f *testing.F) { - f.Add(uint8(flagWrite), uint32(3), uint64(7), uint32(0xDEADBEEF), uint16(0), uint64(0)) - f.Add(uint8(flagTrim), uint32(0), uint64(1), uint32(0), uint16(1), uint64(9)) - f.Fuzz(func(t *testing.T, flags uint8, lba uint32, lsn uint64, dataCRC uint32, res1 uint16, res2 uint64) { - var buf [recordSize]byte - buf[0] = recordMagic - buf[1] = flags - binary.LittleEndian.PutUint16(buf[2:4], res1) - binary.LittleEndian.PutUint32(buf[4:8], lba) - binary.LittleEndian.PutUint64(buf[8:16], lsn) - binary.LittleEndian.PutUint64(buf[16:24], res2) - binary.LittleEndian.PutUint32(buf[24:28], dataCRC) - binary.LittleEndian.PutUint32(buf[28:32], crc32.ChecksumIEEE(buf[:28])) - r, ok := decode(buf[:]) - if !ok { - t.Fatalf("a slot with a valid magic and CRC was rejected") - } - if r != (record{LSN: lsn, LBA: lba, Flags: flags, DataCRC32: dataCRC}) { - t.Fatalf("decoded %+v", r) - } - if gap := knownSmartWALDecodeGap(buf[:]); gap == "" { - re := encode(r) - if re != buf { - t.Fatalf("canonical slot does not re-encode to its bytes") - } - } - }) -} - -// FuzzSmartWALRoundTrip: every record encodes and decodes back to itself. -func FuzzSmartWALRoundTrip(f *testing.F) { - f.Add(uint64(7), uint32(3), uint8(flagWrite), uint32(0xDEADBEEF)) - f.Fuzz(func(t *testing.T, lsn uint64, lba uint32, flags uint8, dataCRC uint32) { - r := record{LSN: lsn, LBA: lba, Flags: flags, DataCRC32: dataCRC} - buf := encode(r) - got, ok := decode(buf[:]) - if !ok || got != r { - t.Fatalf("round trip of %+v: %+v (ok %t)", r, got, ok) - } - }) -} - -// knownSmartWALDecodeGap names accepted slots that are not canonical: -// non-zero reserved bytes (2:4, 16:24) are covered by the record CRC but -// ignored, so such a slot is accepted although encode never writes it. -// Found by FuzzSmartWALRecordFields; reported, not changed here. Any flag -// value is accepted too (decode does not check flags). -func knownSmartWALDecodeGap(buf []byte) string { - if binary.LittleEndian.Uint16(buf[2:4]) != 0 || binary.LittleEndian.Uint64(buf[16:24]) != 0 { - return "non-zero reserved bytes" - } - return "" -} diff --git a/seaweed-block/core/storage/smartwal/recovery.go b/seaweed-block/core/storage/smartwal/recovery.go deleted file mode 100644 index 310fa8cf41..0000000000 --- a/seaweed-block/core/storage/smartwal/recovery.go +++ /dev/null @@ -1,111 +0,0 @@ -package smartwal - -import ( - "fmt" - "hash/crc32" - "log" - "os" - - "github.com/seaweedfs/seaweed-block/core/storage" -) - -// runRecovery rebuilds the LSN frontier from a smartwal store's ring -// buffer and verifies extent contents. Returns the highest LSN whose -// extent block was verified to match its metadata record's CRC. -// -// Algorithm (deliberately last-writer-wins per LBA): -// -// 1. Scan the ring; collect every record whose magic + record-CRC -// check out. Sort ascending by LSN. -// 2. Build a map LBA → highest-LSN record. Older records for the -// same LBA are dominated and ignored. -// 3. For each surviving record: -// - Trim record: counts as recovered (its CRC32 covers a zero -// block; if the extent matches that, the trim is durable). -// - Write record: read the extent block, compute its CRC32, -// compare to record.DataCRC32. If they match, the write is -// durable and counts toward the recovered frontier. If they -// do NOT match, fail closed with a WAL integrity error so the -// volume cannot report Ready=True after detecting corruption. -// 4. The recovered frontier is the highest LSN among VALIDATED -// records, not just the highest LSN seen in the ring. A record -// whose CRC didn't verify cannot advance the frontier. -// -// What this does NOT attempt: -// - rollback to a known-good prior version (V2's "save old data -// before write" runs at write time, not recovery time) -// - 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) { - 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, 0, fmt.Errorf("smartwal: recovery scan: %w", err) - } - if len(records) == 0 { - log.Printf("smartwal: recovery: ring empty; nothing to verify") - return 0, len(bad), nil - } - - // Last-writer-wins map. Records arrive sorted by LSN ascending, - // so the final value in the map is naturally the highest LSN. - lastWrite := make(map[uint32]record, len(records)) - for _, rec := range records { - if cur, ok := lastWrite[rec.LBA]; !ok || rec.LSN > cur.LSN { - lastWrite[rec.LBA] = rec - } - } - - var recovered int - var highestVerifiedLSN uint64 - for _, rec := range lastWrite { - if rec.Flags&flagTrim != 0 { - // Trim: extent should be all zeros at this LBA. Verify by - // checking the CRC against zero bytes — same path as a - // regular Write check below. - data := make([]byte, blockSize) - off := extentBase + int64(rec.LBA)*int64(blockSize) - if _, err := fd.ReadAt(data, off); err != nil { - 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, 0, storage.NewWALIntegrityFailure(nil, detail) - } - recovered++ - if rec.LSN > highestVerifiedLSN { - highestVerifiedLSN = rec.LSN - } - continue - } - - data := make([]byte, blockSize) - off := extentBase + int64(rec.LBA)*int64(blockSize) - if _, err := fd.ReadAt(data, off); err != nil { - 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, 0, storage.NewWALIntegrityFailure(nil, detail) - } - recovered++ - if rec.LSN > highestVerifiedLSN { - highestVerifiedLSN = rec.LSN - } - } - - log.Printf("smartwal: recovery: %d LBAs verified, frontier=%d", - recovered, highestVerifiedLSN) - return highestVerifiedLSN, len(bad), nil -} diff --git a/seaweed-block/core/storage/smartwal/recovery_scan.go b/seaweed-block/core/storage/smartwal/recovery_scan.go deleted file mode 100644 index bea160bf9c..0000000000 --- a/seaweed-block/core/storage/smartwal/recovery_scan.go +++ /dev/null @@ -1,204 +0,0 @@ -package smartwal - -// T4c-2 production smartwal recovery muscle: tier-1 `state_convergence` -// (V3-native, per-LBA last-writer-wins) sub-mode of the `wal_delta` -// recovery content kind (memo §13.0a). -// -// Promoted from T4c-pre-A POC code (commit `66495f9`). Per memo §13 -// round-34: this sub-mode delivers state-convergent semantics — 3 -// writes to LBA=L produce 1 RecoveryEntry whose data is the latest- -// observed value at scan time. The replica's converged state is -// byte-equivalent to the primary's after the scan completes; the -// `INV-REPL-RECOVERY-STREAM-LBA-DEDUP` and `INV-REPL-RECOVERY-STREAM- -// LSN-IS-SCAN-TIME` invariants apply ONLY to this sub-mode. -// -// Scan-time LSN: the LSN field on emitted RecoveryEntry is the -// highest LSN within [fromLSN, head] that wrote that LBA. Concurrent -// live-write may bump the extent's actual data ahead of this LSN at -// scan time — POC report §3.2 documents the concurrency interaction. - -import ( - "errors" - "fmt" - "hash/crc32" - - "github.com/seaweedfs/seaweed-block/core/storage" -) - -// Local aliases keep the call-site code unchanged when promoting from -// POC types. The aliases re-export the unified storage-package types -// without imposing a substrate-specific name on callers. -type RecoveryEntry = storage.RecoveryEntry - -// ErrWALRecycled is the unified sentinel from storage; re-export so -// existing call sites continue to compile. -var ErrWALRecycled = storage.ErrWALRecycled - -// ScanLBAs emits RecoveryEntry callbacks for every LBA modified -// within the LSN range [fromLSN, head], in LSN-ascending order -// (last-writer-wins per LBA). Returns ErrWALRecycled if fromLSN's -// slot has been overwritten. -// -// Uses LSN-ordering of the slot scan to deliver entries in the -// order their LSNs occur (not LBA order). This matches V2's -// StreamEntries shape closer than a raw map iteration would. -// -// POC scope (per design memo §12.2 capability #1): -// - basic range scan with no concurrent writer -// - ErrWALRecycled detection -// - retention boundary characterization -// -// Concurrent live-write + recovery-read interaction (capability #3) -// is observable by callers but is NOT made safe at this layer — -// see POC report §3.2 for the data-staleness concern. -// -// Called by: T4c-pre-A POC tests; future transport recovery -// executor prototype (post architect decision on semantic). -// Owns: per-call buffer for the slot scan; per-LBA last-writer-wins -// map. -// Borrows: fn callback — caller retains; ScanLBAs does not retain -// references to fn or to RecoveryEntry.Data past the callback -// return. -func (s *Store) ScanLBAs(fromLSN uint64, fn func(RecoveryEntry) error) error { - if fn == nil { - return errors.New("smartwal: ScanLBAs: nil callback") - } - - // Snapshot ring capacity + current head under lock so we have - // a stable upper bound for the scan range. - s.mu.RLock() - if s.closed { - s.mu.RUnlock() - return errors.New("smartwal: ScanLBAs after Close") - } - head := s.nextLSN - capacity := s.ring.capacity - blockSize := int(s.hdr.BlockSize) - s.mu.RUnlock() - - if fromLSN >= head { - return nil // nothing to ship; caller is at-or-ahead of head - } - - // Compute oldestPreserved: the smallest LSN whose slot has not - // been overwritten. For ring capacity C and head H (exclusive), - // last C LSNs are preserved: [H-C+1, H-1] inclusive. Equivalent: - // oldestPreserved = H - C (if H > C) else 1. - var oldestPreserved uint64 - if head > capacity { - oldestPreserved = head - capacity - } else { - oldestPreserved = 1 - } - if fromLSN < oldestPreserved { - // T4d-1: wrap in typed RecoveryFailure (storage-side kind). - // Transport extracts via errors.As and maps to engine kind. - return storage.NewWALRecycledFailure( - ErrWALRecycled, - fmt.Sprintf("fromLSN=%d oldestPreserved=%d head=%d", fromLSN, oldestPreserved, head), - ) - } - - // Scan all valid slot records, filter by LSN range, last-writer- - // wins per LBA. - records, err := s.ring.scanValid() - if err != nil { - return fmt.Errorf("smartwal: ScanLBAs ring scan: %w", err) - } - - // Records arrive sorted by LSN ascending from scanValid(). - // Walk them, keeping per-LBA latest record within range. - type lbaState struct { - rec record - } - latestByLBA := make(map[uint32]lbaState) - for _, rec := range records { - if rec.LSN < fromLSN { - continue - } - if rec.LSN >= head { - continue - } - latestByLBA[rec.LBA] = lbaState{rec: rec} - } - - // Mid-scan recycle detection: if any record we collected has - // an LSN below the current oldestPreserved at emit time, the - // scan saw a torn boundary. Re-check after collection. - s.mu.RLock() - currentHead := s.nextLSN - s.mu.RUnlock() - currentOldest := uint64(1) - if currentHead > capacity { - currentOldest = currentHead - capacity - } - if fromLSN < currentOldest { - return fmt.Errorf("%w: mid-scan recycle, fromLSN=%d shifted-oldest=%d", - ErrWALRecycled, fromLSN, currentOldest) - } - - // Emit in LSN-ascending order. Build a slice from the map so - // callers see a deterministic order matching V2 StreamEntries. - emitOrder := make([]record, 0, len(latestByLBA)) - for _, st := range latestByLBA { - emitOrder = append(emitOrder, st.rec) - } - // scanValid already sorted records by LSN ascending; the map - // pass loses that order. Re-sort here. - sortRecordsByLSN(emitOrder) - - for _, rec := range emitOrder { - // Read current extent[LBA]. NOTE: this is the LATEST data - // for that LBA, which may differ from what rec.DataCRC32 - // covers if a concurrent live-write happened between the - // ring scan and this read. See POC report §3.2. - data := make([]byte, blockSize) - off := s.extentBase + int64(rec.LBA)*int64(blockSize) - if _, err := s.fd.ReadAt(data, off); err != nil { - return fmt.Errorf("smartwal: ScanLBAs read extent LBA %d: %w", rec.LBA, err) - } - - // CRC sanity: if the extent's current data does not match - // the slot's recorded CRC, log it (not an error in - // last-writer-wins semantic; the extent's current bytes - // may belong to a NEWER LSN that wrote the same LBA). - // Surfaces via report §3.2 discussion. - if crc32.ChecksumIEEE(data) != rec.DataCRC32 { - // In tier-1 state-convergence semantic, we still emit - // the current bytes — replica converges to the latest - // state. The CRC mismatch is informational. - } - - entry := RecoveryEntry{ - LSN: rec.LSN, - LBA: rec.LBA, - Flags: rec.Flags, - Data: data, - } - if err := fn(entry); err != nil { - return err - } - } - return nil -} - -// sortRecordsByLSN sorts in-place by LSN ascending. Inline to avoid -// importing sort just for this one helper at the POC layer. -func sortRecordsByLSN(recs []record) { - // Simple insertion sort — POC scope; record counts in tests - // are small (<1000 typically). - for i := 1; i < len(recs); i++ { - j := i - for j > 0 && recs[j-1].LSN > recs[j].LSN { - recs[j-1], recs[j] = recs[j], recs[j-1] - j-- - } - } -} - -// RingCapacity exposes the smartwal slot count for POC tests that -// need to characterize retention boundaries. Provisional API; not -// part of LogicalStorage. -func (s *Store) RingCapacity() uint64 { - return s.ring.capacity -} diff --git a/seaweed-block/core/storage/smartwal/recovery_scan_test.go b/seaweed-block/core/storage/smartwal/recovery_scan_test.go deleted file mode 100644 index 2449bcd935..0000000000 --- a/seaweed-block/core/storage/smartwal/recovery_scan_test.go +++ /dev/null @@ -1,455 +0,0 @@ -package smartwal - -// T4c-pre-A POC tests for smartwal recovery capabilities. -// Per design memo §12 (`v3-phase-15-t4c-recovery-protocol-design.md`): -// -// capability #1 — WAL replay (tier 1) -// capability #2 — extent enumeration (tier 3) -// capability #3 — concurrent live-write + recovery-read -// capability #4 — WAL retention behavior characterization -// -// Findings from this file feed `v3-phase-15-t4c-pre-poc-report.md`. - -import ( - "bytes" - "errors" - "fmt" - "path/filepath" - "sync" - "sync/atomic" - "testing" - "time" -) - -// poStore opens a fresh smartwal store for POC tests, with a small -// `walSlots` to make recycle scenarios reach in tens of LSNs. -func poStore(t *testing.T, walSlots uint64) *Store { - t.Helper() - path := filepath.Join(t.TempDir(), "poc.smartwal") - const numBlocks = 64 - const blockSize = 4096 - s, err := CreateStoreWithSlots(path, numBlocks, blockSize, walSlots) - if err != nil { - t.Fatalf("CreateStoreWithSlots: %v", err) - } - t.Cleanup(func() { _ = s.Close() }) - return s -} - -// writeLBA writes a deterministic block with marker byte to an LBA -// and returns the assigned LSN. -func writeLBA(t *testing.T, s *Store, lba uint32, marker byte) uint64 { - t.Helper() - data := make([]byte, s.BlockSize()) - data[0] = marker - data[1] = byte(lba) - lsn, err := s.Write(lba, data) - if err != nil { - t.Fatalf("Write LBA=%d marker=%02x: %v", lba, marker, err) - } - return lsn -} - -// --- Capability #1: WAL replay (tier 1) --- - -// TestSmartwalRecovery_ScanLBAs_BasicRange — write 5 LSNs, ScanLBAs(2) returns -// LBAs touched at LSN ≥ 2, in LSN order, with current extent data. -// Verifies the basic tier-1 shape works on smartwal under no -// concurrent writers. -func TestSmartwalRecovery_ScanLBAs_BasicRange(t *testing.T) { - s := poStore(t, 64) - - // 5 distinct LBAs, 5 distinct LSNs. - lsns := make([]uint64, 5) - for i := uint32(0); i < 5; i++ { - lsns[i] = writeLBA(t, s, i, byte(i+1)) - } - - var got []RecoveryEntry - err := s.ScanLBAs(lsns[1], func(e RecoveryEntry) error { - // Copy data because POC docs Data borrowed; here we want to - // inspect after callback returns. - dup := make([]byte, len(e.Data)) - copy(dup, e.Data) - e.Data = dup - got = append(got, e) - return nil - }) - if err != nil { - t.Fatalf("ScanLBAs: %v", err) - } - if len(got) != 4 { - t.Fatalf("entries: got %d want 4 (LSNs 2..5)", len(got)) - } - // LSN-ascending. - for i := 1; i < len(got); i++ { - if got[i].LSN <= got[i-1].LSN { - t.Fatalf("not LSN-ascending: %d at %d, prev %d at %d", - got[i].LSN, i, got[i-1].LSN, i-1) - } - } - // Each entry's data[0] must be the marker we wrote (extent has - // the latest per-LBA value; in this no-concurrent test that's - // the original write). - for _, e := range got { - expected := byte(e.LBA + 1) - if e.Data[0] != expected { - t.Fatalf("LBA %d: data[0]=%02x want %02x", e.LBA, e.Data[0], expected) - } - } -} - -// TestSmartwalRecovery_ScanLBAs_FromHeadOrAbove_Empty — ScanLBAs(head) and -// ScanLBAs(head+N) return nil, no entries. Caller is at-or-ahead of -// primary head; nothing to ship. -func TestSmartwalRecovery_ScanLBAs_FromHeadOrAbove_Empty(t *testing.T) { - s := poStore(t, 64) - for i := uint32(0); i < 3; i++ { - writeLBA(t, s, i, byte(i+1)) - } - head := s.NextLSN() - - for _, fromLSN := range []uint64{head, head + 1, head + 100} { - t.Run(fmt.Sprintf("from=%d", fromLSN), func(t *testing.T) { - count := 0 - err := s.ScanLBAs(fromLSN, func(e RecoveryEntry) error { - count++ - return nil - }) - if err != nil { - t.Fatalf("ScanLBAs(%d): %v", fromLSN, err) - } - if count != 0 { - t.Fatalf("ScanLBAs(%d): emitted %d entries, want 0", fromLSN, count) - } - }) - } -} - -// TestSmartwalRecovery_ScanLBAs_LastWriterWinsPerLBA — write LBA=0 at three -// distinct LSNs (1, 2, 3) with three different markers. ScanLBAs(1) -// must emit ONE entry for LBA=0 with the latest LSN (3) and the -// latest data marker. This is the smartwal-specific -// state-convergence semantic (extent has only latest data; -// historical writes not recoverable). -// -// FINDING: this is the substrate quirk reported in POC report §3.1. -func TestSmartwalRecovery_ScanLBAs_LastWriterWinsPerLBA(t *testing.T) { - s := poStore(t, 64) - writeLBA(t, s, 0, 0xA1) - writeLBA(t, s, 0, 0xA2) - lsn3 := writeLBA(t, s, 0, 0xA3) - - var got []RecoveryEntry - err := s.ScanLBAs(1, func(e RecoveryEntry) error { - dup := make([]byte, len(e.Data)) - copy(dup, e.Data) - e.Data = dup - got = append(got, e) - return nil - }) - if err != nil { - t.Fatalf("ScanLBAs: %v", err) - } - // Smartwal CANNOT deliver every LSN entry — it has only the - // latest per-LBA in the extent. So 3 writes to the same LBA - // produce 1 entry, not 3. - if len(got) != 1 { - t.Fatalf("entries: got %d want 1 (smartwal last-writer-wins per LBA)", len(got)) - } - if got[0].LBA != 0 { - t.Fatalf("LBA: got %d want 0", got[0].LBA) - } - if got[0].LSN != lsn3 { - t.Fatalf("LSN: got %d want %d (latest within range)", got[0].LSN, lsn3) - } - if got[0].Data[0] != 0xA3 { - t.Fatalf("Data[0]: got %02x want a3 (latest marker)", got[0].Data[0]) - } -} - -// --- Capability #1 + #4: ErrWALRecycled boundary --- - -// TestSmartwalRecovery_ScanLBAs_ErrWALRecycled — write more LSNs than the ring -// capacity holds, then ScanLBAs(1) — expect ErrWALRecycled because -// LSN 1's slot has been overwritten by a newer LSN. -// -// Capability #4 retention characterization: with `walSlots=8`, -// retention window is exactly the last 8 LSNs. -func TestSmartwalRecovery_ScanLBAs_ErrWALRecycled(t *testing.T) { - const walSlots = 8 - s := poStore(t, walSlots) - - // Write walSlots+5 = 13 LSNs. LSNs 1..5 are recycled; preserved - // window is LSNs 6..13 (last walSlots=8). - for i := uint32(0); i < walSlots+5; i++ { - writeLBA(t, s, i%4, byte(i+1)) // 4 LBAs cycled to amplify rewrites - } - - // fromLSN=1: must surface ErrWALRecycled. - err := s.ScanLBAs(1, func(e RecoveryEntry) error { return nil }) - if !errors.Is(err, ErrWALRecycled) { - t.Fatalf("ScanLBAs(1) on recycled WAL: got %v want ErrWALRecycled", err) - } - - // fromLSN at the boundary: head = walSlots+5+1 = 14 (next), so - // last walSlots = LSNs 6..13. fromLSN=6 must succeed. - count := 0 - err = s.ScanLBAs(6, func(e RecoveryEntry) error { - count++ - return nil - }) - if err != nil { - t.Fatalf("ScanLBAs(6) at retention boundary: %v", err) - } - if count == 0 { - t.Fatalf("ScanLBAs(6): emitted 0 entries; expected ≥1 (LBAs covered in [6,13])") - } - - // fromLSN one below boundary (5): must surface ErrWALRecycled. - err = s.ScanLBAs(5, func(e RecoveryEntry) error { return nil }) - if !errors.Is(err, ErrWALRecycled) { - t.Fatalf("ScanLBAs(5) just below boundary: got %v want ErrWALRecycled", err) - } -} - -// --- Capability #2: extent enumeration --- - -// TestSmartwalRecovery_AllBlocks_DeterministicOrdering — AllBlocks returns a map; -// iteration order is stable per the V3 storage contract. Verify -// content correctness; ordering is the caller's job. -func TestSmartwalRecovery_AllBlocks_DeterministicOrdering(t *testing.T) { - s := poStore(t, 64) - expected := map[uint32]byte{} - for i := uint32(0); i < 10; i++ { - marker := byte(0xB0 + i) - writeLBA(t, s, i, marker) - expected[i] = marker - } - if _, err := s.Sync(); err != nil { - t.Fatalf("Sync: %v", err) - } - - got, snapshotErr := s.AllBlocks() - - if snapshotErr != nil { - t.Fatal(snapshotErr) - } - if len(got) != len(expected) { - t.Fatalf("AllBlocks size: got %d want %d", len(got), len(expected)) - } - for lba, marker := range expected { - data, ok := got[lba] - if !ok { - t.Fatalf("AllBlocks missing LBA %d", lba) - } - if data[0] != marker { - t.Fatalf("LBA %d marker: got %02x want %02x", lba, data[0], marker) - } - } -} - -// --- Capability #3: concurrent live-write + recovery-read --- - -// TestSmartwalRecovery_ScanLBAs_ConcurrentLiveWrite_DataStaleness — exercises -// the V3-NEW capability that V2 paused (V2 paused live-ship during -// catch-up, so V2 codebase doesn't validate this concurrency). -// -// Spawns a writer goroutine that continues writing while ScanLBAs -// runs. Verifies: -// - no crash, no deadlock -// - no torn reads (extent reads always return a complete block) -// -// Documents the "data staleness" semantic: ScanLBAs may return -// {LBA, LSN_old, data_new} where data_new came from a write the -// scan didn't see (LSN > snapshot head). This is a CONCRETE -// ARTIFACT of smartwal's extent-only design. -// -// FINDING: feeds POC report §3.2. The bitmap mask rule (memo §2.2) -// at the replica level handles this: live-ship arriving with the -// newer LSN sets bitmap[LBA]=1, and a recovery-stream entry that -// arrives later for the same LBA is skipped. Within the -// recovery-stream lane alone, however, the LSN label may not match -// the data — receiver must not rely on per-recovery-entry LSN-vs- -// data consistency, only on cross-lane bitmap reconciliation. -func TestSmartwalRecovery_ScanLBAs_ConcurrentLiveWrite_DataStaleness(t *testing.T) { - s := poStore(t, 256) - - // Pre-populate. - for i := uint32(0); i < 16; i++ { - writeLBA(t, s, i, 0xC0) - } - headBeforeScan := s.NextLSN() - - // Background writer: keeps overwriting LBAs in the same range. - stop := make(chan struct{}) - var wg sync.WaitGroup - wg.Add(1) - go func() { - defer wg.Done() - marker := byte(0xD0) - for { - select { - case <-stop: - return - default: - } - for lba := uint32(0); lba < 16; lba++ { - if _, err := writeOnceWithMarker(s, lba, marker); err != nil { - return - } - } - marker++ - } - }() - - // Run ScanLBAs while writer is hammering. - collected := make(map[uint32]RecoveryEntry) - err := s.ScanLBAs(1, func(e RecoveryEntry) error { - dup := make([]byte, len(e.Data)) - copy(dup, e.Data) - e.Data = dup - collected[e.LBA] = e - return nil - }) - close(stop) - wg.Wait() - - if err != nil { - // May surface ErrWALRecycled if writer pushed past retention. - // Either outcome is informational for capability #3 — what - // we care about is no panic, no torn reads. - if !errors.Is(err, ErrWALRecycled) { - t.Fatalf("ScanLBAs under concurrent writer: %v", err) - } - t.Logf("ScanLBAs under writer: ErrWALRecycled (expected possibility; writer outpaced retention)") - return - } - - // Verify each emitted entry's data is a complete block (no torn - // read — would be detectable as a mid-block byte that's neither - // 0xC0/0xD0/0xD1/...; first/second byte are markers, the rest - // is zero from the test write pattern). - if len(collected) == 0 { - t.Skip("no entries collected; concurrency outpaced scan") - } - for lba, e := range collected { - if len(e.Data) != s.BlockSize() { - t.Fatalf("LBA %d torn read: data len=%d want %d", lba, len(e.Data), s.BlockSize()) - } - // The data we got reflects EXTENT at scan-emit time, which - // may be newer than the slot's recorded CRC. Verify the - // staleness is observable but not corrupting: the marker - // byte should be one of the values written. - marker := e.Data[0] - if marker != 0xC0 && (marker < 0xD0 || marker > 0xFF) { - t.Fatalf("LBA %d unexpected marker %02x — possible torn read", lba, marker) - } - // LSN field reflects the slot's recorded LSN; data may be - // from a NEWER LSN. This is the "data staleness" finding. - if e.LSN < 1 { - t.Fatalf("LBA %d LSN=0 — invalid", lba) - } - } - - t.Logf("FINDING: ScanLBAs under concurrent writer emitted %d entries; head before scan=%d, head after=%d. No torn reads observed. Data-staleness semantic confirmed: emitted LSN labels reflect slot record at scan-time, but extent data may belong to a newer LSN.", - len(collected), headBeforeScan, s.NextLSN()) -} - -// writeOnceWithMarker writes one block with the given marker and -// returns the assigned LSN. Used by the concurrent writer goroutine. -func writeOnceWithMarker(s *Store, lba uint32, marker byte) (uint64, error) { - data := make([]byte, s.BlockSize()) - data[0] = marker - data[1] = byte(lba) - return s.Write(lba, data) -} - -// --- Capability #4: WAL retention boundary characterization --- - -// TestSmartwalRecovery_RetentionBoundary_Characterized — measures exactly when -// ErrWALRecycled fires for a given walSlots size. Drives capability -// #4 numerically so the POC report can quote concrete values. -func TestSmartwalRecovery_RetentionBoundary_Characterized(t *testing.T) { - for _, walSlots := range []uint64{8, 16, 64} { - t.Run(fmt.Sprintf("slots=%d", walSlots), func(t *testing.T) { - s := poStore(t, walSlots) - - // Write exactly walSlots LSNs. Boundary: ALL preserved. - for i := uint32(0); i < uint32(walSlots); i++ { - writeLBA(t, s, i%4, byte(i+1)) - } - err := s.ScanLBAs(1, func(e RecoveryEntry) error { return nil }) - if err != nil { - t.Fatalf("slots=%d at boundary: ScanLBAs(1) = %v want nil", walSlots, err) - } - - // One more write: LSN 1's slot is overwritten. - writeLBA(t, s, 0, 0xFF) - err = s.ScanLBAs(1, func(e RecoveryEntry) error { return nil }) - if !errors.Is(err, ErrWALRecycled) { - t.Fatalf("slots=%d after walSlots+1: ScanLBAs(1) = %v want ErrWALRecycled", - walSlots, err) - } - - // Currently preserved window: last walSlots LSNs. With - // nextLSN = walSlots+2, oldest preserved = nextLSN - walSlots - // = 2. - fromBoundary := s.NextLSN() - walSlots - err = s.ScanLBAs(fromBoundary, func(e RecoveryEntry) error { return nil }) - if err != nil { - t.Fatalf("slots=%d at fresh boundary: ScanLBAs(%d) = %v want nil", - walSlots, fromBoundary, err) - } - }) - } -} - -// --- Sanity: smartwal API stability under POC additions --- - -// TestSmartwalRecovery_Sanity_ExistingAPIsUnchanged — verify the POC extensions -// don't break baseline smartwal behaviors. -func TestSmartwalRecovery_Sanity_ExistingAPIsUnchanged(t *testing.T) { - s := poStore(t, 64) - writeLBA(t, s, 0, 0x42) - if _, err := s.Sync(); err != nil { - t.Fatalf("Sync: %v", err) - } - got, err := s.Read(0) - if err != nil { - t.Fatalf("Read: %v", err) - } - if got[0] != 0x42 { - t.Fatalf("Read[0]=%02x want 42", got[0]) - } - - // AllBlocks still works. - all, snapshotErr := s.AllBlocks() - if snapshotErr != nil { - t.Fatal(snapshotErr) - } - if len(all) != 1 { - t.Fatalf("AllBlocks: got %d want 1", len(all)) - } - if !bytes.Equal(all[0], got) { - t.Fatal("AllBlocks LBA 0 != Read(0)") - } - - // RingCapacity is the new POC accessor; verify it's the value - // we passed at create. - if cap := s.RingCapacity(); cap != 64 { - t.Fatalf("RingCapacity: got %d want 64", cap) - } - - // New POC public type stable name check (compile-time, not - // runtime). - _ = RecoveryEntry{} - _ = ErrWALRecycled -} - -// goroutineLeakWindow is a small fixed delay used to surface -// goroutine misbehavior on POC tests. Not load-bearing. -const goroutineLeakWindow = 50 * time.Millisecond - -// _ silences unused atomic import if a future test removes its use. -var _ = atomic.AddInt64 diff --git a/seaweed-block/core/storage/smartwal/ring.go b/seaweed-block/core/storage/smartwal/ring.go deleted file mode 100644 index 0c71f5de90..0000000000 --- a/seaweed-block/core/storage/smartwal/ring.go +++ /dev/null @@ -1,93 +0,0 @@ -package smartwal - -import ( - "fmt" - "os" - "sort" - "sync" -) - -// ring is a slot-based circular buffer of fixed-size records inside a -// portion of an open file. All slot writes are pwrites — no seek -// state is maintained. Concurrent appends are safe because each -// caller computes its own absolute slot offset and the underlying -// fd.WriteAt is serialized only by the ring's own mutex. -// -// Slot index = LSN % capacity. This couples ring slot positions to -// the LSN counter, but for monotonically-increasing LSNs that's -// exactly the desired property: each LSN's metadata lands in a -// deterministic slot, and overflow (LSN > capacity) overwrites the -// oldest slot first. -// -// Sync is a separate concern: the ring does NOT fsync on append. The -// caller (Store.Sync) does one fsync per durability boundary, which -// covers both the extent and ring writes when they share a file. -type ring struct { - fd *os.File // the store file; ring lives in [base .. base+capacity*recordSize) - base int64 // absolute offset where the ring starts - capacity uint64 // number of slots - mu sync.Mutex -} - -// newRing constructs a ring view over [base .. base+capacity*recordSize). -// The caller is responsible for ensuring the file region is allocated -// and zero-filled (a fresh slot reads zeros, which decode to "empty"). -func newRing(fd *os.File, base int64, capacity uint64) *ring { - return &ring{fd: fd, base: base, capacity: capacity} -} - -// appendAt writes one record into the slot determined by lsn. Since -// slot = lsn % capacity, two writes with LSNs that collide modulo -// capacity will overwrite each other — but that only happens after -// `capacity` distinct LSNs, by which point the older record's -// metadata is no longer needed (the LBA's most recent write defines -// truth). -func (r *ring) appendAt(lsn uint64, rec record) error { - slot := lsn % r.capacity - offset := r.base + int64(slot)*recordSize - enc := encode(rec) - r.mu.Lock() - defer r.mu.Unlock() - if _, err := r.fd.WriteAt(enc[:], offset); err != nil { - return fmt.Errorf("smartwal: ring write slot %d: %w", slot, err) - } - return nil -} - -// scanValid reads every slot, decodes the valid ones, and returns -// them sorted by LSN ascending. Empty/torn slots are silently -// skipped — a fresh ring returns an empty slice with no 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, 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, bad, nil -} diff --git a/seaweed-block/core/storage/smartwal/smartwal_hole_detection_test.go b/seaweed-block/core/storage/smartwal/smartwal_hole_detection_test.go deleted file mode 100644 index cad242c948..0000000000 --- a/seaweed-block/core/storage/smartwal/smartwal_hole_detection_test.go +++ /dev/null @@ -1,106 +0,0 @@ -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 -} - -// Review finding, under the detection-only rule: 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) - } -} diff --git a/seaweed-block/core/storage/smartwal/smartwal_typed_failure_test.go b/seaweed-block/core/storage/smartwal/smartwal_typed_failure_test.go deleted file mode 100644 index 5043a34fe5..0000000000 --- a/seaweed-block/core/storage/smartwal/smartwal_typed_failure_test.go +++ /dev/null @@ -1,148 +0,0 @@ -package smartwal - -import ( - "errors" - "os" - "path/filepath" - "testing" - - "github.com/seaweedfs/seaweed-block/core/storage" -) - -// T4d-1: smartwal-side typed RecoveryFailure pin. ScanLBAs must -// return *storage.RecoveryFailure on recycle, kind WALRecycled, -// preserving errors.Is(_, ErrWALRecycled) for migration-window -// callers. - -func TestStorageRecoveryFailureKind_Smartwal_RecycleWrappedAsKind(t *testing.T) { - dir := t.TempDir() - path := filepath.Join(dir, "smartwal-recycled.sw") - s, err := CreateStore(path, 16, 4096) - if err != nil { - t.Fatalf("CreateStore: %v", err) - } - defer s.Close() - - // Write enough entries to roll the ring past capacity, so - // ScanLBAs(1, ...) trips fromLSN < oldestPreserved. - capacity := s.RingCapacity() - totalWrites := capacity + 10 - for i := uint64(0); i < totalWrites; i++ { - data := make([]byte, 4096) - data[0] = byte(i + 1) - if _, werr := s.Write(uint32(i%16), data); werr != nil { - t.Fatal(werr) - } - } - - scanErr := s.ScanLBAs(1, func(_ storage.RecoveryEntry) error { return nil }) - if scanErr == nil { - t.Fatal("expected ErrWALRecycled when fromLSN < oldestPreserved") - } - if !errors.Is(scanErr, storage.ErrWALRecycled) { - t.Errorf("smartwal ScanLBAs error must satisfy errors.Is(_, ErrWALRecycled); got: %v", scanErr) - } - var rf *storage.RecoveryFailure - if !errors.As(scanErr, &rf) { - t.Fatalf("smartwal ScanLBAs error must be *storage.RecoveryFailure via errors.As; got: %v", scanErr) - } - if rf.Kind != storage.StorageRecoveryFailureWALRecycled { - t.Errorf("Kind = %v, want StorageRecoveryFailureWALRecycled", rf.Kind) - } -} - -func TestStorageRecoveryFailureKind_Smartwal_CRCMismatchWrappedAsWALIntegrity(t *testing.T) { - dir := t.TempDir() - path := filepath.Join(dir, "smartwal-integrity.sw") - s, err := CreateStore(path, 16, 4096) - if err != nil { - t.Fatalf("CreateStore: %v", err) - } - for i := uint32(0); i < 3; i++ { - data := make([]byte, 4096) - data[0] = byte(0xA0 + i) - if _, werr := s.Write(i, data); werr != nil { - t.Fatal(werr) - } - } - if _, err := s.Sync(); err != nil { - t.Fatalf("Sync: %v", err) - } - if err := s.Close(); err != nil { - t.Fatalf("Close: %v", err) - } - - layout, rec, err := LatestRecord(path) - if err != nil { - t.Fatalf("LatestRecord: %v", err) - } - extentOffset := layout.ExtentStart + int64(rec.LBA)*int64(layout.BlockSize) - f, err := os.OpenFile(path, os.O_RDWR, 0) - if err != nil { - t.Fatalf("OpenFile: %v", err) - } - if _, err := f.WriteAt([]byte{0x5A}, extentOffset); err != nil { - _ = f.Close() - t.Fatalf("corrupt extent: %v", err) - } - if err := f.Close(); err != nil { - t.Fatalf("close corrupted file: %v", err) - } - - reopened, err := OpenStore(path) - if err != nil { - t.Fatalf("OpenStore: %v", err) - } - defer reopened.Close() - _, recoverErr := reopened.Recover() - if recoverErr == nil { - t.Fatal("expected WAL integrity failure after extent/WAL CRC mismatch") - } - if !errors.Is(recoverErr, storage.ErrWALIntegrityFault) { - t.Fatalf("Recover error must satisfy errors.Is(_, ErrWALIntegrityFault); got: %v", recoverErr) - } - var rf *storage.RecoveryFailure - if !errors.As(recoverErr, &rf) { - t.Fatalf("Recover error must be *storage.RecoveryFailure via errors.As; got: %v", recoverErr) - } - if rf.Kind != storage.StorageRecoveryFailureWALIntegrity { - t.Fatalf("Kind = %v, want StorageRecoveryFailureWALIntegrity", rf.Kind) - } -} - -// TestSmartwal_AppliedLSNs_ReportsRingEntries pins smartwal's -// AppliedLSNs (ring-based reduction). -func TestSmartwal_AppliedLSNs_ReportsRingEntries(t *testing.T) { - dir := t.TempDir() - path := filepath.Join(dir, "smartwal-applied.sw") - s, err := CreateStore(path, 16, 4096) - if err != nil { - t.Fatalf("CreateStore: %v", err) - } - defer s.Close() - - // Write 3 distinct LBAs. - for i := uint32(0); i < 3; i++ { - data := make([]byte, 4096) - data[0] = byte(i + 1) - if _, werr := s.Write(i, data); werr != nil { - t.Fatal(werr) - } - } - if _, err := s.Sync(); err != nil { - t.Fatalf("Sync: %v", err) - } - - got, err := s.AppliedLSNs() - if err != nil { - t.Fatalf("AppliedLSNs: %v", err) - } - if len(got) < 3 { - t.Errorf("AppliedLSNs returned %d entries, want >= 3", len(got)) - } - for i := uint32(0); i < 3; i++ { - if _, ok := got[i]; !ok { - t.Errorf("LBA %d missing from AppliedLSNs", i) - } - } -} diff --git a/seaweed-block/core/storage/smartwal/store.go b/seaweed-block/core/storage/smartwal/store.go deleted file mode 100644 index 096db66376..0000000000 --- a/seaweed-block/core/storage/smartwal/store.go +++ /dev/null @@ -1,568 +0,0 @@ -package smartwal - -import ( - "errors" - "fmt" - "hash/crc32" - "log" - "os" - "path/filepath" - "sync" - "sync/atomic" - "time" - - "github.com/seaweedfs/seaweed-block/core/geometry" - "github.com/seaweedfs/seaweed-block/core/storage" -) - -// defaultWALSlots: 65536 slots × 32 bytes = 2 MiB ring. Plenty for -// the experimental demo workload; production sizing would consider -// the working-set size and per-LBA overwrite frequency. -const defaultWALSlots = 65536 - -// Store is the SmartWAL implementation of core/storage.LogicalStorage. -// -// File layout (one preallocated file): -// -// [0 .. headerSize) 4KB header (magic, geometry) -// [headerSize .. extentBase) ring buffer (WALSlots × 32 bytes) -// [extentBase .. extentBase + numBlocks*BS) extent (block-indexed) -// -// Read path: pread directly from extent. The ring is not consulted -// for reads — by construction the extent is current truth. -// -// Write path: -// 1. read existing extent block (kept in memory for rollback) -// 2. pwrite new data to extent -// 3. compute dataCRC32 -// 4. append metadata record to ring (slot = LSN % capacity) -// 5. on append failure: rollback extent to saved old data -// -// Sync: one fsync of the file. Covers BOTH the extent pwrite and the -// ring append since they share a file. After Sync returns, all -// preceding writes' data + metadata are durable. -// -// Recovery: -// 1. scan ring, decode valid records, sort by LSN -// 2. compute last-writer-wins map (highest-LSN record per LBA) -// 3. for each surviving record, verify the extent block's CRC -// against the record's dataCRC32; mismatch → skip (torn write) -// 4. set nextLSN = highest valid LSN + 1 -// -// Concurrency: a single mutex guards bookkeeping (nextLSN, syncedLSN, -// counters); the ring has its own mutex for slot writes. Writes for -// 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 - ring *ring - committer *storage.GroupCommitter // batches concurrent Sync into one fsync - syncCache func() error - - extentBase int64 - - mu sync.RWMutex - closed bool - nextLSN uint64 // next LSN to assign - syncedLSN uint64 // highest LSN known durable on disk - walTail uint64 // exposed S boundary - walHead uint64 // exposed H boundary - - syncs atomic.Uint64 -} - -// CreateStore initializes a fresh smartwal store at path. Fails if -// path already exists. Use OpenStore for the recovery path. -func CreateStore(path string, numBlocks uint32, blockSize int) (*Store, error) { - return CreateStoreWithSlots(path, numBlocks, blockSize, defaultWALSlots) -} - -// CreateStoreWithSlots is CreateStore with an explicit ring capacity. -// Larger rings tolerate more writes between full flushes; smaller -// rings recycle slots faster. -func CreateStoreWithSlots(path string, numBlocks uint32, blockSize int, walSlots uint64) (*Store, error) { - if blockSize == 0 { - blockSize = storage.DefaultBlockSize - } - if err := geometry.ValidateBlockGeometry(uint64(numBlocks), uint64(blockSize)); err != nil { - return nil, err - } - if walSlots == 0 { - walSlots = defaultWALSlots - } - if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { - return nil, fmt.Errorf("smartwal: mkdir %s: %w", filepath.Dir(path), err) - } - f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0o644) - if err != nil { - return nil, fmt.Errorf("smartwal: create %s: %w", path, err) - } - hdr, err := newHeader(uint32(blockSize), numBlocks, walSlots) - if err != nil { - _ = f.Close() - return nil, err - } - hdr.CreatedAt = uint64(time.Now().UnixNano()) - - totalSize := int64(headerSize) + - int64(walSlots*recordSize) + - int64(numBlocks)*int64(blockSize) - if err := f.Truncate(totalSize); err != nil { - _ = f.Close() - return nil, fmt.Errorf("smartwal: preallocate %d bytes: %w", totalSize, err) - } - if _, err := f.Seek(0, 0); err != nil { - _ = f.Close() - return nil, fmt.Errorf("smartwal: seek to header: %w", err) - } - if err := hdr.writeTo(f); err != nil { - _ = f.Close() - return nil, err - } - if err := f.Sync(); err != nil { - _ = f.Close() - return nil, fmt.Errorf("smartwal: fsync after create: %w", err) - } - return openInitialized(path, f, &hdr) -} - -// OpenStore opens an existing store WITHOUT recovering it. Call -// Recover() before any Read/Write to rebuild the LSN counter and -// validate extent contents against the ring's metadata. -func OpenStore(path string) (*Store, error) { - f, err := os.OpenFile(path, os.O_RDWR, 0o644) - if err != nil { - return nil, fmt.Errorf("smartwal: open %s: %w", path, err) - } - if _, err := f.Seek(0, 0); err != nil { - _ = f.Close() - return nil, fmt.Errorf("smartwal: seek to header: %w", err) - } - hdr, err := readHeader(f) - if err != nil { - _ = f.Close() - return nil, err - } - if err := hdr.validate(); err != nil { - _ = f.Close() - return nil, err - } - return openInitialized(path, f, &hdr) -} - -func openInitialized(path string, f *os.File, hdr *header) (*Store, error) { - ringBase := int64(headerSize) - extentBase := ringBase + int64(hdr.WALSlots)*recordSize - r := newRing(f, ringBase, hdr.WALSlots) - s := &Store{ - path: path, - fd: f, - hdr: hdr, - ring: r, - extentBase: extentBase, - nextLSN: 1, - } - // Group committer batches concurrent Sync callers into one - // fsync — same pattern WALStore uses. Without this, SmartWAL - // scales poorly under concurrent durable writers because each - // caller's Sync() does its own fd.Sync(). - s.committer = storage.NewGroupCommitter(storage.GroupCommitterConfig{ - SyncFunc: func() error { return f.Sync() }, - MaxDelay: 1 * time.Millisecond, - MaxBatch: 64, - }) - s.syncCache = s.committer.SyncCache - go s.committer.Run() - return s, nil -} - -// 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, 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 - } - if frontier > s.syncedLSN { - s.syncedLSN = frontier - } - if frontier > s.walHead { - s.walHead = frontier - } - if s.walTail == 0 && frontier > 0 { - s.walTail = 1 - } - return s.syncedLSN, nil -} - -// Write writes one block to extent, then appends a metadata record. -// Failure-atomic: if the metadata append fails after the extent -// write, the extent is rolled back to its prior bytes so a later -// Sync cannot make untracked data durable. -func (s *Store) Write(lba uint32, data []byte) (uint64, error) { - if lba >= s.hdr.NumBlocks { - return 0, fmt.Errorf("smartwal: LBA %d out of range", lba) - } - if len(data) != int(s.hdr.BlockSize) { - return 0, fmt.Errorf("smartwal: data size %d != block size %d", len(data), s.hdr.BlockSize) - } - s.mu.Lock() - if s.closed { - s.mu.Unlock() - return 0, errors.New("smartwal: Write after Close") - } - lsn := s.nextLSN - if err := s.writeAt(lba, lsn, data, flagWrite); err != nil { - s.mu.Unlock() - return 0, err - } - s.nextLSN++ - s.bumpHeadLocked(lsn) - s.mu.Unlock() - return lsn, nil -} - -func (s *Store) WriteBatch(startLBA uint32, blocks [][]byte) ([]uint64, error) { - if len(blocks) == 0 { - return nil, nil - } - if uint64(startLBA)+uint64(len(blocks)) > uint64(s.hdr.NumBlocks) { - return nil, fmt.Errorf("smartwal: batch [%d,%d) out of range (max %d)", startLBA, uint64(startLBA)+uint64(len(blocks)), s.hdr.NumBlocks) - } - for i, data := range blocks { - if len(data) != int(s.hdr.BlockSize) { - return nil, fmt.Errorf("smartwal: batch block %d data size %d != block size %d", i, len(data), s.hdr.BlockSize) - } - } - s.mu.Lock() - if s.closed { - s.mu.Unlock() - return nil, errors.New("smartwal: WriteBatch after Close") - } - lsns := make([]uint64, 0, len(blocks)) - for i, data := range blocks { - lsn := s.nextLSN - if err := s.writeAt(startLBA+uint32(i), lsn, data, flagWrite); err != nil { - s.mu.Unlock() - return lsns, err - } - s.nextLSN++ - s.bumpHeadLocked(lsn) - lsns = append(lsns, lsn) - } - s.mu.Unlock() - return lsns, nil -} - -// writeAt is the shared write path used by Write and ApplyEntry. -// Saves prior extent bytes, writes new bytes, computes CRC, appends -// to ring, and rolls back on append failure. -func (s *Store) writeAt(lba uint32, lsn uint64, data []byte, flags uint8) error { - offset := s.extentBase + int64(lba)*int64(s.hdr.BlockSize) - - old := make([]byte, s.hdr.BlockSize) - if _, err := s.fd.ReadAt(old, offset); err != nil { - return fmt.Errorf("smartwal: read pre-write extent LBA %d: %w", lba, err) - } - if _, err := s.fd.WriteAt(data, offset); err != nil { - return fmt.Errorf("smartwal: write extent LBA %d: %w", lba, err) - } - rec := record{ - LSN: lsn, - LBA: lba, - Flags: flags, - DataCRC32: crc32.ChecksumIEEE(data), - } - if err := s.ring.appendAt(lsn, rec); err != nil { - // Rollback: restore prior extent bytes so an unsynced extent - // write cannot become "untracked durable" via a later Sync. - _, _ = s.fd.WriteAt(old, offset) - return fmt.Errorf("smartwal: ring append (extent rolled back): %w", err) - } - return nil -} - -// Read returns the current bytes at lba. SmartWAL reads always come -// from the extent — the ring is not consulted on the read path. -func (s *Store) Read(lba uint32) ([]byte, error) { - if lba >= s.hdr.NumBlocks { - return nil, fmt.Errorf("smartwal: LBA %d out of range", lba) - } - s.mu.RLock() - if s.closed { - s.mu.RUnlock() - return nil, errors.New("smartwal: Read after Close") - } - s.mu.RUnlock() - data := make([]byte, s.hdr.BlockSize) - off := s.extentBase + int64(lba)*int64(s.hdr.BlockSize) - if _, err := s.fd.ReadAt(data, off); err != nil { - return nil, fmt.Errorf("smartwal: read extent LBA %d: %w", lba, err) - } - return data, nil -} - -// Sync forces all in-flight writes to durable storage. One fsync -// covers both the extent pwrites and the ring appends because they -// share a file. -func (s *Store) Sync() (uint64, error) { - s.mu.RLock() - if s.closed { - s.mu.RUnlock() - return 0, errors.New("smartwal: Sync after Close") - } - targetHead := s.walHead - s.mu.RUnlock() - if err := s.syncCache(); err != nil { - return 0, fmt.Errorf("smartwal: group commit fsync: %w", err) - } - s.syncs.Add(1) - - s.mu.Lock() - if targetHead > s.syncedLSN { - s.syncedLSN = targetHead - } - frontier := s.syncedLSN - s.mu.Unlock() - return frontier, nil -} - -// Boundaries returns the live R/S/H boundaries. -func (s *Store) Boundaries() (R, S, H uint64) { - s.mu.RLock() - defer s.mu.RUnlock() - return s.syncedLSN, s.walTail, s.walHead -} - -// NextLSN returns the LSN that will be assigned to the next Write. -func (s *Store) NextLSN() uint64 { - s.mu.RLock() - defer s.mu.RUnlock() - return s.nextLSN -} - -// NumBlocks returns the addressable block count. -func (s *Store) NumBlocks() uint32 { return s.hdr.NumBlocks } - -// BlockSize returns the IO unit size in bytes. -func (s *Store) BlockSize() int { return int(s.hdr.BlockSize) } - -// AdvanceFrontier bumps the recorded frontier without writing data. -func (s *Store) AdvanceFrontier(lsn uint64) { - s.mu.Lock() - defer s.mu.Unlock() - if lsn >= s.nextLSN { - s.nextLSN = lsn + 1 - } - if lsn > s.walHead { - s.walHead = lsn - } -} - -// AdvanceWALTail moves the retained-window tail forward. -func (s *Store) AdvanceWALTail(newTail uint64) { - s.mu.Lock() - defer s.mu.Unlock() - if newTail > s.walTail { - s.walTail = newTail - } -} - -// WriteExtentDirect installs a base block directly into the extent -// without going through the WAL ring append path — INV-RECV-BITMAP- -// CORE (§6.10). The receiver's per-session bitmap is the sole arbiter -// of BASE-vs-WAL conflict at this LBA; substrate-level WAL replay / -// stale-skip is intentionally bypassed. -// -// No LSN is recorded; the ring is NOT touched. nextLSN / walHead are -// NOT advanced. The recovery layer pairs this with AdvanceFrontier -// (targetLSN) at MarkBaseComplete to keep post-rebuild frontier -// reporting honest. -// -// Durability follows the same rule as Write: bytes become durable -// only on the next successful Sync. -func (s *Store) WriteExtentDirect(lba uint32, data []byte) error { - if lba >= s.hdr.NumBlocks { - return fmt.Errorf("smartwal: WriteExtentDirect LBA %d out of range", lba) - } - if len(data) != int(s.hdr.BlockSize) { - return fmt.Errorf("smartwal: WriteExtentDirect data size %d != block size %d", len(data), s.hdr.BlockSize) - } - s.mu.RLock() - if s.closed { - s.mu.RUnlock() - return errors.New("smartwal: WriteExtentDirect after Close") - } - s.mu.RUnlock() - offset := s.extentBase + int64(lba)*int64(s.hdr.BlockSize) - if _, err := s.fd.WriteAt(data, offset); err != nil { - return fmt.Errorf("smartwal: WriteExtentDirect extent LBA %d: %w", lba, err) - } - return nil -} - -// ApplyEntry writes a replicated block with the source's LSN. -func (s *Store) ApplyEntry(lba uint32, data []byte, lsn uint64) error { - if lba >= s.hdr.NumBlocks { - return fmt.Errorf("smartwal: apply LBA %d out of range", lba) - } - if len(data) != int(s.hdr.BlockSize) { - return fmt.Errorf("smartwal: apply data size %d != block size %d", len(data), s.hdr.BlockSize) - } - s.mu.Lock() - defer s.mu.Unlock() - if err := s.writeAt(lba, lsn, data, flagWrite); err != nil { - return err - } - if lsn >= s.nextLSN { - s.nextLSN = lsn + 1 - } - s.bumpHeadLocked(lsn) - return nil -} - -// RecoveryMode reports smartwal's recovery sub-mode (T4d-4 part A; -// T4c §I row 6). smartwal's ScanLBAs emits per-LBA last-writer-wins -// with scan-time LSN — state-convergence semantics. -func (s *Store) RecoveryMode() storage.RecoveryMode { - return storage.RecoveryModeStateConvergence -} - -// AppliedLSNs returns per-LBA latest-applied-LSN derived from the -// ring's valid records. smartwal's ring is capacity-bounded: records -// older than (head - capacity) have been overwritten, so the returned -// map is "best-effort within retention" — LBAs whose latest write has -// rolled out of the ring are not reported. -// -// PARTIAL-VIEW NOTE (kickoff §2.5 #3 caveat): smartwal's ring -// retention is typically larger than walstore's WAL window, so this -// view is more complete than walstore's `AppliedLSNs()`. Still -// defense-in-depth — the apply gate (T4d-2) is the authoritative -// correctness boundary. -// -// Called by: T4d-2 replica recovery apply gate at session start. -// Owns: per-call snapshot from `ring.scanValid()` reduced per-LBA -// last-writer-wins. -// Borrows: nothing (returned map is fresh and caller-owned). -func (s *Store) AppliedLSNs() (map[uint32]uint64, error) { - records, err := s.ring.scanValid() - if err != nil { - return nil, fmt.Errorf("smartwal: AppliedLSNs ring scan: %w", err) - } - out := make(map[uint32]uint64, len(records)) - for _, rec := range records { - if existing, ok := out[rec.LBA]; !ok || rec.LSN > existing { - out[rec.LBA] = rec.LSN - } - } - return out, nil -} - -// AllBlocks snapshots every LBA's current bytes by reading directly -// from the extent. Linear scan — N reads — but in practice the -// rebuild server is the only caller and runs once per session. -func (s *Store) AllBlocks() (map[uint32][]byte, error) { - out := make(map[uint32][]byte, s.hdr.NumBlocks) - for lba := uint32(0); lba < s.hdr.NumBlocks; lba++ { - data, err := s.Read(lba) - if err != nil { - return nil, fmt.Errorf("snapshot LBA %d: %w", lba, err) - } - // Only include LBAs with non-zero content — preserves the - // "snapshot of dirty bits" semantics callers expect. - nonZero := false - for _, b := range data { - if b != 0 { - nonZero = true - break - } - } - if nonZero { - out[lba] = data - } - } - return out, nil -} - -// Close fsyncs and releases the file. Idempotent. -func (s *Store) Close() error { - s.mu.Lock() - if s.closed { - s.mu.Unlock() - return nil - } - s.closed = true - s.mu.Unlock() - if s.committer != nil { - s.committer.Stop() - } - if s.fd != nil { - _ = s.fd.Sync() - err := s.fd.Close() - s.fd = nil - return err - } - return nil -} - -// bumpHeadLocked advances the in-memory walHead boundary after a successful -// append. The caller holds s.mu so nextLSN and the visible head move together. -func (s *Store) bumpHeadLocked(lsn uint64) { - if lsn > s.walHead { - s.walHead = lsn - } - if s.walTail == 0 { - s.walTail = lsn - } -} - -// SyncCount returns the total number of fsync operations performed. -// Diagnostic only. -func (s *Store) SyncCount() uint64 { return s.syncs.Load() } - -// Compile-time assertion: Store satisfies the LogicalStorage contract. -var _ storage.LogicalStorage = (*Store)(nil) - -// StoreID returns the header UUID written when the store was created. -func (s *Store) StoreID() storage.StoreID { return storage.StoreID(s.hdr.UUID) } diff --git a/seaweed-block/core/storage/smartwal/store_test.go b/seaweed-block/core/storage/smartwal/store_test.go deleted file mode 100644 index 8e1422e071..0000000000 --- a/seaweed-block/core/storage/smartwal/store_test.go +++ /dev/null @@ -1,749 +0,0 @@ -package smartwal - -// Completion oracle: recover(a,b) band — NOT recover(a) closure. -// See sw-block/design/recover-semantics-adjustment-plan.md §8.1. - -import ( - "bytes" - "os" - "path/filepath" - "testing" - - "github.com/seaweedfs/seaweed-block/core/storage" -) - -// All the same contract assertions used in core/storage/contract_test.go -// — we duplicate the small subset here rather than depending on a -// test-helper export so this experimental subpackage stays -// self-contained and removable without touching the main storage -// package's public surface. - -func makeBlock(blockSize int, fillByte byte) []byte { - b := make([]byte, blockSize) - for i := range b { - b[i] = fillByte - } - return b -} - -func freshStore(t *testing.T) *Store { - t.Helper() - dir := t.TempDir() - path := filepath.Join(dir, "store.bin") - s, err := CreateStore(path, 16, 4096) - if err != nil { - t.Fatalf("CreateStore: %v", err) - } - t.Cleanup(func() { _ = s.Close() }) - return s -} - -func TestSmartWAL_FailedAppendDoesNotConsumeLSN(t *testing.T) { - s := freshStore(t) - bad, err := os.CreateTemp(t.TempDir(), "closed-ring") - if err != nil { - t.Fatal(err) - } - if err := bad.Close(); err != nil { - t.Fatal(err) - } - - s.ring.fd = bad - if _, err := s.Write(0, makeBlock(4096, 0xA1)); err == nil { - t.Fatal("Write with closed ring fd succeeded") - } - if got := s.NextLSN(); got != 1 { - t.Fatalf("NextLSN after failed append=%d want 1", got) - } - - s.ring.fd = s.fd - lsn, err := s.Write(0, makeBlock(4096, 0xA2)) - if err != nil { - t.Fatal(err) - } - if lsn != 1 { - t.Fatalf("successful Write LSN=%d want reused LSN 1", lsn) - } - - s.ring.fd = bad - lsns, err := s.WriteBatch(1, [][]byte{ - makeBlock(4096, 0xB1), - makeBlock(4096, 0xB2), - }) - if err == nil { - t.Fatal("WriteBatch with closed ring fd succeeded") - } - if len(lsns) != 0 { - t.Fatalf("failed batch returned LSNs=%v want none", lsns) - } - if got := s.NextLSN(); got != 2 { - t.Fatalf("NextLSN after failed batch=%d want 2", got) - } - - s.ring.fd = s.fd - lsns, err = s.WriteBatch(1, [][]byte{ - makeBlock(4096, 0xC1), - makeBlock(4096, 0xC2), - }) - if err != nil { - t.Fatal(err) - } - if len(lsns) != 2 || lsns[0] != 2 || lsns[1] != 3 { - t.Fatalf("successful batch LSNs=%v want [2 3]", lsns) - } -} - -func TestSmartWAL_SyncDoesNotClaimConcurrentWrite(t *testing.T) { - s := freshStore(t) - if lsn, err := s.Write(0, makeBlock(4096, 0xA1)); err != nil || lsn != 1 { - t.Fatalf("first Write lsn=%d err=%v", lsn, err) - } - - syncStarted := make(chan struct{}) - releaseSync := make(chan struct{}) - s.syncCache = func() error { - close(syncStarted) - <-releaseSync - return nil - } - type syncResult struct { - frontier uint64 - err error - } - result := make(chan syncResult, 1) - go func() { - frontier, syncErr := s.Sync() - result <- syncResult{frontier: frontier, err: syncErr} - }() - - <-syncStarted - if lsn, err := s.Write(1, makeBlock(4096, 0xA2)); err != nil || lsn != 2 { - t.Fatalf("concurrent Write lsn=%d err=%v", lsn, err) - } - close(releaseSync) - got := <-result - if got.err != nil { - t.Fatal(got.err) - } - if got.frontier != 1 { - t.Fatalf("Sync frontier=%d want captured frontier 1", got.frontier) - } - R, _, H := s.Boundaries() - if R != 1 || H != 2 { - t.Fatalf("boundaries R=%d H=%d want R=1 H=2", R, H) - } -} - -// --- LogicalStorage contract surface (the same shape as the main -// core/storage contract tests). --- - -func TestSmartWAL_SatisfiesLogicalStorageInterface(t *testing.T) { - // Compile-time check is in store.go; this is a runtime sanity that - // the type can be assigned to the interface. - var s storage.LogicalStorage = freshStore(t) - _ = s -} - -func TestSmartWAL_WriteReadRoundTrip(t *testing.T) { - s := freshStore(t) - want := makeBlock(s.BlockSize(), 0xAB) - lsn, err := s.Write(0, want) - if err != nil { - t.Fatal(err) - } - if lsn == 0 { - t.Fatal("Write returned LSN 0") - } - got, err := s.Read(0) - if err != nil { - t.Fatal(err) - } - if !bytes.Equal(got, want) { - t.Fatalf("Read returned wrong bytes") - } -} - -func TestSmartWAL_ReadUnwrittenLBAReturnsZeros(t *testing.T) { - s := freshStore(t) - got, err := s.Read(7) - if err != nil { - t.Fatal(err) - } - zero := make([]byte, s.BlockSize()) - if !bytes.Equal(got, zero) { - t.Fatal("unread LBA should be zeros") - } -} - -func TestSmartWAL_WriteAdvancesLSN(t *testing.T) { - s := freshStore(t) - var last uint64 - for i := uint32(0); i < 5; i++ { - lsn, err := s.Write(i, makeBlock(s.BlockSize(), byte(i))) - if err != nil { - t.Fatal(err) - } - if lsn <= last { - t.Fatalf("LSN did not advance: prev=%d got=%d", last, lsn) - } - last = lsn - } -} - -func TestSmartWAL_SyncReturnsHighestWritten(t *testing.T) { - s := freshStore(t) - var highest uint64 - for i := uint32(0); i < 3; i++ { - lsn, err := s.Write(i, makeBlock(s.BlockSize(), 1)) - if err != nil { - t.Fatal(err) - } - highest = lsn - } - synced, err := s.Sync() - if err != nil { - t.Fatal(err) - } - if synced != highest { - t.Fatalf("Sync returned %d, want %d", synced, highest) - } -} - -func TestSmartWAL_BoundariesReflectWrites(t *testing.T) { - s := freshStore(t) - R, S, H := s.Boundaries() - if R != 0 || S != 0 || H != 0 { - t.Fatalf("fresh: R=%d S=%d H=%d, all want 0", R, S, H) - } - _, _ = s.Write(0, makeBlock(s.BlockSize(), 1)) - _, _ = s.Sync() - R, _, H = s.Boundaries() - if R == 0 || H == 0 || R != H { - t.Fatalf("after sync of one write: R=%d H=%d, want R==H>0", R, H) - } -} - -func TestSmartWAL_ApplyEntryUsesSuppliedLSN(t *testing.T) { - s := freshStore(t) - want := makeBlock(s.BlockSize(), 0xCD) - if err := s.ApplyEntry(3, want, 100); err != nil { - t.Fatal(err) - } - got, err := s.Read(3) - if err != nil { - t.Fatal(err) - } - if !bytes.Equal(got, want) { - t.Fatal("ApplyEntry did not round-trip") - } - _, _, H := s.Boundaries() - if H != 100 { - t.Fatalf("ApplyEntry should bump H to supplied LSN, got %d", H) - } - next, err := s.Write(4, makeBlock(s.BlockSize(), 0xEF)) - if err != nil { - t.Fatal(err) - } - if next <= 100 { - t.Fatalf("Write after ApplyEntry must allocate beyond supplied LSN, got %d", next) - } -} - -func TestSmartWAL_AdvanceFrontierBumpsH(t *testing.T) { - s := freshStore(t) - s.AdvanceFrontier(50) - _, _, H := s.Boundaries() - if H != 50 { - t.Fatalf("AdvanceFrontier(50) should set H=50, got %d", H) - } - lsn, _ := s.Write(0, makeBlock(s.BlockSize(), 1)) - if lsn <= 50 { - t.Fatalf("Write after AdvanceFrontier(50): lsn=%d, want > 50", lsn) - } -} - -// TestSmartWAL_WriteExtentDirect — INV-RECV-BITMAP-CORE (§6.10). -// smartwal-specific contract pin: WriteExtentDirect writes to the -// extent without touching the ring (no LSN appended) and without -// advancing nextLSN / walHead. The recovery receiver pairs it with -// AdvanceFrontier(targetLSN) at MarkBaseComplete; this test asserts -// the substrate-side half of that contract. -func TestSmartWAL_WriteExtentDirect(t *testing.T) { - s := freshStore(t) - bs := s.BlockSize() - baseBytes := makeBlock(bs, 0xAA) - - // Pre-condition: fresh store, frontier zero. - _, _, h0 := s.Boundaries() - if h0 != 0 { - t.Fatalf("fresh smartwal H=%d want 0", h0) - } - if next := s.NextLSN(); next != 1 { - t.Fatalf("fresh smartwal nextLSN=%d want 1", next) - } - - // WriteExtentDirect succeeds and Read returns the bytes (smartwal - // reads always come from the extent — the ring is not consulted). - if err := s.WriteExtentDirect(3, baseBytes); err != nil { - t.Fatalf("WriteExtentDirect: %v", err) - } - got, err := s.Read(3) - if err != nil { - t.Fatalf("Read after WriteExtentDirect: %v", err) - } - if !bytes.Equal(got, baseBytes) { - t.Errorf("Read(3) returned %02x... want %02x...", got[:2], baseBytes[:2]) - } - - // Frontier MUST NOT have advanced — BASE has no LSN at this layer. - _, _, h1 := s.Boundaries() - if h1 != 0 { - t.Errorf("WriteExtentDirect advanced H to %d (must NOT touch frontier on smartwal)", h1) - } - if next := s.NextLSN(); next != 1 { - t.Errorf("WriteExtentDirect advanced nextLSN to %d (smartwal ring should be untouched)", next) - } - - // A subsequent ApplyEntry at LSN > 0 goes through the ring + writeAt - // path and shadows the BASE bytes — smartwal's reads always pull - // from the extent, and ApplyEntry's writeAt overwrites the same - // extent offset, so the WAL bytes win at the byte level. - walBytes := makeBlock(bs, 0xBB) - if err := s.ApplyEntry(3, walBytes, 5); err != nil { - t.Fatalf("ApplyEntry after WriteExtentDirect: %v", err) - } - got2, err := s.Read(3) - if err != nil { - t.Fatalf("Read after ApplyEntry: %v", err) - } - if !bytes.Equal(got2, walBytes) { - t.Errorf("Read(3) after ApplyEntry returned %02x... want %02x...", got2[:2], walBytes[:2]) - } - _, _, h2 := s.Boundaries() - if h2 < 5 { - t.Errorf("after ApplyEntry(lsn=5) H=%d want >= 5 (ApplyEntry's normal frontier side effect)", h2) - } - - // Bypass-vs-WAL ordering — running another WriteExtentDirect for - // the SAME LBA AFTER an ApplyEntry would naively overwrite the - // extent. The receiver's bitmap discipline (§6.10) prevents this - // at the application layer; but at the substrate layer, the call - // IS technically still allowed and observable (smartwal does not - // enforce arbitration — bitmap is the sole arbiter, by design). - // Pin that observation so a future "let's silently dedupe at - // substrate" change doesn't quietly subvert §6.10. - staleBase := makeBlock(bs, 0xCC) - if err := s.WriteExtentDirect(3, staleBase); err != nil { - t.Fatalf("WriteExtentDirect (post-ApplyEntry, substrate must allow): %v", err) - } - got3, _ := s.Read(3) - if !bytes.Equal(got3, staleBase) { - t.Errorf("substrate-level: WriteExtentDirect after ApplyEntry must overwrite (bitmap arbitration is at receiver layer); got %02x want %02x", got3[0], staleBase[0]) - } -} - -func TestSmartWAL_AdvanceWALTailMovesS(t *testing.T) { - s := freshStore(t) - _, _ = s.Write(0, makeBlock(s.BlockSize(), 1)) - s.AdvanceWALTail(20) - _, S, _ := s.Boundaries() - if S != 20 { - t.Fatalf("AdvanceWALTail(20): S=%d, want 20", S) - } - s.AdvanceWALTail(5) - _, S, _ = s.Boundaries() - if S != 20 { - t.Fatalf("AdvanceWALTail(5) after 20 must not regress: S=%d", S) - } -} - -func TestSmartWAL_CloseIdempotent(t *testing.T) { - s := freshStore(t) - if err := s.Close(); err != nil { - t.Fatal(err) - } - if err := s.Close(); err != nil { - t.Fatal(err) - } -} - -func TestSmartWAL_RecoverFreshReturnsZero(t *testing.T) { - s := freshStore(t) - r, err := s.Recover() - if err != nil { - t.Fatal(err) - } - if r != 0 { - t.Fatalf("fresh Recover: got %d, want 0", r) - } -} - -// --- SmartWAL-specific tests: persistence + crash consistency. --- - -func TestSmartWAL_WriteSyncCloseReopenRead(t *testing.T) { - dir := t.TempDir() - path := filepath.Join(dir, "store.bin") - - { - s, err := CreateStore(path, 16, 4096) - if err != nil { - t.Fatal(err) - } - for i := uint32(0); i < 4; i++ { - if _, err := s.Write(i, makeBlock(4096, byte(0xA0+i))); err != nil { - t.Fatal(err) - } - } - if _, err := s.Sync(); err != nil { - t.Fatal(err) - } - _ = s.Close() - } - { - s, err := OpenStore(path) - if err != nil { - t.Fatal(err) - } - defer s.Close() - if _, err := s.Recover(); err != nil { - t.Fatal(err) - } - for i := uint32(0); i < 4; i++ { - got, _ := s.Read(i) - want := makeBlock(4096, byte(0xA0+i)) - if !bytes.Equal(got, want) { - t.Fatalf("LBA %d: bytes did not survive close+reopen", i) - } - } - } -} - -// TestSmartWAL_AckedWritesSurviveSimulatedCrash mirrors the WALStore -// equivalent: drop the file handle without going through Close (no -// finalizing fsync in our path either, since Sync was the durability -// boundary). Acked blocks must come back; unacked may or may not but -// must not corrupt acked ones. -func TestSmartWAL_AckedWritesSurviveSimulatedCrash(t *testing.T) { - dir := t.TempDir() - path := filepath.Join(dir, "store.bin") - - func() { - s, err := CreateStore(path, 16, 4096) - if err != nil { - t.Fatal(err) - } - for i := uint32(0); i < 3; i++ { - if _, err := s.Write(i, makeBlock(4096, byte(0xA0+i))); err != nil { - t.Fatal(err) - } - } - // Acked: must survive. - if _, err := s.Sync(); err != nil { - t.Fatal(err) - } - // Unacked: may or may not survive. - for i := uint32(3); i < 5; i++ { - if _, err := s.Write(i, makeBlock(4096, byte(0xA0+i))); err != nil { - t.Fatal(err) - } - } - // Drop file handle without Close — no implicit fsync, no - // shutdown housekeeping. - _ = s.fd.Close() - }() - - s, err := OpenStore(path) - if err != nil { - t.Fatalf("OpenStore after simulated crash: %v", err) - } - defer s.Close() - if _, err := s.Recover(); err != nil { - t.Fatalf("Recover after simulated crash: %v", err) - } - - for i := uint32(0); i < 3; i++ { - got, err := s.Read(i) - if err != nil { - t.Fatal(err) - } - want := makeBlock(4096, byte(0xA0+i)) - if !bytes.Equal(got, want) { - t.Fatalf("LBA %d: ACKED data did not survive simulated crash; got[0]=%02x want[0]=%02x", - i, got[0], want[0]) - } - } - // Unacked: present-as-written or absent (zero); never a different - // LBA's data, never garbage. - for i := uint32(3); i < 5; i++ { - got, _ := s.Read(i) - want := makeBlock(4096, byte(0xA0+i)) - zero := make([]byte, 4096) - if !bytes.Equal(got, want) && !bytes.Equal(got, zero) { - t.Fatalf("LBA %d: post-Sync write recovered to neither write nor zero — corruption: got[0]=%02x", - i, got[0]) - } - } -} - -// TestSmartWAL_CrashFamily_AbruptKillAtMultipleWindows is the -// SmartWAL parallel of WALStore's crash family. SmartWAL's -// architecture has fewer "windows" than WALStore because it has no -// separate WAL→extent flush step (writes go directly to extent, one -// fsync per Sync covers both extent and metadata). The meaningful -// windows here are: -// -// - kill_pre_sync: writes returned but no Sync was called yet. -// Nothing required to survive. Reads of those LBAs return -// either the written bytes (if the extent write reached disk) -// or zeros (if it did not) — never garbage. -// - kill_post_sync: writes followed by a successful Sync, then -// immediate kill. Acked writes must survive. -// - kill_after_acked_then_unacked_overwrite: write A to LBA 0 + -// Sync; overwrite LBA 0 with B (no Sync); kill. The -// failure-atomicity claim is that LBA 0 reads either A or B — -// never garbage, never some other LBA's data, never a third -// value that was never written. -// -// "Abrupt kill" is simulated by dropping the file handle without -// going through Close — no implicit fsync, no housekeeping. -func TestSmartWAL_CrashFamily_AbruptKillAtMultipleWindows(t *testing.T) { - t.Run("kill_pre_sync", func(t *testing.T) { - dir := t.TempDir() - path := filepath.Join(dir, "store.bin") - - patterns := [][]byte{ - makeBlock(4096, 0xA0), - makeBlock(4096, 0xA1), - makeBlock(4096, 0xA2), - } - func() { - s, err := CreateStore(path, 16, 4096) - if err != nil { - t.Fatal(err) - } - for i, data := range patterns { - if _, err := s.Write(uint32(i), data); err != nil { - t.Fatal(err) - } - } - _ = s.fd.Close() // bypass Close — no fsync, no metadata persist - }() - - s, err := OpenStore(path) - if err != nil { - t.Fatal(err) - } - defer s.Close() - if _, err := s.Recover(); err != nil { - t.Fatal(err) - } - zero := make([]byte, 4096) - for i, want := range patterns { - got, err := s.Read(uint32(i)) - if err != nil { - t.Fatal(err) - } - if !bytes.Equal(got, want) && !bytes.Equal(got, zero) { - t.Fatalf("LBA %d after pre-Sync kill: got neither write nor zero — corruption: got[0]=%02x", - i, got[0]) - } - } - }) - - t.Run("kill_post_sync", func(t *testing.T) { - dir := t.TempDir() - path := filepath.Join(dir, "store.bin") - - patterns := [][]byte{ - makeBlock(4096, 0xB0), - makeBlock(4096, 0xB1), - makeBlock(4096, 0xB2), - } - func() { - s, err := CreateStore(path, 16, 4096) - if err != nil { - t.Fatal(err) - } - for i, data := range patterns { - if _, err := s.Write(uint32(i), data); err != nil { - t.Fatal(err) - } - } - if _, err := s.Sync(); err != nil { - t.Fatal(err) - } - _ = s.fd.Close() - }() - - s, err := OpenStore(path) - if err != nil { - t.Fatal(err) - } - defer s.Close() - if _, err := s.Recover(); err != nil { - t.Fatal(err) - } - for i, want := range patterns { - got, err := s.Read(uint32(i)) - if err != nil { - t.Fatal(err) - } - if !bytes.Equal(got, want) { - t.Fatalf("LBA %d ACKED bytes did not survive post-Sync kill: got[0]=%02x want[0]=%02x", - i, got[0], want[0]) - } - } - }) - - t.Run("kill_after_acked_then_unacked_overwrite", func(t *testing.T) { - dir := t.TempDir() - path := filepath.Join(dir, "store.bin") - - acked := makeBlock(4096, 0xCC) // pattern A — acked via Sync - overwrite := makeBlock(4096, 0xDD) // pattern B — written, never Sync'd - - func() { - s, err := CreateStore(path, 16, 4096) - if err != nil { - t.Fatal(err) - } - // Acked: A on LBA 0. - if _, err := s.Write(0, acked); err != nil { - t.Fatal(err) - } - if _, err := s.Sync(); err != nil { - t.Fatal(err) - } - // Unacked overwrite: B on LBA 0. Extent has B (atomic at - // 4KB-on-4KB-sector); metadata for LSN=2 may or may not - // have hit disk. - if _, err := s.Write(0, overwrite); err != nil { - t.Fatal(err) - } - _ = s.fd.Close() - }() - - s, err := OpenStore(path) - if err != nil { - t.Fatal(err) - } - defer s.Close() - if _, err := s.Recover(); err != nil { - t.Fatal(err) - } - got, err := s.Read(0) - if err != nil { - t.Fatal(err) - } - // Failure atomicity: read returns either the acked bytes or - // the unacked-overwrite bytes — never garbage, never another - // LBA's data, never a third value that was never written. - if !bytes.Equal(got, acked) && !bytes.Equal(got, overwrite) { - t.Fatalf("LBA 0 after acked+unacked-overwrite kill: got neither A nor B — corruption: got[0]=%02x acked[0]=%02x overwrite[0]=%02x", - got[0], acked[0], overwrite[0]) - } - // Other LBAs must remain zero (no cross-LBA contamination). - zero := make([]byte, 4096) - for i := uint32(1); i < 4; i++ { - other, _ := s.Read(i) - if !bytes.Equal(other, zero) { - t.Fatalf("LBA %d should be untouched, got non-zero bytes: got[0]=%02x", - i, other[0]) - } - } - }) -} - -// TestSmartWAL_RecoverIsIdempotent: calling Recover twice on the -// same on-disk state yields identical results. -func TestSmartWAL_RecoverIsIdempotent(t *testing.T) { - dir := t.TempDir() - path := filepath.Join(dir, "store.bin") - - { - s, err := CreateStore(path, 8, 4096) - if err != nil { - t.Fatal(err) - } - for i := uint32(0); i < 3; i++ { - _, _ = s.Write(i, makeBlock(4096, byte(i+1))) - } - _, _ = s.Sync() - _ = s.Close() - } - s, err := OpenStore(path) - if err != nil { - t.Fatal(err) - } - defer s.Close() - r1, _ := s.Recover() - r2, _ := s.Recover() - if r1 != r2 { - t.Fatalf("Recover not idempotent: r1=%d r2=%d", r1, r2) - } -} - -// TestSmartWAL_OpenRejectsBadMagic. -func TestSmartWAL_OpenRejectsBadMagic(t *testing.T) { - dir := t.TempDir() - path := filepath.Join(dir, "bogus.bin") - if err := os.WriteFile(path, []byte("not_a_smartwal_store"), 0o644); err != nil { - t.Fatal(err) - } - _, err := OpenStore(path) - if err == nil { - t.Fatal("OpenStore on bogus file must error") - } -} - -// TestSmartWAL_RingWrapPreservesLatestPerLBA: with a tiny ring (4 -// slots), write 12 distinct LBAs once each. The ring overwrites the -// oldest 8 records, leaving 4. Recovery sees only 4 records but -// extent has all 12 blocks. Verified extents match those 4 records; -// the other 8 LBAs read as whatever extent has (which IS the data -// we wrote, but the metadata is gone). This proves the design's -// "metadata is bounded by ring size, but extent retains all data" -// property. -func TestSmartWAL_RingWrapPreservesLatestPerLBA(t *testing.T) { - dir := t.TempDir() - path := filepath.Join(dir, "store.bin") - - const ringSlots = 4 - { - s, err := CreateStoreWithSlots(path, 32, 4096, ringSlots) - if err != nil { - t.Fatal(err) - } - for i := uint32(0); i < 12; i++ { - if _, err := s.Write(i, makeBlock(4096, byte(0x10+i))); err != nil { - t.Fatal(err) - } - } - if _, err := s.Sync(); err != nil { - t.Fatal(err) - } - _ = s.Close() - } - - s, err := OpenStore(path) - if err != nil { - t.Fatal(err) - } - defer s.Close() - frontier, err := s.Recover() - if err != nil { - t.Fatal(err) - } - if frontier == 0 { - t.Fatal("Recover should report a non-zero frontier from the ring") - } - // Every LBA's extent bytes should match what we wrote, regardless - // of whether its metadata record survived ring overwrite. - for i := uint32(0); i < 12; i++ { - got, _ := s.Read(i) - want := makeBlock(4096, byte(0x10+i)) - if !bytes.Equal(got, want) { - t.Fatalf("LBA %d extent contents lost", i) - } - } -} diff --git a/seaweed-block/core/storage/smartwal/superblock.go b/seaweed-block/core/storage/smartwal/superblock.go deleted file mode 100644 index 9e210f089c..0000000000 --- a/seaweed-block/core/storage/smartwal/superblock.go +++ /dev/null @@ -1,162 +0,0 @@ -package smartwal - -import ( - "crypto/rand" - "encoding/binary" - "errors" - "fmt" - "io" -) - -// File-format identity. Distinct from the WALStore magic so the two -// backends can never accidentally open each other's files. -// -// Version history: -// 1: initial layout. -// 2: T3a Addendum A — added ImplKind + ImplVersion so the -// DurableProvider can self-identify this as a smartwal file -// via a uniform field shape parallel to walstore's superblock. -// Opening a v1 file with v2 code returns errBadVersion -// (one-way bump; no compat read path). -const ( - headerSize = 4096 - headerMagic = "SWAW" // SmartWAL: "SW" + AW - headerVersion = 2 -) - -// implKindSmartWAL matches core/storage.ImplKindSmartWAL (=2). -// Duplicated as a raw byte constant here to avoid a reverse -// import; the shared wire value is documented in storage.ImplKind. -const implKindSmartWAL uint8 = 2 - -// smartwalImplVersion is this package's per-impl schema version. -// Independent from headerVersion (superblock-format version). -const smartwalImplVersion uint32 = 1 - -var ( - errBadMagic = errors.New("smartwal: not a smartwal store (bad magic)") - errBadVersion = errors.New("smartwal: unsupported version") - errBadGeometry = errors.New("smartwal: invalid geometry") - errBadImpl = errors.New("smartwal: wrong impl kind on disk") -) - -// header is the 4KB preamble of a smartwal store file. It records -// geometry only — no recovery state, no checkpoint LSN. Recovery -// works by rescanning the ring on every Open, so the only on-disk -// invariant the header must preserve is the file layout. -type header struct { - Magic [4]byte - Version uint16 - Flags uint16 - UUID [16]byte - BlockSize uint32 // bytes per addressable block - NumBlocks uint32 // total addressable blocks - WALSlots uint64 // number of 32-byte slots in the ring - CreatedAt uint64 // unix nanoseconds - // T3a Addendum A — impl self-identity (parallel to walstore's - // superblock ImplKind + ImplVersion fields). Always set to - // implKindSmartWAL + smartwalImplVersion on new files. - ImplKind uint8 - ImplVersion uint32 -} - -func newHeader(blockSize uint32, numBlocks uint32, walSlots uint64) (header, error) { - h := header{ - Version: headerVersion, - BlockSize: blockSize, - NumBlocks: numBlocks, - WALSlots: walSlots, - ImplKind: implKindSmartWAL, - ImplVersion: smartwalImplVersion, - } - copy(h.Magic[:], headerMagic) - if _, err := rand.Read(h.UUID[:]); err != nil { - return header{}, fmt.Errorf("smartwal: header UUID: %w", err) - } - return h, nil -} - -func (h *header) writeTo(w io.Writer) error { - buf := make([]byte, headerSize) - off := 0 - off += copy(buf[off:], h.Magic[:]) - binary.LittleEndian.PutUint16(buf[off:], h.Version) - off += 2 - binary.LittleEndian.PutUint16(buf[off:], h.Flags) - off += 2 - off += copy(buf[off:], h.UUID[:]) - binary.LittleEndian.PutUint32(buf[off:], h.BlockSize) - off += 4 - binary.LittleEndian.PutUint32(buf[off:], h.NumBlocks) - off += 4 - binary.LittleEndian.PutUint64(buf[off:], h.WALSlots) - off += 8 - binary.LittleEndian.PutUint64(buf[off:], h.CreatedAt) - off += 8 - // T3a Addendum A — ImplKind + ImplVersion. - buf[off] = h.ImplKind - off++ - off += 3 // reserved for future kind expansion / alignment - binary.LittleEndian.PutUint32(buf[off:], h.ImplVersion) - if _, err := w.Write(buf); err != nil { - return fmt.Errorf("smartwal: write header: %w", err) - } - return nil -} - -func readHeader(r io.Reader) (header, error) { - buf := make([]byte, headerSize) - if _, err := io.ReadFull(r, buf); err != nil { - return header{}, fmt.Errorf("smartwal: read header: %w", err) - } - var h header - off := 0 - copy(h.Magic[:], buf[off:off+4]) - off += 4 - if string(h.Magic[:]) != headerMagic { - return header{}, errBadMagic - } - h.Version = binary.LittleEndian.Uint16(buf[off:]) - off += 2 - if h.Version != headerVersion { - return header{}, fmt.Errorf("%w: got %d, want %d", errBadVersion, h.Version, headerVersion) - } - h.Flags = binary.LittleEndian.Uint16(buf[off:]) - off += 2 - copy(h.UUID[:], buf[off:off+16]) - off += 16 - h.BlockSize = binary.LittleEndian.Uint32(buf[off:]) - off += 4 - h.NumBlocks = binary.LittleEndian.Uint32(buf[off:]) - off += 4 - h.WALSlots = binary.LittleEndian.Uint64(buf[off:]) - off += 8 - h.CreatedAt = binary.LittleEndian.Uint64(buf[off:]) - off += 8 - // T3a Addendum A — ImplKind + ImplVersion. - h.ImplKind = buf[off] - off++ - off += 3 // reserved - h.ImplVersion = binary.LittleEndian.Uint32(buf[off:]) - return h, nil -} - -func (h *header) validate() error { - if string(h.Magic[:]) != headerMagic { - return errBadMagic - } - if h.BlockSize == 0 { - return fmt.Errorf("%w: BlockSize=0", errBadGeometry) - } - if h.NumBlocks == 0 { - return fmt.Errorf("%w: NumBlocks=0", errBadGeometry) - } - if h.WALSlots == 0 { - return fmt.Errorf("%w: WALSlots=0", errBadGeometry) - } - // T3a Addendum A — ImplKind must match smartwal. - if h.ImplKind != implKindSmartWAL { - return fmt.Errorf("%w: got %d, want %d", errBadImpl, h.ImplKind, implKindSmartWAL) - } - return nil -} diff --git a/seaweed-block/core/storage/smartwal/volume_size_limit_test.go b/seaweed-block/core/storage/smartwal/volume_size_limit_test.go deleted file mode 100644 index 406ecb4710..0000000000 --- a/seaweed-block/core/storage/smartwal/volume_size_limit_test.go +++ /dev/null @@ -1,23 +0,0 @@ -package smartwal - -import ( - "os" - "path/filepath" - "strings" - "testing" -) - -func TestCreateCapacityBeforeFilesystem(t *testing.T) { - parent := filepath.Join(t.TempDir(), "file") - if err := os.WriteFile(parent, []byte("unchanged"), 0600); err != nil { - t.Fatal(err) - } - s, err := CreateStore(filepath.Join(parent, "volume"), ^uint32(0), 8192) - if s != nil { - s.Close() - t.Fatal("created oversized image") - } - if err == nil || !strings.Contains(err.Error(), "16 TiB - 4 KiB") { - t.Fatalf("capacity must precede filesystem: %v", err) - } -} diff --git a/seaweed-block/deploy/config/blockvolume.env b/seaweed-block/deploy/config/blockvolume.env index 45d8419b41..66e5475a80 100644 --- a/seaweed-block/deploy/config/blockvolume.env +++ b/seaweed-block/deploy/config/blockvolume.env @@ -41,8 +41,8 @@ SWB_DURABLE_ROOT=/var/lib/sw-block-volume/volumes # --durable-impl (default empty: auto). Auto creates a new volume as walstore, # opens an existing one with its on-disk format, and refuses a walstore-chunk # root. Explicit values: walstore; walstore-chunk (walstore published to -# SeaweedFS, proof of concept); smartwal (experimental). This example pins -# walstore. +# SeaweedFS, proof of concept). The removed experimental engines (smartwal, +# parallel-walstore) are refused. This example pins walstore. SWB_DURABLE_IMPL=walstore # --durable-blocks (default 2048), --durable-blocksize (default 4096). Volume # geometry on first create; ignored when an existing volume is opened. diff --git a/seaweed-block/docs/assets/smartwal-layout.svg b/seaweed-block/docs/assets/smartwal-layout.svg deleted file mode 100644 index 65abf6b8f6..0000000000 --- a/seaweed-block/docs/assets/smartwal-layout.svg +++ /dev/null @@ -1,93 +0,0 @@ - - smartwal (experimental) layout: data written in place in the extent, plus a ring of 32-byte metadata records indexed by LSN modulo capacity - - - - - - - - - - - - smartwal · in-place data plus a metadata record ring - - EXPERIMENTAL - Not a default and no chunk snapshots · core/storage/smartwal/store.go (Store), record.go, ring.go, recovery.go - - - File regions (not to scale) - - header - 4 KiB · offset 0 - - record ring - slots × 32 bytes (65,536 slots = 2 MiB default) - - extent: the data, written in place - numBlocks × BlockSize · reads always come from here - - - - One ring slot: a 32-byte record (record.go encode) - - - - - - - - - mg - fl - rsv - LBA u32 - LSN u64 - reserved2 (zero) - dataCRC32 - recCRC32 - 0 - 1 - 2 - 4 - 8 - 16 - 24 - 28 - 32 - mg = magic 0xAC (anything else is an empty slot) · fl = flags (write 0x01, trim 0x02, barrier 0x04) · rsv = reserved · little-endian - dataCRC32 = CRC32 of the data block in the extent · recCRC32 = CRC32 of bytes 0..27 · slot index = LSN mod capacity (ring.go appendAt) - - - Write order (Store.writeAt) and Sync - - 1 · read the old block - kept in memory for rollback - - 2 · pwrite data in place - the extent slot of the LBA - - 3 · append the record - slot = LSN mod capacity; on failure - the old block is written back - - 4 · Sync: one fsync - covers data and record together - (same file) - - - - - - - - Known crash window between 2 and 3 - extent newer than the ring: CRC check fails, volume does not open - - - - Recovery (runRecoveryCounting): - scan every slot (a bad recCRC is skipped and counted as a warning) → highest LSN per LBA → - check the extent block against dataCRC32; a mismatch fails closed as a WAL integrity failure → frontier = highest verified LSN - diff --git a/seaweed-block/docs/design/block-design.md b/seaweed-block/docs/design/block-design.md index b3bdb53766..41232862de 100644 --- a/seaweed-block/docs/design/block-design.md +++ b/seaweed-block/docs/design/block-design.md @@ -6,7 +6,7 @@ The design is split into three documents: this shared core and one document per | Document | Covers | |---|---| -| Core design (this document) | **Part 1**, the core block service: frontends and the Backend contract, walstore, smartwal (experimental), durability and `Sync`, the authority model, the replication engine, recovery. **Part 2**, verification, lessons and known issues across the codebase. | +| Core design (this document) | **Part 1**, the core block service: frontends and the Backend contract, walstore, the removed experimental engines, durability and `Sync`, the authority model, the replication engine, recovery. **Part 2**, verification, lessons and known issues across the codebase. | | [Agent workspace design](agent-workspace-design.md) | Agent workspace disks (proof of concept): a frontend, local walstore and a SeaweedFS chunk backend; one replica per workspace with durability from snapshots; the cut, the two-level manifest, snapshots, forks, GC, leases and host moves; the security model. | | [Kubernetes block design](kubernetes-block-design.md) | Kubernetes block volumes (alpha): the CSI driver, Helm and the operator controllers, RF=2/3 replication and failover from the product view, iSCSI ALUA, multipath and NVMe/TCP ANA, authority promotion, readiness, the operation layer. | @@ -19,7 +19,7 @@ The state machines and the invariant ledger of all three documents, with the rul - [Part 1. Core block service](#part-1-core-block-service) - [1.1 Frontends and the Backend contract](#11-frontends-and-the-backend-contract) - [1.2 walstore: WAL plus extent](#12-walstore-wal-plus-extent) - - [1.3 smartwal: in-place writes plus a metadata ring](#13-smartwal-in-place-writes-plus-a-metadata-ring) + - [1.3 Removed experimental engines](#13-removed-experimental-engines) - [1.4 Durability and Sync](#14-durability-and-sync) - [1.5 Authority: blockmaster, assignments, epochs, leases](#15-authority-blockmaster-assignments-epochs-leases) - [1.6 Replication and failover](#16-replication-and-failover) @@ -40,7 +40,7 @@ flowchart TD subgraph BV["blockvolume (one process per volume replica)"] FE["frontend: NVMe/TCP, iSCSI, ublk"] --> BE["frontend.Backend: Read / Write / Sync / Close"] BE --> SA["durable.StorageBackend: per-I/O lineage gate"] - SA --> LS["storage.LogicalStorage: walstore or smartwal"] + SA --> LS["storage.LogicalStorage: walstore"] SA --> RV["replication.ReplicationVolume (RF > 1)"] RV -->|"ship by LSN, barrier"| R1["replica blockvolume"] end @@ -185,177 +185,12 @@ stateDiagram-v2 - Torn-wrap loss: the in-memory tail moved before the superblock tail was persisted, so a wrapped write could overwrite bytes the disk still declared retained; a torn record there hid later synced records. Found by model checking, reproduced in code, fixed by #159; `TestWALStoreAppendDuringFlushThenTornWrapKeepsSyncedRecords`. - Physical-order replay: after a wrap, an older version of an LBA could be replayed over a newer one. Fixed by #156; `TestWALStoreRecoverLastWriterWinsAcrossScanOrder`. -## 1.3 smartwal: in-place writes plus a metadata ring +## 1.3 Removed experimental engines -**Status: experimental.** It shows that `LogicalStorage` admits more than one implementation. It is not a default: `blockvolume --durable-impl` defaults to auto, which creates new volumes as walstore and opens an existing volume with its on-disk format, so smartwal is used only when chosen explicitly or found on disk. Auto refuses a root that carries chunk metadata (a `walstore-chunk` volume) instead of opening it as plain walstore; such a volume needs `--durable-impl=walstore-chunk` with its remote configuration (`core/frontend/durable/provider.go` `openOrCreate`). Open issues: - -- in-place overwrites have no rollback on a torn write (see the crash window in Open items); -- a block loses its per-block CRC once its ring record recycles; -- the handling of a corrupted committed record is still open; -- it does not support the chunk layer, so it has no snapshots, forks or host moves. - -**Layout.** A 4 KB header, a ring of 32-byte records, and the extent (`core/storage/smartwal/store.go`). A record holds magic, flags, LBA, LSN, the CRC32 of the 4 KB data block, and a record CRC (`core/storage/smartwal/record.go`). Slot = LSN mod capacity (`ring.go` `appendAt`). - -

- smartwal file: a 4 KiB header, a ring of 32-byte records and the extent; the byte layout of one record; the write order read old block, write in place, append record, Sync; the crash window between the in-place write and the append; recovery -

- -Numbers in the figure: the header is 4096 bytes (`smartwal/superblock.go` `headerSize`); a record is 32 bytes with the byte offsets of `record.go` `encode` (magic 0xAC; flags write 0x01, trim 0x02, barrier 0x04); the default ring has 65,536 slots, 2 MiB (`store.go` `defaultWALSlots`). On a data CRC mismatch, recovery fails closed (`recovery.go` `runRecoveryCounting`); the comment on the `Store` type still says such a record is skipped, which the code no longer does. - -**Write, read, Sync.** `Store.writeAt` reads the old block (kept for rollback), writes the new data in place, then appends the record; if the append fails, the old block is written back. Reads always come from the extent. `Sync` is one `fsync` of the file. - -**Recovery.** `runRecoveryCounting` (`core/storage/smartwal/recovery.go`): scan slots (record-CRC failures are skipped and counted as a warning), keep the highest-LSN record per LBA, check the extent block against its data CRC, and fail closed with a WAL integrity failure (`NewWALIntegrityFailure`) on a mismatch. The frontier is the highest verified LSN. - -```mermaid -stateDiagram-v2 - [*] --> OldData: block holds the previous version - OldData --> DataWritten: pwrite new data in place - DataWritten --> Recorded: append 32-byte record - DataWritten --> OldData: append failed, rollback - Recorded --> Durable: Sync (one fsync) - DataWritten --> Unopenable: crash here, extent newer than ring (known issue) -``` - -**Invariants and known gaps.** - -| Item | Where | Test | -|---|---|---| -| Recovery picks the highest LSN per LBA and verifies the extent CRC | `recovery.go` `runRecoveryCounting` | `TestStorageRecoveryFailureKind_Smartwal_CRCMismatchWrappedAsWALIntegrity` (`core/storage/smartwal/smartwal_typed_failure_test.go`) | -| A failed append does not consume an LSN | `store.go` `writeAt` | `TestSmartWAL_FailedAppendDoesNotConsumeLSN` (`core/storage/smartwal/store_test.go`) | -| Known gap: a crash after the in-place write and before the ring append (or a power cut that writes back the data page but not the ring page) leaves the volume unopenable; an unacknowledged write makes acknowledged data unavailable | `store.go` `writeAt` order; `recovery.go` CRC check | not covered; in progress | -| Known gap: no per-block CRC once a slot is recycled, so later extent corruption is undetected | design | — | -| Known gap: writes to the same LBA from different goroutines are not ordered at this layer | `store.go` type comment | — | - -**Review directions.** Any fix must define the order between the record and the data and say how a torn pair is classified (torn and unsynced, versus corrupted and synced). A synced watermark persisted outside the ring is the planned way to tell them apart. - -**Lessons.** #51 (open): a CRC-failed committed record is skipped and the volume reports ready. #155 made this visible as a warning; the fix needs the format change described in Part 2. - -## 1.4 Durability and Sync - -- **One durability point.** A write is durable only when a `Sync` covering its LSN returns nil. `Sync` returns the durable frontier. -- **Group commit.** Concurrent `Sync` callers share one `fsync`. The committer waits up to `MaxDelay` (1 ms) or until 64 waiters are queued (`core/storage/group_commit.go` `NewGroupCommitter`, `Run`). -- **Deduplication.** A sync that started after the last mutation covers later `Sync` requests with no new writes (`walstore.go` `walSyncCovered`). -- **A failed `fsync` is sticky.** The first failed `fsync` of the store's file (WAL, extent or superblock), or a failed WAL append, latches a typed `io_error` fault; the open store then refuses every later `Sync`, write and checkpoint until it is reopened and recovered (`walstore.go` `noteFsyncFailure`, `noteAppendFailure`, `syncFile`, `stickyIOFault`). Every `fsync` of the file is serialized with that latch, so no publication can pass the check and complete after another path's `fsync` failed (#172). -- **With replication.** `ReplicationVolume.Sync` queues a barrier behind every shipped write, runs the local `fsync` in parallel, and applies the volume's durability mode (§1.6). -- **Observability.** Per-stage power-of-two histograms (frontend receive, WAL append, group-commit wait, physical sync, return) are exposed under `/status/durable` (`docs/fsync-latency.md`). - -**Review directions.** -- `fsync` failure semantics: after a failed `fsync`, the kernel may have dropped the dirty pages, so a later successful `fsync` proves nothing about them. Any new path that `fsync`s the store's file must go through `syncFile`, so the fault latches. -- Do not add a stage's p99 to another's; the populations differ. - -## 1.5 Authority: blockmaster, assignments, epochs, leases - -**Algorithm.** -- blockmaster is the only component that mints epochs. A reassignment takes the maximum epoch published for the volume plus one (`core/authority/authority.go` `applyWithWorkspaceMove`, `IntentReassign` case). A workspace move reserves its epoch the same way and journals the move before the epoch is published (`core/authority/workspace.go` `prepareWorkspaceMoveLocked`). -- If a durable authority write fails, the publisher marks the volume uncertain and refuses further writes for it, so a later write cannot go backwards (`workspace.go` `persistWorkspaceLocked`). -- blockvolume never elects itself; it serves under the assignment it was given, and every I/O re-checks that assignment (§1.1). -- Workspace volumes add a lease ([agent workspace design §7](agent-workspace-design.md#7-lease-takeover-and-host-moves)). - -```mermaid -stateDiagram-v2 - [*] --> Unbound - Unbound --> Bound: IntentBind (epoch 1) - Bound --> Bound: same assignment republished - Bound --> Bound: IntentRefreshEndpoint (endpoint version + 1), only on the line it was decided against - Bound --> Reassigned: IntentReassign (max epoch + 1) - Reassigned --> Bound: new primary serves at the new epoch - Bound --> Deleting: deletion reservation (id never reused) - Deleting --> [*] -``` - -**Invariants.** - -| Invariant | Enforced in | Test | Model-checked | -|---|---|---|---| -| Epochs per volume are minted only by blockmaster and strictly increase | `authority.go`; `workspace.go` | `TestWorkspaceClockSkewPersistsAndProtectsRestart` (`core/authority/workspace_skew_test.go`) | yes | -| A failed or uncertain authority write never lets the epoch go backwards | `workspace.go` `persistWorkspaceLocked` | covered by the authority store tests | yes (removing the guard produces a counterexample) | -| Each move request id gets exactly one epoch | `workspace.go` `MoveWorkspace`, `sameWorkspaceRequest` | `TestWorkspaceForcedMoveRequiresExplicitForceAndLeaseExpiry` (`core/authority/workspace_test.go`) | yes | -| A deleted volume id is never created again | `core/host/master/services.go` (deletion reservations) | `TestMarkVolumeDeleting_ReservesUnknownIdsAndSurvivesDeleteAndRestart` (`core/host/master/volume_deleting_test.go`) | yes | - -**Review directions.** Any new way to publish an assignment must go through the publisher's epoch rule; nothing else may construct an epoch. The control plane has no authentication today (see Known issues), so every destructive RPC is reachable by anyone who can reach the port. - -## 1.6 Replication and failover - -This section is the replication engine as a core component. Kubernetes volumes use it when their StorageClass sets `replicationFactor` to 2 or 3 (the default is 1); agent workspaces do not use it (they run RF=1). The product view (StorageClass and Helm settings, failure detection, the promotion gate, multipath, readiness) is in the [Kubernetes block design](kubernetes-block-design.md). - -**Shipping.** The primary writes locally first, then ships each write to every replica in LSN order (`core/replication/volume.go` `OnLocalWrite`), through a per-peer FIFO. - -**Durable acknowledgement.** `ReplicationVolume.Sync` enqueues a barrier for the target LSN on every peer queue, runs the local `fsync` in parallel, and judges the result by mode (`core/replication/durability.go`): -- `best_effort`: the local `fsync` is enough; a failed peer barrier degrades that peer; -- `sync_quorum`: a majority of nodes (primary plus replicas) are durable; -- `sync_all`: every replica is durable. - -**Replica fencing.** The replica listener persists its epoch floor before acting on a higher epoch (`core/transport/replica.go` `raiseFloor`; `floor.go`). It refuses frames below the floor, frames that arrive while it is primary, and frames before its role is known (`acceptMutationLineage`, `EnterDualLane`). A failed `ApplyEntry` closes the connection, so no barrier can acknowledge past the gap. Replication listeners open only when the assignment has replica slots (`cmd/blockvolume/replication_ingress.go`). - -**Catch-up and rebuild.** The engine decides per peer (`core/engine/state.go` `RecoveryDecision`): -- **catch-up** when the gap is still in the primary's WAL: replay WAL entries; -- **rebuild** when it is not: a dual-lane session copies the base image while also feeding live WAL entries, and the receiver arbitrates per LBA with a bitmap ("WAL has won base") (`core/recovery/doc.go`). While a rebuild is active, the primary's checkpoint is clamped to the session's pin floor so the WAL it needs is retained (`walstore.go` `persistCheckpointReleasing`). - -**Promotion.** A replica is promotion-ready only if it is a member, reachable, caught up, has completed its fence at the current epoch, and has delivered the post-rebuild durable acknowledgement (`core/engine/promotion_ready.go` `BuildPromotionReadyFact`). - -```mermaid -stateDiagram-v2 - [*] --> Unknown - Unknown --> Healthy: probe, then a barrier whose (last data epoch, end) the primary's epoch table finds in sync - Healthy --> Degraded: barrier or ship failure - Healthy --> NeedsRebuild: seed barrier finds diverged history (another epoch at the same LSNs, or a tail above the frontier), via Degraded - Degraded --> CatchingUp: gap within the primary's WAL - CatchingUp --> CatchingUp: identical recovery facts retain the prepared session - CatchingUp --> CatchingUp: active session refuses promotion readiness - Healthy --> Healthy: delayed probe retains completed durable R - Healthy --> Healthy: completed recovery certifies P, prune version suffix - CatchingUp --> Healthy: caught up to the target and reconciled in sync by (epoch, LSN) - CatchingUp --> Degraded: catch-up fails - Degraded --> Healthy: recovers and reconciles in sync by (epoch, LSN), never by length - Degraded --> NeedsRebuild: a heal's reconciliation finds diverged history - Degraded --> NeedsRebuild: gap beyond WAL retention or retries exhausted - CatchingUp --> NeedsRebuild: WAL recycled - NeedsRebuild --> [*]: terminal for this peer -``` - -(Peer states and allowed transitions are in `core/replication/peer.go` `ReplicaState`, `replicaStateTransitionAllowed`. Every route to `Healthy` from a recovery verdict goes through `ReplicaPeer.HealIfInSync`: a barrier in this session whose (last data epoch, end) the primary's epoch table (`core/transport/epoch_table.go`, `SharedEnd`) finds in sync; diverged history goes to `NeedsRebuild` and is never counted. `NeedsRebuild` is terminal in this state machine; the rebuild itself runs as a separate dual-lane session, and the Kubernetes line drives it through an opt-in operator path, see the [Kubernetes block design](kubernetes-block-design.md#4-replication-and-failover).) - -**Epoch table** (`core/transport/epoch_table.go`): each volume's durable record of the first LSN of every epoch it holds data from; an entry's identity is (epoch, LSN). A recovery ships history whose epochs arrive only at its end, so the table is invalid from before its first byte until that end, under a random token held by the newest recovery. - -```mermaid -stateDiagram-v2 - [*] --> Valid - Valid --> Valid: live entry of a new epoch, row noted before the apply; primary role adopted at the next LSN; load drops rows above the next LSN - Valid --> Invalid: catch-up lane start, rebuild's first base byte, or dual-lane SessionStart (Invalidate, new token) - Invalid --> Invalid: another recovery starts (new token takes the mark, marked "took over invalid"); a completion with another token, or a catch-up's that took over an invalid table, is refused - Invalid --> Valid: the token's recovery synced its data, then its final barrier or rebuild-done (dual-lane too) installs the primary's rows cut at its end - Invalid --> Valid: primary role adopted over it: exactly [(epoch, next LSN)] -``` - -While invalid the volume reports no last data epoch: it reconciles as diverged, is never counted and is rebuilt, and no live entry is noted. Every recovery-data apply runs under the table's apply fence (shared) and only while its token owns the mark; a change of owner takes the fence exclusive, so it waits for in-flight applies to settle and later ones of the old owner are refused. A live apply holds the fence shared too and only while the table is valid, so a recovery's Invalidate drains it. A catch-up must state the LSN it starts after (a start without it is refused) and takes the mark only if the durable end is exactly that LSN; a live entry of a new epoch is accepted only at the store's next LSN. The unconditional reset happens only at primary adoption, after the fence: a primary refuses every inbound recovery frame (`admitMutation`, `EnterDualLane`), so no recovery's data lands under it. - -**Invariants.** - -| Invariant | Enforced in | Test | Model-checked | -|---|---|---|---| -| A replica refuses traffic below its persisted epoch floor, while primary, or before its role is known | `transport/replica.go` `acceptMutationLineage`, `raiseFloor` | `TestG1_RestartedReplicaRefusesShipBelowItsAcknowledgedEpoch` (`core/transport/g1_durable_floor_test.go`); `TestG2_PromotedHostRefusesShipFromDeposedPrimary` (`core/host/volume/g2_self_fence_test.go`) | yes (RF=2 slice) | -| The rebuild port applies the same admission rules | `transport/replica.go` `EnterDualLane` | `TestDualLaneRebuildPort_RefusesStaleSenderAfterFence`, `TestDualLaneRebuildPort_RefusesBeforeRoleKnown` (`core/transport/g6_dual_lane_fence_test.go`) | — | -| A failed apply closes the connection; no barrier acknowledges past a gap | `transport/replica.go` `handleConn` | `TestReplicaApplyFailureStopsBarrierAtTheGap` (`core/transport/replica_apply_error_test.go`); `TestReplicaApplyFailure_PrimaryDegradesRecoversAndReplaysFailedLSN` (`core/replication/component/replica_apply_failure_recovery_test.go`) | — | -| Replication ports are open only for assigned replica slots | `cmd/blockvolume/replication_ingress.go` | `TestBinaryReplicationIngressFollowsAssignedSlots` (`cmd/blockvolume/replication_ingress_binary_test.go`) | — | -| Catch-up versus rebuild follows WAL retention | `core/engine/apply.go` | `TestV3_Decision_CatchUp_GapWithinWAL`, `TestV3_Decision_Rebuild_GapBeyondWAL` (`core/engine/apply_test.go`) | — | -| Only a fenced, caught-up member is promotion-ready | `engine/promotion_ready.go` | `TestBuildPromotionReadyFact_RefusesPendingFence` (`core/engine/promotion_ready_test.go`) | yes (RF=2: acknowledged writes survive failover) | - -**Tests and coverage.** Unit and component tests with in-process replicas; binary tests for ingress. Not modelled: RF=3 quorum, catch-up and rebuild interleavings, startup grace after a primary restart. - -**Review directions.** -- Every inbound frame type must pass the same admission check. -- Any change to barrier accounting must state what "acknowledged" means for each durability mode. -- Rebuild and live WAL feeding must have a single emitter; a second path that ships WAL bypasses ordering. - -**Lessons.** -- #84: the dual-lane rebuild port had no epoch or role check, bypassing the replica fences. Fixed in #85; `TestDualLaneRebuildPort_RefusesStaleSenderAfterFence`. -- #89: a failed `ApplyEntry` was only logged, so a barrier could acknowledge past the gap. Fixed in #93; `TestReplicaApplyFailureStopsBarrierAtTheGap`. -- Epoch floor not persisted (G1) and a new primary not fencing its own listener (G2). Fixed in #83 and #82; `TestG1_RestartedReplicaRefusesShipBelowItsAcknowledgedEpoch`, `TestG2_PromotedHostRefusesShipFromDeposedPrimary`. - -## 1.7 Recovery and typed fail-closed reasons +v1.1 removes the two experimental engines, smartwal (in-place writes plus a metadata ring) and parallel-walstore. Their selector names are refused by blockvolume (`--durable-impl`), the provider and the Kubernetes launcher, and a volume either one created is refused at open under every selector, before any selector comparison, read-only and never modified, with the typed answer "created by a removed experimental engine; copy the data to a walstore volume with v1.0.x first" (`core/frontend/durable/provider.go` `verifyImplOnDisk`, `RemovedEngineName`; ledger `INV-OPEN-REMOVED-ENGINE-REFUSED-001`, `INV-OPEN-REMOVED-ENGINE-NAME-REFUSED-001`). Only their on-disk magics remain in the code: `SWAW`, and `SWPW` in either of parallel-walstore's two header slots. `blockvolume --durable-impl` defaults to auto, which creates new volumes as walstore and opens an existing walstore volume; auto refuses a root that carries chunk metadata (a `walstore-chunk` volume) instead of opening it as plain walstore; such a volume needs `--durable-impl=walstore-chunk` with its remote configuration (`core/frontend/durable/provider.go` `openOrCreate`). When local recovery fails, blockvolume reports a typed reason at once instead of waiting for a timeout (`cmd/blockvolume/durable_startup.go` `openAndRecoverDurable`; `core/host/volume/recovery_watchdog.go` `LocalRecoveryHealthReason`): -- `wal_corrupt`: a WAL integrity failure (bad bounds, a CRC mismatch in smartwal); +- `wal_corrupt`: a WAL integrity failure (bad bounds, a damaged committed record); - `io_error`: an I/O error from the substrate; - `recovery_timeout`: anything unclassified, from the watchdog. @@ -418,7 +253,6 @@ These are tracked for fixes. Most were raised by an independent review of this r - **NVMe/TCP H2CData offset overflow.** The `DATAO + length` bound check is done in 32-bit arithmetic and can wrap, so one malformed PDU can panic the process (`core/frontend/nvme/session.go` `recvH2CData`). Reachable from loopback by default. **Planned fix:** 64-bit arithmetic, offset and R2T consistency checks, and bounds on wire-supplied allocations. - **Process notes in source comments.** #162 removed reviewer names and decision timestamps from code comments. A few comments still cite internal review labels (for example "ruling F1") where a neutral design rationale would be clearer. - **fsync latency.** #173 removed the idle group-commit wait: a lone `Sync` no longer waits out the collection delay, and guest `fsync` fell from about 5.5 ms to a median of 3.23 ms against 2.74 ms local (ublk; see [workspace measurements](../workspace-measurements.md)). Remaining lead: the checkpoint superblock `fsync` runs under the exclusive store lock, stalling reads and writes each flush cycle. -- **smartwal crash window.** A crash between the in-place write and the ring append can leave the volume unopenable (§1.3). smartwal is experimental and not a default: standalone `blockvolume` creates new volumes as walstore (auto), and Kubernetes and workspaces use walstore. **Planned:** fix the ordering. - **Forged records in user data.** WAL records are not bound to a store incarnation or lap, so bytes inside user data that happen to decode as a valid record could be replayed by the defensive scan. **Planned:** an incarnation nonce and lap in the next format, plus a clean-shutdown marker in the meantime. - **Mid-history WAL corruption only warns** (§1.2 step 2). Fixing it needs the synced watermark in the next format. - **No authentication** on the control plane, the replication channel or the filer client. Frontends bind to loopback by default. **Planned:** mTLS and role checks for destructive operations. diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 5fb433ba49..897a8d64ff 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -57,6 +57,7 @@ stateDiagram-v2 [*] --> CreateRefused: CreateWALStore without local headroom (free < size + WAL) [*] --> CreateRefused: chunk volume, create mode: geometry flags disagree with the volume record, or the record is not read [*] --> Opened: half-fence marked map integrity failure, same-incarnation other slot valid unmarked and intact; restart legacy recovery + [*] --> OpenRefused: a removed experimental engine's volume (SWAW, or SWPW in either header slot), any selector Opened --> Recovering: RecoverVolume Recovering --> Serving: Recover ok, backend operational; workspace primary: lease held, then HEAD claim, then frontends listen, then ready Serving --> Closed: runtime HEAD fence, exit 78 head_fenced @@ -74,6 +75,7 @@ stateDiagram-v2 | — | Opened | v3 A/B descriptors and owned-map dependencies valid (or the selected marked map has an integrity-only failure and the same-incarnation valid unmarked half-fence slot has an intact map); exclusive file ownership acquired; legacy formats refused; backend starts not operational | `core/storage/walstore.go` `OpenWALStoreWithOptions`; `core/frontend/durable/provider.go` `openOrCreate` | `INV-WAL-OPGATE-001`, `INV-WAL-V3-ACTIVATION-001`, `INV-WAL-V3-DESCRIPTOR-001`, `INV-WAL-V3-MAP-PUBLISH-001`, `INV-CHUNK-HALF-FENCE-FALLBACK-001` | | — | CreateRefused | a new volume needs the durable root's free space >= its size + WAL (a lab build, tag `swblock_lab_bigvol`, only warns), checked before the store, its WAL or its fresh marker is created (the replica floor, written when the assignment arrives, precedes the check and stays); the refusal ends the process with status 1; an existing volume opens and warns when its remaining data growth + WAL exceed the free space | `core/frontend/durable/headroom.go`; `core/frontend/durable/provider.go` `openOrCreate` | `INV-LOCAL-HEADROOM-001` | | — | CreateRefused | a chunk volume in create mode (no local store yet): before the provider is built, the geometry flags are compared with the volume record; they disagree, or the record is there but does not decode: exit 78; the filer failed the read: exit 75; nothing is created; an absent record keeps the create path; an existing store is never rechecked against the flags | `cmd/blockvolume/main.go` (create-mode check); `cmd/blockvolume/chunk_remote.go` `geometryFlagsRefusal` | `INV-VOL-GEOMETRY-FLAGS-RECORD-001` | +| — | OpenRefused | the file's header carries a removed experimental engine's magic (smartwal, parallel-walstore): refused typed under every selector, read-only, never modified | `core/frontend/durable/provider.go` `verifyImplOnDisk` | `INV-OPEN-REMOVED-ENGINE-REFUSED-001` | | Opened | Recovering | the volume is open in the provider | `core/frontend/durable/provider.go` `RecoverVolume` | `INV-WAL-OPGATE-001`, `INV-RECOVERY-PROGRESS-WINDOW-001` | | Recovering | Serving | v3 nonce/cursor-bound physical prefix satisfies its W/BASE gate; rollback fence and rebuilt bounds publish before reuse; `Recover` aborts/drains an open COW window before lower locks, holds the capture barrier and invalidates proofs at start/end; the frontend targets start, and `FrontendPrimaryReady` is reported, only once the backend admits I/O (a chunk volume: after its storage claim; attach-pending or fenced reports not ready with the reason); a workspace primary claims HEAD, listens and reports ready only while its lease guard permits now (`WorkspaceLeaseGuard.Held`; without a grant: `NotReadyReason=lease_not_held`, exit 75 after the start-time wait); a primary of a replicated line serves only when its own `--replication-ack` is the profile its assignment names (otherwise not Healthy, `NotReadyReason` naming both profiles, ahead of the backend's own refusal) | `core/storage/walstore_v3.go` `recoverV3`; `core/storage/walstore.go` `WALStore.Recover`; `cmd/blockvolume/frontend_gate.go` `awaitFrontendStart`; `core/frontend/durable/storage_adapter.go` `FirstServing`; `core/host/volume/status_server.go` `statusProjection`; `core/host/volume/workspace_lease.go` `Held`; `core/host/volume/workspace_startup.go` `noteAckProfile` | `INV-WAL-SYNCED-RECOVERED-001`, `INV-WAL-REPLAY-LWW-001`, `INV-WAL-FRONTIER-GAP-001`, `INV-CUT-RECOVER-BARRIER-001`, `INV-WAL-V3-W-RECOVERY-001`, `INV-WAL-V3-FENCE-001`, `INV-WAL-V3-MAP-PUBLISH-001`, `INV-FE-PRIMARY-READY-OPERATIONAL-001`, `INV-WS-SERVE-LEASE-HELD-001`, `INV-PRIMARY-ACK-PROFILE-001`, `INV-ATTACH-ASSIGNMENT-BOUND-001`, `INV-LAYOUT-REMOTE-CAPABILITIES-001` | | Recovering | RecoveryFailed | a WAL integrity failure or an I/O error; the backend stays not operational and the host blocks local readiness with `wal_corrupt` or `io_error` | `cmd/blockvolume/durable_startup.go` `openAndRecoverDurable`; `core/host/volume/recovery_watchdog.go` `LocalRecoveryHealthReason` | `INV-WAL-TYPED-FAILCLOSED-001`, `INV-WAL-OPGATE-001`, `INV-WAL-V3-W-RECOVERY-001` | @@ -590,6 +592,8 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-REBUILD-SNAPSHOT-COMPLETE-001` | A rebuild snapshot returns all readable nonzero blocks or an error, never a partial success. The sender propagates snapshot failure before shipping blocks or RebuildDone. | M3 NeedsRebuild (base enumeration) | `core/storage/logical_storage.go` `AllBlocks`; storage implementations; `core/transport/rebuild_sender.go` `doRebuild` | `TestChunkHydration_SnapshotFailsOnReadError`, `TestRebuildSnapshotErrorNeverShipsPartialImage` | Existing fail-closed recovery contract; error propagation only | ACTIVE | | `INV-WAL-SYNCED-RECOVERED-001` | After a crash without media corruption, `Recover` returns every write that a `Sync` acknowledged. | M1 Recovering → Serving | `core/storage/walstore_v3.go` `recoverV3`; `core/storage/walstore.go` `WALStore.Recover` | `TestNativeReplacementTornWrapKeepsAcknowledgedSuffix` (`core/storage/legacy_replacement_v3_test.go`) | `WALRecovery` `I1` | ACTIVE | | `INV-RECOVERY-PROGRESS-WINDOW-001` | Startup reports recovery_timeout only after a window without a new fixed-order phase/count frontier; repeated preparation cannot renew it. Progress never grants readiness or ownership. | M1 Recovering | `core/host/volume/recovery_watchdog.go`; `cmd/blockvolume/durable_startup.go`; `core/storage/recovery_progress.go` | `TestDurableStartup_LocalRecoveryWorkIsOutsideFixedDeadline` (`cmd/blockvolume/durable_startup_budget_test.go`); `TestRecoveryProgress_CountingEntriesOutliveTheTotalWindow`, `TestRecoveryProgress_RepeatedAttachPreparationDoesNotRenew` (`core/host/volume/recovery_progress_test.go`); attach: `TestAttachReportsItsVolumeSizedLocalWork`, `TestAttachReportsTheCreatedThisStartScan`, `TestAttachProgressFlushesSlowWorkAboutEverySecond` (`core/storage/chunk_attach_progress_test.go`), `TestAttachProgressCountsEachAttemptFromZero`, `TestAttachRemoteCallsCarryTheirOwnBound`, `TestAttachManifestReadCarriesThePerFetchRule` (`core/frontend/durable/attach_progress_test.go`), `TestAttachManifestReadBoundsEachFetch` (`core/frontend/chunkstore/layout_attach_fetch_test.go`) | — (joint recovery+attach Linux qualification: 7495 PASS, 0 FAIL, race x5 including the attach tests); C.L | ACTIVE | +| `INV-OPEN-REMOVED-ENGINE-REFUSED-001` | A volume whose header carries a removed experimental engine's magic (smartwal `SWAW`; parallel-walstore `SWPW` at offset 0 or 4096) is refused typed (copy the data to a walstore volume with v1.0.x first) under every selector, read-only and never modified. | M1 [*] → OpenRefused | `core/frontend/durable/provider.go` `verifyImplOnDisk` | `TestDurableProvider_RefusesRemovedEngineVolumes` (byte-identical file after each refusal; `core/frontend/durable/provider_auto_impl_test.go`); `TestWALStoreChunk_SelectorRules` (`core/frontend/durable/provider_chunk_test.go`) | — | ACTIVE | +| `INV-OPEN-REMOVED-ENGINE-NAME-REFUSED-001` | A selector naming a removed experimental engine (`smartwal`, `parallel-walstore`) is refused typed, with the same advice, by blockvolume, the provider and the Kubernetes launcher before any volume is touched. | M1 [*] → OpenRefused | `core/frontend/durable/provider.go` `RemovedEngineName`, `NewDurableProvider`; `cmd/blockvolume/main.go` `parseFlags`; `core/launcher/k8s_renderer.go` | `TestDurableProvider_RefusesRemovedEngineNames` (`core/frontend/durable/provider_auto_impl_test.go`); `TestBlockvolumeRefusesRemovedEngineNames` (`cmd/blockvolume/durable_impl_default_test.go`); `TestK8sRendererRefusesRemovedEngines` (`core/launcher/k8s_renderer_test.go`) | — | ACTIVE | | `INV-WAL-OPGATE-001` | A durable backend refuses `Read`, `Write` and `Sync` until `RecoverVolume` succeeds; a failed recovery leaves it refused. | M1 Opened → Serving; Recovering → RecoveryFailed | `core/frontend/durable/storage_adapter.go` `readyCheck`; `core/frontend/durable/provider.go` `RecoverVolume` | `TestT3b_DurableProvider_Open_StartsNotOperational` (`core/frontend/durable/provider_test.go`); `TestT3b_Recovery_CleanRecover_FlipsOperational` (`core/frontend/durable/recovery_test.go`); `TestWALStoreChunk_MoveBackOntoAnOldRootIsRefused` (`core/frontend/durable/provider_chunk_moveback_test.go`) | — | ACTIVE | | `INV-FE-NVME-READY-001` | A read or write on a successfully recovered chunk volume awaiting attachment waits for attachment readiness, before storage admission, for at most 3 s or until an earlier caller deadline, on the local monotonic clock. | M1 Opened / Recovering → Serving | `core/frontend/durable/storage_adapter.go` `admitAfterAttachUnqueued`, `awaitAttachAdmission`, `readyCheck` | `TestWALStoreChunk_PendingReadWaitIsBounded`; `TestWALStoreChunk_PendingReadHonoursEarlierDeadline`; `TestWALStoreChunk_TakeoverWriteWaitsForAttach`; `TestReadReadinessWaitDoesNotHoldAdmissionAndCloseWakesIt` (`core/frontend/durable/read_ready_wait_test.go`); also in `core/frontend/durable/takeover_read_ready_test.go` | — | ACTIVE | | `INV-FE-NVME-READY-STATUS-001` | An NVMe read or write whose attachment-readiness wait times out or is refused completes with Namespace Not Ready (SC 0x82), DNR=0, without reading or mutating storage. | M1 Opened / Recovering → Serving | `core/frontend/durable/storage_adapter.go` `attachReadyTimeout`; `core/frontend/nvme/io.go` `mapBackendError` | `TestWALStoreChunk_TakeoverReadBeforeAttachIsRetryable`; `TestSessionReadNotReadyIsRetryable` (`core/frontend/nvme/read_ready_retry_test.go`); `TestWALStoreChunk_PendingAttachBeyondHostRetryBudget` (`core/frontend/durable/takeover_read_ready_test.go`) | — | ACTIVE | @@ -605,7 +609,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-WAL-FSYNC-STICKY-001` | After the first failed `fsync` of the store file (WAL, extent, superblock, or the chunk layer's presence save), the open store refuses every later `Sync`, write, checkpoint and presence save without calling `fsync` again; only a reopen and `Recover` clear it. | M1 Serving → FaultLatched | `core/storage/walstore.go` `noteFsyncFailure`, `syncFile`, `stickyIOFault` | `TestNativeReplacementDataFsyncFailureIsSticky` (`core/storage/legacy_replacement_v3_test.go`); `TestNativeReplacementCallerPublicationFaults` (`core/storage/legacy_replacement_v3_test.go`); `TestWALStoreV3SyncRechecksTheFaultAtTheAckBoundary` (`core/storage/walstore_v3_test.go`); `TestAPresenceSaveIsRefusedAfterAFailedFsync`, `TestAPresenceSavesFailedFsyncStaysFailed` (`core/storage/chunk_presence_fsync_test.go`) | — | ACTIVE | | `INV-WAL-APPEND-STICKY-001` | A WAL append whose write failed latches the store fault; writers already queued behind it are refused. | M1 Serving → FaultLatched | `core/storage/walstore_v3.go` `latchV3`, `appendWriteV3` | `TestNativeReplacementQueuedApplyAfterFailedAppend` (`core/storage/legacy_replacement_v3_test.go`); `TestWALStoreV3AppendWriteErrorLatchesTheStore` (`core/storage/walstore_v3_test.go`) | — | ACTIVE | | `INV-WAL-SYNC-FRONTIER-001` | `Sync` never reports an uncovered write durable: it returns the global synced frontier, which is at least the caller's own write and is covered by a completed `fsync`. It may include later writes whose covering `fsync` completed before the caller resumed. | M1 write lifecycle: Appended → Synced | `core/storage/walstore.go` `WALStore.Sync` | `TestWALStore_SyncDoesNotClaimConcurrentWrite` (`core/storage/walstore_test.go`); `TestNativeReplacementSyncCallerReturnOrdering` (`core/storage/legacy_sync_replacement_v3_test.go`) | — | ACTIVE | -| `INV-WAL-TYPED-FAILCLOSED-001` | A corrupt replay at startup is reported as `wal_corrupt` at once and keeps local readiness blocked. | M1 Recovering → RecoveryFailed | `cmd/blockvolume/durable_startup.go` `openAndRecoverDurable`; `core/host/volume/recovery_watchdog.go` `LocalRecoveryHealthReason` | `TestDurableStartup_RealProviderCorruptReplayIsWALCorrupt` (`cmd/blockvolume/durable_startup_test.go`); `TestLocalRecoveryFailure_CorruptWALReportsWALCorruptAtOnce` (`core/host/volume/recovery_typed_reason_test.go`) | — | ACTIVE | +| `INV-WAL-TYPED-FAILCLOSED-001` | A corrupt replay at startup is reported as `wal_corrupt` at once and keeps local readiness blocked. | M1 Recovering → RecoveryFailed | `cmd/blockvolume/durable_startup.go` `openAndRecoverDurable`; `core/host/volume/recovery_watchdog.go` `LocalRecoveryHealthReason` | `TestDurableStartup_Issue51_WALStoreV3CommittedHoleBlocksReadiness` (`cmd/blockvolume/durable_startup_slotcrc_test.go`); `TestLocalRecoveryFailure_CorruptWALReportsWALCorruptAtOnce` (`core/host/volume/recovery_typed_reason_test.go`) | — | ACTIVE | | `INV-WAL-WARN-NO-HEALTH-001` | Recovery warnings (for example `wal_hole_suspected`) appear in status without changing health or eligibility. | M1 Serving | `core/host/volume/status_server.go` `statusProjection` | `TestStatusServer_StatusCarriesRecoveryWarningsWithoutChangingHealth` (`core/host/volume/status_warnings_test.go`) | — | ACTIVE | | `INV-WAL-V3-ACTIVATION-001` | Public create produces an owned-map v3/impl3 volume with the requested chunk geometry, in mode C unless mode A is requested. | M1 open/create/readonly | `core/storage/walstore.go` `CreateWALStoreWithOptions`; `core/storage/walstore_v3.go` `createWALStoreV3Configured` | `TestWALStoreProductionSelectorCreatesMappedV3`, `TestWALStoreProductionCreateOptions` (`core/storage/walstore_activation_test.go`) | Selector wiring only; native protocol remains the accepted composed format model, not a new model proof | ACTIVE | | `INV-WAL-V3-ACTIVATION-FALLBACK-001` | When descriptor slot A is damaged without being a valid legacy superblock and slot B is valid, writable and read-only open select slot B. | M1 open/create/readonly | `core/storage/walstore_v3.go` `refuseLegacyWALStore`, `openWALStoreV3File`; `core/storage/walstore_readonly_v3.go` `openReadOnlyV3`; `core/storage/superblock_v3.go` `selectSlotV3` | `TestWALStoreProductionFallsBackWhenDamagedSlotOnlyLooksLegacy` (`core/storage/walstore_activation_test.go`) | — | ACTIVE | @@ -737,7 +741,7 @@ Notes: - `INV-WAL-CHECKPOINT-SNAPSHOT-001`: The SIGKILL test is Linux only. - `INV-FE-FLUSH-SYNC-001`: NVMe/TCP also asserts failed-Sync status and reason logging through the actual session dispatch, and success produces no failure log. - `INV-WAL-V3-RESET-001`: Format bump v3, plan row 8 (DESIGN 8.6). Dark: no production path calls the reset, and it must not be activated before the reset model (r4.5) passes. The precondition is CheckpointLSN >= W rather than an empty retained range: retained old-incarnation bytes at or below the checkpoint are preserved in the extent. The map root is unchanged by a reset, so no map page is retired. -- `INV-WAL-V3-BASE-001`: Format bump v3, plan row 9a (DESIGN r17.3.1 sections 8.1, 8.2, 8.4, 8.5, 8.7). Production reaches it through both callers below: the legacy single-lane caller by default, the dual-lane `Receiver` with `--recovery-mode=dual-lane`. Row 9b makes the seam `BaseInstallPreparer.BeginBaseInstall(baseLSN, installID) (InstallHandle, error)`: the dual-lane `Receiver` begins at SessionStart (BaseLSN = FromLSN, a fresh random ID) and its `RebuildSession` writes, applies and completes only through the handle, propagating the `MarkBaseComplete` error; stores without the seam keep their exact pre-seam behaviour through the lazy legacy handle (parallelwal's staging is now `BaseStager.BeginBaseStage`). Since row 10b the legacy single-lane caller (`core/transport/replica.go`) is on the handle too: the first admitted `MsgRebuildBlock` (or an empty rebuild's `MsgRebuildDone`) begins one install per connection at the lineage's frontier hint under a fresh random ID, blocks go through `WriteBase`, a different hint on the connection is refused, and done completes and then Syncs, closing the connection with no `MsgBarrierResp` when either fails; a reconnect is a superseding install under the coverage rule (tagged controls in `core/transport/replica_install_format_v3_test.go`). A v3 begin with an attached chunk layer that has no BASE transition hook is refused (`errV3NotYet`), writing nothing (`TestBaseInstallV3BeginRefusesWithAnUnsupportedAttachedChunkLayer`; a supported layer is drained as in `INV-WAL-V3-CHUNK-BASE-001`); since row 9c the v3 `SeedChunkFrontier` publishes CheckpointLSN = W = map coverage = lsn through the one checkpoint publication (`publishCheckpointV3`: data fsync, metadata and chunk barriers, owned-map candidate, the sole slot publisher under syncMu with the lifetime check), moves the volatile frontier only after it, publishes nothing on failure, and refuses local writes, an install, an attached layer or a store without an owned map; the provider's former refusal of a HEAD restore onto a v3 store is gone since row 12a (see the `INV-WAL-V3-MAP-PUBLISH-001` note); since row 11a an installing physical reopen (an installing ID this open did not begin) keeps its recovered bounds (E, R, intact or damaged) without fencing, publishing or admitting; a same-open Recover of this open's live install records none, so its still-valid handle cannot append past a cached cut that a resume would fence from; it republishes the live install's trusted records in the dirty map and keeps the volatile map coverage, or latches the store when the recovered cut is short of the live writer, and a covering superseding begin after it fences [E, floor + WALSize) and fsyncs before its two-slot installing publication, anchors at P = max(E, the persisted retainedHead) without lowering retainedHead, and restarts the writer at P (forward only); since row 11b the same-ID resume after a reopen (store level; no current caller resumes, both receivers begin fresh IDs) runs under `installMu` exclusive and appends nothing until the trusted-through-W check (intact suffix and E >= the persisted retainedHead), the fence of [E, floor + WALSize) with fsync and a retainedHead = E publication all held, refusing with `ErrInstallSuffixDamaged` and writing nothing otherwise; the writer continues at E and the recovered install-lane records are replayed. A begin while installed is refused until retirement (8.5 has no installed -> installing edge). +- `INV-WAL-V3-BASE-001`: Format bump v3, plan row 9a (DESIGN r17.3.1 sections 8.1, 8.2, 8.4, 8.5, 8.7). Production reaches it through both callers below: the legacy single-lane caller by default, the dual-lane `Receiver` with `--recovery-mode=dual-lane`. Row 9b makes the seam `BaseInstallPreparer.BeginBaseInstall(baseLSN, installID) (InstallHandle, error)`: the dual-lane `Receiver` begins at SessionStart (BaseLSN = FromLSN, a fresh random ID) and its `RebuildSession` writes, applies and completes only through the handle, propagating the `MarkBaseComplete` error; stores without the seam keep their exact pre-seam behaviour through the lazy legacy handle (the legacy `BaseStager.BeginBaseStage` staging remains as an interface; parallel-walstore, its one shipped implementation, is removed). Since row 10b the legacy single-lane caller (`core/transport/replica.go`) is on the handle too: the first admitted `MsgRebuildBlock` (or an empty rebuild's `MsgRebuildDone`) begins one install per connection at the lineage's frontier hint under a fresh random ID, blocks go through `WriteBase`, a different hint on the connection is refused, and done completes and then Syncs, closing the connection with no `MsgBarrierResp` when either fails; a reconnect is a superseding install under the coverage rule (tagged controls in `core/transport/replica_install_format_v3_test.go`). A v3 begin with an attached chunk layer that has no BASE transition hook is refused (`errV3NotYet`), writing nothing (`TestBaseInstallV3BeginRefusesWithAnUnsupportedAttachedChunkLayer`; a supported layer is drained as in `INV-WAL-V3-CHUNK-BASE-001`); since row 9c the v3 `SeedChunkFrontier` publishes CheckpointLSN = W = map coverage = lsn through the one checkpoint publication (`publishCheckpointV3`: data fsync, metadata and chunk barriers, owned-map candidate, the sole slot publisher under syncMu with the lifetime check), moves the volatile frontier only after it, publishes nothing on failure, and refuses local writes, an install, an attached layer or a store without an owned map; the provider's former refusal of a HEAD restore onto a v3 store is gone since row 12a (see the `INV-WAL-V3-MAP-PUBLISH-001` note); since row 11a an installing physical reopen (an installing ID this open did not begin) keeps its recovered bounds (E, R, intact or damaged) without fencing, publishing or admitting; a same-open Recover of this open's live install records none, so its still-valid handle cannot append past a cached cut that a resume would fence from; it republishes the live install's trusted records in the dirty map and keeps the volatile map coverage, or latches the store when the recovered cut is short of the live writer, and a covering superseding begin after it fences [E, floor + WALSize) and fsyncs before its two-slot installing publication, anchors at P = max(E, the persisted retainedHead) without lowering retainedHead, and restarts the writer at P (forward only); since row 11b the same-ID resume after a reopen (store level; no current caller resumes, both receivers begin fresh IDs) runs under `installMu` exclusive and appends nothing until the trusted-through-W check (intact suffix and E >= the persisted retainedHead), the fence of [E, floor + WALSize) with fsync and a retainedHead = E publication all held, refusing with `ErrInstallSuffixDamaged` and writing nothing otherwise; the writer continues at E and the recovered install-lane records are replayed. A begin while installed is refused until retirement (8.5 has no installed -> installing edge). - `INV-WAL-V3-MIGRATE-001`: Archived with the converter and its legacy fixtures; v2 inputs refuse open without mutation. - `INV-WAL-V3-W-001`, `INV-WAL-V3-FENCE-001`: Format bump v3, plan rows 5 and 5b (DESIGN r15 sections 6.1 to 6.6). Since 5b the v3 format runs inside the real `WALStore`, through the shared committer, dirty map, flusher and leaf. Since activation (row 12b) production create and open (`CreateWALStoreWithOptions`, `OpenWALStoreWithOptions`) reach it. Without the row-7 map candidate (unmapped test fixtures only) the v3 checkpoint and tail do not advance. `INV-WAL-V3-W-001` stays a STUB for the reason in the format v3 status note below; `INV-WAL-V3-FENCE-001` is still a STUB although the path is active, its promotion pending a per-row check of its tests. The test "crash" closes the file without further writes, so the slot-before-records reordering that mode C's lagged W guards against is covered by the composed model, not by these tests. Installing recovery is row 11. - `INV-WAL-V3-PUBLISH-001`: Format bump v3, plan row 3 (DESIGN r15 sections 4, 5 and 5.1). The v3 store is wired in (rows 4 and 5) and activated (row 12b); the row stays a STUB for the reason in the format v3 status note below. The v2 checkpoint path (`persistCheckpointReleasing`) is retired. The map coverage predicates against the root are added by row 7, and the conditions on BASE edges by rows 9 to 11. @@ -815,7 +819,7 @@ Notes: | `INV-REPL-NO-PER-LBA-DATA-REGRESSION` | On a replica, an entry writes data only if its LSN is above both P and its LBA's applied LSN, one value shared by every session and lane; a successful write sets that applied LSN to the entry's LSN. | M3 replica apply / session release | `core/replication/apply_gate.go` `applyRecovery`, `applyLive`; `cmd/blockvolume/replication_ingress.go` `replicationIngress` (one `NewReplicaApplyGate` per replica) | `TestReplicationIngressSharesApplyVersionsAcrossSessions` (`cmd/blockvolume/replication_ingress_apply_test.go`); `TestApplyGate_OverlappingSessionsNeverRegressBytes` (`core/replication/apply_gate_cross_session_test.go`); `TestApplyGate_AlreadyAdmittedWireSessionNeverRegressesBytes` (`core/replication/apply_gate_wire_overlap_test.go`); `TestApplyGate_PrunedDurableVersionsRemainStale` (`core/replication/apply_gate_floor_test.go`); `TestApplyGate_LiveAndRecovery_DistinctCoverageSharedVersion` (`core/replication/apply_gate_test.go`) | `ReplicaApplyOrder` NoRegression; `ReplicaPrefixFloor` NoRegression/OnlySuffix | ACTIVE | | `INV-REPL-NO-PER-LBA-STALE-RECOVERY` | A stale recovery-lane entry, LSN at or below max(applied LSN, P), writes no data and still marks its LBA covered for its own session. | M3 replica apply / session release | `core/replication/apply_gate.go` `applyRecovery` | `TestApplyGate_RecoveryLane_StaleSkip_DoesNotRegressData`, `TestApplyGate_RecoveryLane_StaleSkip_AdvancesRecoveryCovered` (`core/replication/apply_gate_test.go`) | — | ACTIVE | | `INV-REPL-NO-PER-LBA-STALE-LIVE` | A stale live-lane entry writes no data, returns an error, and marks no recovery coverage. | M3 replica apply / session release | `core/replication/apply_gate.go` `applyLive`; `core/transport/replica.go` `handleConn` (closes the connection, `INV-REPL-APPLY-FAIL-001`) | `TestApplyGate_LiveLane_StaleEntry_ReturnsError`, `TestApplyGate_LiveLane_StaleEntry_DoesNotAdvanceRecoveryCovered` (`core/replication/apply_gate_test.go`) | — | ACTIVE | -| `INV-REPL-LIVE-NEXT-LSN-001` | Inside an epoch, a live-lane entry above the store's next LSN (an LSN skipped) is not applied: the replica closes the connection and its barrier reports the end below the gap; entries replayed from that end apply once, in order. | M3 replica apply | `core/transport/replica.go` `handleConn` (with and without the apply gate; no live entry lands while a recovery owns the store) | `TestReplicaAppliesALiveEntryOnlyAtItsNextLSN`, `TestReplicaAppliesNoLiveEntryWhileARecoveryOwnsTheStore` (`core/replication/replica_next_lsn_test.go`; walstore and smartwal, the volume's listener construction); guarded during a recovery (a per-block catch-up's end may sit above a gap): such a replica is never a fencing round's target and never completes a write, `TestPromotionGate_DecidesOnTheFencingRound` (row: invalid table, highest end), `TestReplicaMidCatchUpNeverCompletesAWrite` (`core/replication/component/midrecovery/mid_recovery_count_test.go`); also in `core/host/master/fence_gate_test.go` | — | ACTIVE | +| `INV-REPL-LIVE-NEXT-LSN-001` | Inside an epoch, a live-lane entry above the store's next LSN (an LSN skipped) is not applied: the replica closes the connection and its barrier reports the end below the gap; entries replayed from that end apply once, in order. | M3 replica apply | `core/transport/replica.go` `handleConn` (with and without the apply gate; no live entry lands while a recovery owns the store) | `TestReplicaAppliesALiveEntryOnlyAtItsNextLSN`, `TestReplicaAppliesNoLiveEntryWhileARecoveryOwnsTheStore` (`core/replication/replica_next_lsn_test.go`; walstore, the volume's listener construction); guarded during a recovery (a per-block catch-up's end may sit above a gap): such a replica is never a fencing round's target and never completes a write, `TestPromotionGate_DecidesOnTheFencingRound` (row: invalid table, highest end), `TestReplicaMidCatchUpNeverCompletesAWrite` (`core/replication/component/midrecovery/mid_recovery_count_test.go`); also in `core/host/master/fence_gate_test.go` | — | ACTIVE | | `INV-REPL-NO-PER-LBA-RETAIN` | Closing a session or merging a substrate seed below the recorded value never lowers an LBA's applied LSN. | M3 replica apply / session release | `core/replication/apply_gate.go` `CloseSession`, `initSessionLocked` | `TestApplyGate_CloseAndLowerSeedNeverEraseReplicaVersion` (`core/replication/apply_gate_cross_session_test.go`) | — | ACTIVE | | `INV-REPL-NO-PER-LBA-FAILED-WRITE` | A failed physical write leaves its LBA's applied LSN and its session's coverage unchanged. | M3 replica apply / session release | `core/replication/apply_gate.go` `applyRecovery`, `applyLive` | `TestApplyGate_FailedWriteDoesNotPublishReplicaVersion` (`core/replication/apply_gate_cross_session_test.go`) | — | ACTIVE | | `INV-REPL-NO-PER-LBA-CERTIFIED-PREFIX` | P advances only through an explicit recovery-prefix certificate admitted for the active, prefix-eligible lineage; synced R, live traffic and session changes never advance it. | M3 replica apply / session release | `core/replication/apply_gate.go` `CertifyRecoveryPrefix`; `core/transport/replica.go` `certifyRecoveryPrefix`, `markPrefixEligibility` | `TestApplyGate_CertifiedRecoveryClosesBoundVersionHistory`, `TestApplyGate_CertifiedPrefixFreezesAcrossSessions`, `TestApplyGate_SyncedLiveMaximumDoesNotCoverRecoveryHole` (`core/replication/apply_gate_floor_test.go`); `TestApplyGate_HealthyRecoveryPublishesWirePrefix`, `TestApplyGate_WirePrefixCannotIntroduceOrReviveSession` (`core/replication/apply_gate_prefix_wire_test.go`) | `ReplicaPrefixFloor` CertifiedCoverage | ACTIVE | diff --git a/seaweed-block/docs/design/kubernetes-block-design.md b/seaweed-block/docs/design/kubernetes-block-design.md index 8886f12a88..20ea776aa3 100644 --- a/seaweed-block/docs/design/kubernetes-block-design.md +++ b/seaweed-block/docs/design/kubernetes-block-design.md @@ -8,7 +8,7 @@ The three design documents: | Document | Covers | |---|---| -| [Core design](block-design.md) | The shared core: frontends and the Backend contract, walstore, smartwal (experimental), durability and `Sync`, authority and epochs, the replication engine, recovery; verification, lessons and known issues across the codebase | +| [Core design](block-design.md) | The shared core: frontends and the Backend contract, walstore, the removed experimental engines, durability and `Sync`, authority and epochs, the replication engine, recovery; verification, lessons and known issues across the codebase | | [Agent workspace design](agent-workspace-design.md) | Agent workspace disks (proof of concept): one local replica per workspace, cuts to SeaweedFS, snapshots, forks, GC, host moves | | Kubernetes block design (this document) | The product view of Kubernetes volumes: CSI, Helm and the operator controllers, replication and failover, multipath, promotion, readiness, the operation layer | diff --git a/seaweed-block/docs/design/lba-width-census.tsv b/seaweed-block/docs/design/lba-width-census.tsv index 726487e2c8..c48451b27b 100644 --- a/seaweed-block/docs/design/lba-width-census.tsv +++ b/seaweed-block/docs/design/lba-width-census.tsv @@ -6,10 +6,6 @@ lba-width-census/1 walstore-v3 disk map root chunks/chunkBlocks/pages 64 core/st lba-width-census/1 walstore-v3 disk presence absent/local index 64 core/storage/chunk_layer.go:2003 Canonical decimal parsed with bitSize 64; new bitmap replaces this in the single upgrade lba-width-census/1 chunk-record disk-proposed page segment / header chunks 64 core/storage/chunk_record.go (#816) page Segment and header Chunks already uint64; chunk within segment implicit; candidates uint32 is bounded count not LBA lba-width-census/1 remote-layout disk segment shard/chunk index/root shard 64 core/frontend/chunkstore/layout/layout.go:181 uint64 uvarint; no new remote format needed for address width -lba-width-census/1 smartwal disk record.LBA 32 core/storage/smartwal/record.go:79 LE uint32 bytes 4:8; do not widen; production reachability audit decides removal in a separate change -lba-width-census/1 smartwal disk header.NumBlocks 32 core/storage/smartwal/superblock.go:90 LE uint32 bytes 28:32; do not widen; keep paired with its record codec pending removal audit -lba-width-census/1 parallelwal disk walRecord.LBA 32 core/storage/parallelwal/record.go:43 LE uint32 bytes 16:20; do not widen; production reachability audit decides removal in a separate change -lba-width-census/1 parallelwal disk fileHeader.NumBlocks 32 core/storage/parallelwal/header.go:95 LE uint32 bytes 28:32; do not widen; keep paired with its record codec pending removal audit lba-width-census/1 storage-contract memory LogicalStorage addresses and NumBlocks 32 core/storage/logical_storage.go:63 Must widen for serving high addresses; current geometry refuses above uint32 lba-width-census/1 storage-contract memory RecoveryEntry.LBA 32 core/storage/recovery_contract.go:80 Scan/restore narrow existing 64-bit WAL addresses; update every adapter lba-width-census/1 storage-contract memory BlockMetadata hooks and NumBlocks 32 core/storage/block_metadata.go:15 Enterprise metadata seam must be widened or explicitly refused; no OSS persisted index here diff --git a/seaweed-block/docs/overview.md b/seaweed-block/docs/overview.md index 220a7d30b9..395b82beb6 100644 --- a/seaweed-block/docs/overview.md +++ b/seaweed-block/docs/overview.md @@ -7,7 +7,7 @@ belong under `internal/docs/`, not here. | File | Purpose | |---|---| -| `design/block-design.md` | Core design: frontends, walstore and smartwal, durability, authority, replication engine, recovery; verification and known issues | +| `design/block-design.md` | Core design: frontends, walstore (and the removed experimental engines), durability, authority, replication engine, recovery; verification and known issues | | `design/agent-workspace-design.md` | Agent workspace disks: chunk backend, cuts, snapshots, forks, GC, host moves, security model | | `design/kubernetes-block-design.md` | Kubernetes block volumes: CSI, Helm and operator, replication and failover, multipath, readiness | | `spec/` | TLA+ specifications of the protocols where a bug would lose data | diff --git a/seaweed-block/docs/persisted-state.md b/seaweed-block/docs/persisted-state.md index 61ed2561e2..99ab8b7bb8 100644 --- a/seaweed-block/docs/persisted-state.md +++ b/seaweed-block/docs/persisted-state.md @@ -64,9 +64,8 @@ All under `--durable-root` unless the row says otherwise. | Host limit configuration | `<--host-limit-dir>/configuration.json`, shared by the host's holders | blockvolume | JSON, compared byte for byte; a different configuration is refused | **no** | no | | Lock files | `.lock`; the host limit directory's lock and slot files | blockvolume | empty lock files | not needed | no | -The experimental stores (`--durable-impl smartwal`, `parallel-walstore`) have their own magic and version in -`.bin`, refuse other versions, and are not pinned. They are experimental; smartwal does not support the -chunk layer. +The experimental stores of v1.0.x (`--durable-impl smartwal`, `parallel-walstore`) are removed in v1.1. A +`.bin` carrying their magic is refused at open, typed and unmodified: created by a removed experimental engine; copy the data to a walstore volume with v1.0.x first. ## Files the sw-block commands write diff --git a/seaweed-block/docs/releases/README.md b/seaweed-block/docs/releases/README.md index a4ac616934..97cd9221cc 100644 --- a/seaweed-block/docs/releases/README.md +++ b/seaweed-block/docs/releases/README.md @@ -4,6 +4,7 @@ Seaweed Block release notes use narrow product claims. Each alpha version names what a user or reviewer can actually run, what QA evidence backs it, and what is still outside the supported boundary. +- [v1.1 (unreleased)](v1.1.md) - [v1.0.1](v1.0.1.md) - [v1.0.0](v1.0.0.md) - [Cleaning changes in v1.0.1](cleaning-convergence.md) diff --git a/seaweed-block/docs/releases/v1.1.md b/seaweed-block/docs/releases/v1.1.md new file mode 100644 index 0000000000..0083cbda57 --- /dev/null +++ b/seaweed-block/docs/releases/v1.1.md @@ -0,0 +1,8 @@ +# v1.1 (unreleased) + +These notes collect v1.1's changes as they land; v1.1 is not released. + +## Removed +- The experimental engines `--durable-impl smartwal` and `--durable-impl parallel-walstore` are removed. A volume + either one created does not open: it is refused with "created by a removed experimental engine; copy the data to a walstore volume with v1.0.x first". The names are refused by `blockvolume + --durable-impl`, `blockmaster --launcher-durable-impl` and the provider. v1.0.1's notes carried the advance notice. diff --git a/seaweed-block/docs/standalone-deployment.md b/seaweed-block/docs/standalone-deployment.md index d5e56d2703..560f9921a6 100644 --- a/seaweed-block/docs/standalone-deployment.md +++ b/seaweed-block/docs/standalone-deployment.md @@ -407,7 +407,7 @@ volume or prove frontend readiness. | `SWB_HEARTBEAT_INTERVAL` | `--heartbeat-interval` | `2s` | Heartbeat interval | | `SWB_RECOVER_TIMEOUT` | `--recover-timeout` | `30s` | Time to become promotion-ready before reporting `recovery_timeout` | | `SWB_DURABLE_ROOT` | `--durable-root` | empty (in memory, not durable) | Storage directory; writable by the service user | -| `SWB_DURABLE_IMPL` | `--durable-impl` | empty (auto) | Auto creates new volumes as `walstore`, opens existing ones with their on-disk format, and refuses a `walstore-chunk` root; so does every explicit value other than `walstore-chunk` (a chunk root holds data that may live only in the remote HEAD: open it with `--durable-impl=walstore-chunk` and its remote configuration). Explicit: `walstore`, `walstore-chunk` (workspace, proof of concept), `smartwal` (experimental). The examples set `walstore`. | +| `SWB_DURABLE_IMPL` | `--durable-impl` | empty (auto) | Auto creates new volumes as `walstore`, opens existing ones with their on-disk format, and refuses a `walstore-chunk` root; so does every explicit value other than `walstore-chunk` (a chunk root holds data that may live only in the remote HEAD: open it with `--durable-impl=walstore-chunk` and its remote configuration). Explicit: `walstore`, `walstore-chunk` (workspace, proof of concept). The removed experimental engines (`smartwal`, `parallel-walstore`) are refused. The examples set `walstore`. | | `SWB_DURABLE_BLOCKS` | `--durable-blocks` | `2048` | Blocks on first create | | `SWB_DURABLE_BLOCKSIZE` | `--durable-blocksize` | `4096` | Block size on first create | | `SWB_NVME_LISTEN` | `--nvme-listen` | empty (off) | NVMe/TCP target; loopback only, no authentication | @@ -688,9 +688,8 @@ step stops it. In order, it: prints `PASS` and the artifact directory. An exit trap unmounts, disconnects and stops the processes. -The script's default engine is `SW_BLOCK_DURABLE_IMPL=smartwal`; the command -above sets `walstore`, the engine used by the Kubernetes chart and the -workspace path. There is no equivalent script for ublk yet. +The script's default engine is `SW_BLOCK_DURABLE_IMPL=walstore`, the engine +used by the Kubernetes chart and the workspace path. There is no equivalent script for ublk yet. ## Planned workspace hand-over diff --git a/seaweed-block/docs/status-schema.md b/seaweed-block/docs/status-schema.md index b818324b38..975325eb57 100644 --- a/seaweed-block/docs/status-schema.md +++ b/seaweed-block/docs/status-schema.md @@ -79,7 +79,7 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`. | `Volumes[].HeadWrites{}` | uint64 | acknowledged HEAD writes by cause since holder catalog start; unknown replies excluded | | `Volumes[].VolumeID` | string | the volume | | `Volumes[].Path` | string | its store path under --durable-root | -| `Volumes[].Impl` | string | the durable implementation (walstore, smartwal, walstore-chunk, ...) | +| `Volumes[].Impl` | string | the durable implementation (walstore or walstore-chunk) | | `Volumes[].ReplicaID` | string | the replica this store holds | | `Volumes[].StoreID` | string | the store's superblock UUID (hex); empty when it carries none (omitted when empty) | | `Volumes[].Epoch` | uint64 | the epoch the store is latched to; 0 before an assignment | diff --git a/seaweed-block/docs/wiki/code-map.md b/seaweed-block/docs/wiki/code-map.md index 5baba180b2..7cd7ffcae2 100644 --- a/seaweed-block/docs/wiki/code-map.md +++ b/seaweed-block/docs/wiki/code-map.md @@ -29,7 +29,6 @@ developers; it is not a complete API reference. | `core/frontend/durable` | durable provider and the per-I/O lineage gate | | `core/frontend/chunkstore` | SeaweedFS chunk backend: HEAD CAS, catalog, snapshots, GC | | `core/storage` | walstore (WAL plus extent), chunk layer, recovery | -| `core/storage/smartwal` | experimental in-place engine | | `core/replication`, `core/recovery`, `core/transport` | RF>1 shipping, catch-up and rebuild, replica fencing | | `testops` | scenario descriptions and release gates | @@ -66,7 +65,7 @@ mutation and prevents lifecycle ownership from becoming a broad operator. | Enrich live node/CSI evidence | `cmd/sw-block/main.go`, `core/ops/kubernetes_node_evidence.go` | | Replay support bundles | `core/ops/observation_bundle.go`, `scripts/collect-helm-support-bundle.sh` | | Render report/dashboard/snapshot | `core/ops/observation_report.go`, `core/ops/observation_dashboard.go`, `core/ops/operator_snapshot.go` | -| SmartWAL and recovery frontier handling | `core/storage/smartwal/`, `core/recovery/`, `core/transport/` | +| Recovery frontier handling | `core/recovery/`, `core/transport/` | | CRD/RBAC status conformance | `core/ops/kubernetes_status_writer.go`, `core/ops/kubernetes_status_conformance_test.go`, `charts/seaweed-block/crds/` | | blockvolume process readiness | `cmd/blockvolume/main.go`, `core/host/volume/host.go`, `core/frontend/durable/` | | Release image/chart compatibility | `charts/seaweed-block/templates/`, `charts/seaweed-block/values.yaml`, `docs/releases/`, `docs/quickstart-kubernetes.md` | diff --git a/seaweed-block/docs/wiki/deep-dives/smartwal-dirty-failure.md b/seaweed-block/docs/wiki/deep-dives/smartwal-dirty-failure.md deleted file mode 100644 index 6106eb212f..0000000000 --- a/seaweed-block/docs/wiki/deep-dives/smartwal-dirty-failure.md +++ /dev/null @@ -1,142 +0,0 @@ -# SmartWAL Dirty-Failure Path - -The SmartWAL corruption gate is the best example of why live dirty-failure -tests matter. It found a real false-ready bug that unit tests and clean failure -tests missed. - -## Problem - -A corrupted WAL record is not the same as a missing pod or a clean restart. It -is a block-storage integrity event. The system must answer harder questions: - -- Did recovery read a committed record or a torn tail? -- Is the corruption before or after the durable frontier? -- Can later records be trusted if an earlier committed record failed CRC? -- Does local readiness stay blocked while diagnostics remain available? -- Does the control plane refuse to project `Ready=True` without a positive - readiness fact? - -If the product detects corruption but still reports `Ready=True`, users get a -false safety signal. - -The required behavior is: - -```text -detect integrity fault --> fail closed --> block local readiness --> projection refuses Ready=True without positive readiness -``` - -## Failure Chain - -```mermaid -sequenceDiagram - participant QA as TestOps corrupt gate - participant WAL as SmartWAL - participant BV as blockvolume - participant BM as blockmaster - participant OPS as operator-status/report - - QA->>WAL: corrupt real WAL record - WAL-->>BV: recovery CRC mismatch / WAL integrity fault - BV->>BV: keep status endpoint diagnosable - BV->>BM: do not publish local primary readiness - BM->>OPS: evidence lacks positive primary readiness - OPS-->>QA: Ready is Unknown/Blocked, never Ready=True -``` - -## What The Gate Caught - -The gate forced fixes through multiple layers: - -1. Storage layer: do not skip mid-history CRC mismatch as a harmless torn tail. -2. blockvolume process: do not continue publishing healthy after durable - recovery fault. -3. blockmaster projection: heartbeat/reachability is not enough for Ready. - Primary readiness must be positively confirmed. - -This sequence matters because each local fix was necessary but insufficient -until the surface stopped claiming false readiness. - -## Why Clean Failure Tests Missed This - -Clean failures are easy to reason about: - -```text -pod killed -status endpoint gone -primary unavailable -``` - -Dirty failures are different: - -```text -process restarted -status endpoint reachable -storage recovery found corruption -local readiness blocked -control plane still has old assignment facts -``` - -That shape exposes a common anti-pattern: - -```text -reachable process + assigned primary -> Ready -``` - -For block storage, that is wrong. Reachability is an observation, not readiness. -Readiness must include semantic storage and authority facts. - -## Historical Method Link - -The methodology docs use these terms: - -| Term | In this gate | -|---|---| -| frontier | recovery boundary that must not regress | -| barrier/fence | ordering/durability checkpoint | -| lineage | old ready facts must not override new fault state | -| projection | blockmaster/operator view of readiness | -| readiness | permission to serve writes | - -The bug existed because projection and readiness were not fully separated at -every layer. The fix was not just a storage patch; it was a control-structure -repair. - -## Main Code Areas - -| Layer | Code area | -|---|---| -| SmartWAL recovery | `core/storage/smartwal/` | -| durable frontend readiness | `core/frontend/durable/` | -| blockvolume process readiness | `cmd/blockvolume/main.go` | -| blockmaster projection | `core/host/master/observation_snapshot.go`, `core/host/volume/projection_bridge.go` | -| status projection | `core/ops` | - -## QA Evidence - -| Artifact | Purpose | -|---|---| -| `helm-smartwal-corrupt-restart-chain.yaml` | live dirty-failure scenario | -| Phase 34 D4 finding | proved false Ready after real WAL corruption | -| Phase 34 D4 verify reports | tracked storage fix, process fix, projection fix | -| Phase 34 D4 PASS | confirmed no false Ready after corruption | - -## Design Rule - -Do not let "process is reachable" imply "volume is ready". - -```text -reachable endpoint + assigned primary != positive readiness evidence -``` - -This same rule should be reused for returned-replica rebuild, partial recovery, -and future dirty shutdown scenarios. - -## Non-Claims - -- The gate does not prove all WAL corruption modes are recoverable. -- It does not prove no data loss under every power-loss pattern. -- It proves the product does not falsely report Ready when known dirty evidence - is present. diff --git a/seaweed-block/docs/wiki/index.md b/seaweed-block/docs/wiki/index.md index fc7c9453eb..efea6d6a39 100644 --- a/seaweed-block/docs/wiki/index.md +++ b/seaweed-block/docs/wiki/index.md @@ -55,7 +55,6 @@ right gate and diagnose a failed run. - [Operation Layer v0.5](deep-dives/operation-layer-v05.md) - [Status Writer Conformance](deep-dives/status-writer-conformance.md) - [ManagedVolume Readiness](deep-dives/managed-volume-readiness.md) -- [SmartWAL Dirty Failure](deep-dives/smartwal-dirty-failure.md) - [WAL Frontier Recovery](deep-dives/wal-frontier-recovery.md) - [blockvolume Process Readiness](deep-dives/blockvolume-process-readiness.md) - [Authority And Promotion](deep-dives/authority-promotion.md) diff --git a/seaweed-block/docs/wiki/state-machines.md b/seaweed-block/docs/wiki/state-machines.md index ea1eb93bf4..90bf6f01a6 100644 --- a/seaweed-block/docs/wiki/state-machines.md +++ b/seaweed-block/docs/wiki/state-machines.md @@ -114,7 +114,7 @@ shape. ## Dirty-Failure Rule -The SmartWAL corruption gate established the pattern: +The corruption gate of the (since removed) SmartWAL engine established the pattern: ```text detect corruption diff --git a/seaweed-block/docs/wiki/testops-map.md b/seaweed-block/docs/wiki/testops-map.md index 8e88bea066..8d3cbb39c8 100644 --- a/seaweed-block/docs/wiki/testops-map.md +++ b/seaweed-block/docs/wiki/testops-map.md @@ -22,7 +22,7 @@ injection. | Day-1 install | `helm-first-volume-via-sw-block-cli-chain.yaml` | Helm + first PVC | | Multi-volume RF=3 | `helm-multi-volume-rf3-*.yaml` | identity isolation and HA gates | | Restart persistence | `helm-*-restart-*.yaml` | authority and data persistence | -| Failure evidence | `status-endpoint-unreachable-*`, `helm-smartwal-corrupt-restart-chain.yaml` | no false Ready | +| Failure evidence | `status-endpoint-unreachable-*` | no false Ready | | Lifecycle owner | `lifecycle-owner-*.yaml` | admission/action/finalizer boundary | | Cleanup | `cleanup-residue-chain.yaml` and cleanup verifier | zero-residue contract | | Protocol | `iscsi-*`, `nvme-*` | frontend-specific gates | @@ -43,7 +43,6 @@ implementation detail, not a product capability. | Gate | Why it matters | |---|---| -| SmartWAL corruption restart | proves dirty evidence cannot become false Ready | | live node/CSI evidence | prevents node and CSI blockers from being masked | | status API conformance | catches CRD schema/RBAC bugs missed by mocks | | lifecycle-owner admission | proves mutation boundary on a real Kubernetes API | diff --git a/seaweed-block/internal/testops/registration_test.go b/seaweed-block/internal/testops/registration_test.go index e0af02fbba..7ae0061200 100644 --- a/seaweed-block/internal/testops/registration_test.go +++ b/seaweed-block/internal/testops/registration_test.go @@ -377,13 +377,13 @@ func TestISCSIP7BackendFioMatrixRegistrationBuildsShellDriver(t *testing.T) { if _, err := os.Stat(shell.Path); err != nil { t.Fatalf("shell driver path missing: %v", err) } - for _, want := range []string{"summary.md", "walstore/fio.iter*.log", "smartwal/fio.iter*.log"} { + for _, want := range []string{"summary.md", "walstore/fio.iter*.log"} { if !containsString(registration.Artifacts, want) { t.Fatalf("registration artifacts missing %q: %v", want, registration.Artifacts) } } - if got := registration.ScenarioDefaultParams["SW_BLOCK_BACKEND_MATRIX"]; got != "walstore smartwal" { - t.Fatalf("backend matrix default=%q want walstore smartwal", got) + if got := registration.ScenarioDefaultParams["SW_BLOCK_BACKEND_MATRIX"]; got != "walstore" { + t.Fatalf("backend matrix default=%q want walstore", got) } if !containsString(registration.NonClaims, "No product performance claim.") { t.Fatalf("registration must keep performance non-claim: %v", registration.NonClaims) diff --git a/seaweed-block/internal/testops/registry/iscsi-p7-backend-fio-matrix.json b/seaweed-block/internal/testops/registry/iscsi-p7-backend-fio-matrix.json index 91bca5615f..1d0dd15077 100644 --- a/seaweed-block/internal/testops/registry/iscsi-p7-backend-fio-matrix.json +++ b/seaweed-block/internal/testops/registry/iscsi-p7-backend-fio-matrix.json @@ -21,7 +21,7 @@ "scenario_default_params": { "SW_BLOCK_BACKEND_FIO_RUNTIME": "60", "SW_BLOCK_BACKEND_FIO_SIZE": "128m", - "SW_BLOCK_BACKEND_MATRIX": "walstore smartwal" + "SW_BLOCK_BACKEND_MATRIX": "walstore" }, "qa_instruction": "internal/docs/qa-assignments/iscsi-p7-backend-fio-matrix-validation.md", "known_green_commit": "", @@ -33,13 +33,7 @@ "walstore/blockvolume.log", "walstore/fio.iter*.log", "walstore/iscsi-sessions.final.txt", - "walstore/cleanup.log", - "smartwal/run.log", - "smartwal/blockmaster.log", - "smartwal/blockvolume.log", - "smartwal/fio.iter*.log", - "smartwal/iscsi-sessions.final.txt", - "smartwal/cleanup.log" + "walstore/cleanup.log" ], "non_claims": [ "Experimental comparison harness only.", diff --git a/seaweed-block/mkdocs.yml b/seaweed-block/mkdocs.yml index 272e7f2065..39af6e0730 100644 --- a/seaweed-block/mkdocs.yml +++ b/seaweed-block/mkdocs.yml @@ -45,7 +45,6 @@ nav: - Operation Layer v0.5: wiki/deep-dives/operation-layer-v05.md - Status Writer Conformance: wiki/deep-dives/status-writer-conformance.md - ManagedVolume Readiness: wiki/deep-dives/managed-volume-readiness.md - - SmartWAL Dirty Failure: wiki/deep-dives/smartwal-dirty-failure.md - WAL Frontier Recovery: wiki/deep-dives/wal-frontier-recovery.md - blockvolume Process Readiness: wiki/deep-dives/blockvolume-process-readiness.md - Authority And Promotion: wiki/deep-dives/authority-promotion.md diff --git a/seaweed-block/scripts/iterate-m01-nvme.sh b/seaweed-block/scripts/iterate-m01-nvme.sh index 2c04435d9b..dc83d32eb2 100755 --- a/seaweed-block/scripts/iterate-m01-nvme.sh +++ b/seaweed-block/scripts/iterate-m01-nvme.sh @@ -24,7 +24,7 @@ SMB_STAGE_REMOTE="${SMB_STAGE_REMOTE:-/mnt/smb/work/share/t2-sanity/seaweed_bloc REMOTE_BUILD_DIR="${REMOTE_BUILD_DIR:-/tmp/t2m01_sb}" REMOTE_RUN_DIR="${REMOTE_RUN_DIR:-/tmp/t2m01}" SUBSYS_NQN="${SUBSYS_NQN:-nqn.2026-04.m01:v1-r1}" -DURABLE_IMPL="${DURABLE_IMPL:-smartwal}" # smartwal | walstore +DURABLE_IMPL="${DURABLE_IMPL:-walstore}" MATRIX_A_CYCLES="${MATRIX_A_CYCLES:-10}" MATRIX_B_ITERATIONS="${MATRIX_B_ITERATIONS:-50}" ARTIFACT_DIR="${ARTIFACT_DIR:-${SRC_DIR%/*}/seaweedfs/sw-block/design/bugs/001-artifacts}" @@ -273,7 +273,7 @@ log " Matrix D all 5 cycles PASS" # 8. dd read pattern at raw LBA 0 # 9. Verify bytes match pre-kill — byte-exact # -# Variant matrix: DURABLE_IMPL env var selects walstore|smartwal. +# DURABLE_IMPL selects the engine (walstore). log "Matrix E — real SIGKILL crash recovery (canonical G4 kill/restart)" $SSH " diff --git a/seaweed-block/scripts/overview.md b/seaweed-block/scripts/overview.md index 6b64da88fa..db9e6f6fa1 100644 --- a/seaweed-block/scripts/overview.md +++ b/seaweed-block/scripts/overview.md @@ -21,7 +21,7 @@ This directory contains developer and QA helper scripts. | `run-alpha-k8s-dynamic.sh` | Public dynamic PVC alpha smoke entry. | | `run-alpha-app-demo.sh` | App-demo implementation used by `run-k8s-demo.sh`. | | `run-iscsi-os-smoke.sh` | Privileged Linux OS-initiator smoke: `iscsiadm` -> `mkfs.ext4` -> mount -> checksum -> logout on a 256 MiB target. | -| `run-iscsi-backend-fio-matrix.sh` | Privileged Linux OS-initiator backend matrix: runs the same fio workload against `walstore` and `smartwal`, writing per-backend artifacts and an experimental summary. | +| `run-iscsi-backend-fio-matrix.sh` | Privileged Linux OS-initiator backend matrix: runs the same fio workload against each backend (`walstore`), writing per-backend artifacts and an experimental summary. | | `run-iscsi-compat-soak.sh` | Privileged compatibility soak wrapper: runs OS fio repeat and optional K8s fio / attach-detach steps with one summary. | | `run-iscsi-alua-os-smoke.sh` | Privileged Linux OS-initiator smoke for ALUA reporting: `iscsiadm` -> `sg_inq`/`sg_rtpg` -> mount -> checksum -> logout. | | `run-iscsi-alua-multipath-smoke.sh` | Privileged Linux OS-initiator smoke for two iSCSI paths: two portals -> ALUA active/standby evidence -> standby write reject -> `multipath -ll`. | diff --git a/seaweed-block/scripts/run-iscsi-alua-mounted-failover-smoke.sh b/seaweed-block/scripts/run-iscsi-alua-mounted-failover-smoke.sh index 65211ffa7c..df993671c6 100755 --- a/seaweed-block/scripts/run-iscsi-alua-mounted-failover-smoke.sh +++ b/seaweed-block/scripts/run-iscsi-alua-mounted-failover-smoke.sh @@ -158,7 +158,7 @@ start_blockvolume() { --heartbeat-interval 200ms \ --t1-readiness \ --durable-root "$store" \ - --durable-impl smartwal \ + --durable-impl walstore \ --durable-blocks "$BLOCKS" \ --durable-blocksize "$BLOCK_SIZE" \ --iscsi-listen "127.0.0.1:${port}" \ diff --git a/seaweed-block/scripts/run-iscsi-alua-multipath-smoke.sh b/seaweed-block/scripts/run-iscsi-alua-multipath-smoke.sh index eb5d4c6a01..586a6ca4d4 100755 --- a/seaweed-block/scripts/run-iscsi-alua-multipath-smoke.sh +++ b/seaweed-block/scripts/run-iscsi-alua-multipath-smoke.sh @@ -138,7 +138,7 @@ start_blockvolume() { --heartbeat-interval 200ms \ --t1-readiness \ --durable-root "$store" \ - --durable-impl smartwal \ + --durable-impl walstore \ --durable-blocks "$BLOCKS" \ --durable-blocksize "$BLOCK_SIZE" \ --iscsi-listen "127.0.0.1:${port}" \ diff --git a/seaweed-block/scripts/run-iscsi-alua-os-smoke.sh b/seaweed-block/scripts/run-iscsi-alua-os-smoke.sh index 86d57a2689..1ce1abdab0 100755 --- a/seaweed-block/scripts/run-iscsi-alua-os-smoke.sh +++ b/seaweed-block/scripts/run-iscsi-alua-os-smoke.sh @@ -111,7 +111,7 @@ setsid -f "${BIN_DIR}/blockvolume" \ --heartbeat-interval 200ms \ --t1-readiness \ --durable-root "${RUN_DIR}/volume-store" \ - --durable-impl smartwal \ + --durable-impl walstore \ --durable-blocks "$BLOCKS" \ --durable-blocksize "$BLOCK_SIZE" \ --iscsi-listen "127.0.0.1:${PORT}" \ diff --git a/seaweed-block/scripts/run-iscsi-backend-fio-matrix.sh b/seaweed-block/scripts/run-iscsi-backend-fio-matrix.sh index 0210b0f413..1b9b7caecf 100755 --- a/seaweed-block/scripts/run-iscsi-backend-fio-matrix.sh +++ b/seaweed-block/scripts/run-iscsi-backend-fio-matrix.sh @@ -6,7 +6,7 @@ RUN_ID="${RUN_ID:-$(date -u +%Y%m%dT%H%M%SZ)}" WORK_DIR="${SW_BLOCK_BACKEND_MATRIX_WORK_DIR:-/tmp/sw-block-backend-matrix}" ARTIFACT_ROOT="${SW_BLOCK_ARTIFACT_DIR:-${WORK_DIR}/runs/${RUN_ID}}" BIN_DIR="${SW_BLOCK_BIN_DIR:-${WORK_DIR}/bin}" -BACKENDS="${SW_BLOCK_BACKEND_MATRIX:-walstore smartwal}" +BACKENDS="${SW_BLOCK_BACKEND_MATRIX:-walstore}" FIO_RUNTIME="${SW_BLOCK_BACKEND_FIO_RUNTIME:-60}" FIO_SIZE="${SW_BLOCK_BACKEND_FIO_SIZE:-128m}" BASE_ISCSI_PORT="${SW_BLOCK_BACKEND_BASE_ISCSI_PORT:-3290}" @@ -57,10 +57,10 @@ idx=0 overall=0 for backend in $BACKENDS; do case "$backend" in - walstore|smartwal) + walstore) ;; *) - echo "unsupported backend ${backend}; want walstore or smartwal" >&2 + echo "unsupported backend ${backend}; want walstore" >&2 exit 2 ;; esac diff --git a/seaweed-block/scripts/run-iscsi-os-smoke.sh b/seaweed-block/scripts/run-iscsi-os-smoke.sh index 865bda3476..c5e028859c 100755 --- a/seaweed-block/scripts/run-iscsi-os-smoke.sh +++ b/seaweed-block/scripts/run-iscsi-os-smoke.sh @@ -18,7 +18,7 @@ CHAP_BAD_SECRET="${SW_BLOCK_ISCSI_CHAP_BAD_SECRET:-}" MOUNT_DIR="${SW_BLOCK_ISCSI_MOUNT_DIR:-${WORK_DIR}/mnt}" BLOCKS="${SW_BLOCK_DURABLE_BLOCKS:-65536}" # 256 MiB at 4 KiB. BLOCK_SIZE="${SW_BLOCK_DURABLE_BLOCKSIZE:-4096}" -DURABLE_IMPL="${SW_BLOCK_DURABLE_IMPL:-smartwal}" +DURABLE_IMPL="${SW_BLOCK_DURABLE_IMPL:-walstore}" ITERATIONS="${SW_BLOCK_ISCSI_ITERATIONS:-1}" STRESS="${SW_BLOCK_ISCSI_STRESS:-none}" # none | fio | dd FIO_SIZE="${SW_BLOCK_ISCSI_FIO_SIZE:-32m}" diff --git a/seaweed-block/scripts/run-nvme-mounted-failover-smoke.sh b/seaweed-block/scripts/run-nvme-mounted-failover-smoke.sh index eb58627549..c91f77ef99 100755 --- a/seaweed-block/scripts/run-nvme-mounted-failover-smoke.sh +++ b/seaweed-block/scripts/run-nvme-mounted-failover-smoke.sh @@ -15,7 +15,7 @@ SUBSYS_NQN="${SW_BLOCK_NVME_NQN:-nqn.2026-05.io.seaweedfs:failover-v1}" NSID="${SW_BLOCK_NVME_NSID:-1}" BLOCKS="${SW_BLOCK_DURABLE_BLOCKS:-65536}" BLOCK_SIZE="${SW_BLOCK_DURABLE_BLOCKSIZE:-4096}" -DURABLE_IMPL="${SW_BLOCK_DURABLE_IMPL:-smartwal}" +DURABLE_IMPL="${SW_BLOCK_DURABLE_IMPL:-walstore}" BIN_DIR="${SW_BLOCK_BIN_DIR:-${WORK_DIR}/bin}" RUN_DIR="${WORK_DIR}/run" MOUNT_DIR="${SW_BLOCK_NVME_MOUNT_DIR:-${WORK_DIR}/mnt}" diff --git a/seaweed-block/scripts/run-nvme-multipath-smoke.sh b/seaweed-block/scripts/run-nvme-multipath-smoke.sh index 0bc315ccf0..386c4f9959 100755 --- a/seaweed-block/scripts/run-nvme-multipath-smoke.sh +++ b/seaweed-block/scripts/run-nvme-multipath-smoke.sh @@ -9,7 +9,7 @@ SUBSYS_NQN="${SW_BLOCK_NVME_NQN:-nqn.2026-05.io.seaweedfs:mpath-v1}" NSID="${SW_BLOCK_NVME_NSID:-1}" BLOCKS="${SW_BLOCK_DURABLE_BLOCKS:-65536}" BLOCK_SIZE="${SW_BLOCK_DURABLE_BLOCKSIZE:-4096}" -DURABLE_IMPL="${SW_BLOCK_DURABLE_IMPL:-smartwal}" +DURABLE_IMPL="${SW_BLOCK_DURABLE_IMPL:-walstore}" BIN_DIR="${SW_BLOCK_BIN_DIR:-${WORK_DIR}/bin}" RUN_DIR="${WORK_DIR}/run" diff --git a/seaweed-block/scripts/run-nvme-os-smoke.sh b/seaweed-block/scripts/run-nvme-os-smoke.sh index a11d77c978..a36500c2b6 100755 --- a/seaweed-block/scripts/run-nvme-os-smoke.sh +++ b/seaweed-block/scripts/run-nvme-os-smoke.sh @@ -10,7 +10,7 @@ NSID="${SW_BLOCK_NVME_NSID:-1}" MOUNT_DIR="${SW_BLOCK_NVME_MOUNT_DIR:-${WORK_DIR}/mnt}" BLOCKS="${SW_BLOCK_DURABLE_BLOCKS:-65536}" # 256 MiB at 4 KiB. BLOCK_SIZE="${SW_BLOCK_DURABLE_BLOCKSIZE:-4096}" -DURABLE_IMPL="${SW_BLOCK_DURABLE_IMPL:-smartwal}" +DURABLE_IMPL="${SW_BLOCK_DURABLE_IMPL:-walstore}" ITERATIONS="${SW_BLOCK_NVME_ITERATIONS:-1}" STRESS="${SW_BLOCK_NVME_STRESS:-none}" # none | fio | dd FIO_SIZE="${SW_BLOCK_NVME_FIO_SIZE:-32m}" diff --git a/seaweed-block/scripts/run-phase101-nvme-stage-unstage-gate.sh b/seaweed-block/scripts/run-phase101-nvme-stage-unstage-gate.sh index ada986d70d..9d698d09b2 100644 --- a/seaweed-block/scripts/run-phase101-nvme-stage-unstage-gate.sh +++ b/seaweed-block/scripts/run-phase101-nvme-stage-unstage-gate.sh @@ -11,7 +11,7 @@ NSID="${SW_BLOCK_NVME_NSID:-1}" CYCLES="${SW_BLOCK_NVME_STAGE_CYCLES:-3}" BLOCKS="${SW_BLOCK_DURABLE_BLOCKS:-4096}" BLOCK_SIZE="${SW_BLOCK_DURABLE_BLOCKSIZE:-4096}" -DURABLE_IMPL="${SW_BLOCK_DURABLE_IMPL:-smartwal}" +DURABLE_IMPL="${SW_BLOCK_DURABLE_IMPL:-walstore}" BIN_DIR="${SW_BLOCK_BIN_DIR:-${WORK_DIR}/bin}" RUN_DIR="${WORK_DIR}/run" diff --git a/seaweed-block/scripts/run-phase163-nvme-rdma-standalone-live-gate.sh b/seaweed-block/scripts/run-phase163-nvme-rdma-standalone-live-gate.sh index 2d7ad17067..496ae53fff 100644 --- a/seaweed-block/scripts/run-phase163-nvme-rdma-standalone-live-gate.sh +++ b/seaweed-block/scripts/run-phase163-nvme-rdma-standalone-live-gate.sh @@ -112,7 +112,7 @@ sudo "${BIN}/blockvolume" \ --heartbeat-interval 200ms \ --t1-readiness \ --durable-root "${WORK}/volume-store" \ - --durable-impl smartwal \ + --durable-impl walstore \ --durable-blocks 8192 \ --durable-blocksize 4096 \ --nvme-listen "${TARGET_IP}:${TARGET_PORT}" \ diff --git a/seaweed-block/scripts/run-phase164-nvme-rdma-standalone-hardening-gate.sh b/seaweed-block/scripts/run-phase164-nvme-rdma-standalone-hardening-gate.sh index 8b2066ce56..a9c833bf9b 100644 --- a/seaweed-block/scripts/run-phase164-nvme-rdma-standalone-hardening-gate.sh +++ b/seaweed-block/scripts/run-phase164-nvme-rdma-standalone-hardening-gate.sh @@ -144,7 +144,7 @@ start_volume() { --heartbeat-interval 200ms \ --t1-readiness \ --durable-root "${storage_root}" \ - --durable-impl smartwal \ + --durable-impl walstore \ --durable-blocks 8192 \ --durable-blocksize 4096 \ --nvme-listen "${TARGET_IP}:${rdma_port}" \ @@ -300,7 +300,7 @@ sudo "${BIN}/blockvolume" \ --master "127.0.0.1:${MASTER_PORT}" --server-id s1 --volume-id v1 --replica-id r1 \ --data-addr "127.0.0.1:${BAD_DATA_PORT}" --ctrl-addr "127.0.0.1:${BAD_CTRL_PORT}" \ --status-addr "127.0.0.1:${BAD_STATUS_PORT}" --heartbeat-interval 200ms --t1-readiness \ - --durable-root "${WORK}/bad-store" --durable-impl smartwal --durable-blocks 8192 --durable-blocksize 4096 \ + --durable-root "${WORK}/bad-store" --durable-impl walstore --durable-blocks 8192 --durable-blocksize 4096 \ --nvme-listen "${INVALID_TARGET_IP}:${RDMA_PORT_BAD}" --nvme-transport rdma --allow-external-nvme-bind \ --nvme-subsysnqn "${NQN_BAD}" --nvme-ns 1 \ >"${ARTIFACT_DIR}/startup-rollback.log" 2>&1 & diff --git a/seaweed-block/scripts/run-phase167-parallel-wal-candidate-gate.sh b/seaweed-block/scripts/run-phase167-parallel-wal-candidate-gate.sh deleted file mode 100755 index ec4b151a37..0000000000 --- a/seaweed-block/scripts/run-phase167-parallel-wal-candidate-gate.sh +++ /dev/null @@ -1,228 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -ROOT="${1:-$(pwd)}" -ARTIFACT_DIR="${SW_BLOCK_ARTIFACT_DIR:-${ROOT}/results/phase167-parallel-wal-candidate-gate}" -SUMMARY="${ARTIFACT_DIR}/phase167-parallel-wal-candidate-summary.txt" -BENCH="${ARTIFACT_DIR}/parallel-wal-contention-benchmark.txt" -BENCHTIME="${SW_BLOCK_PHASE167_PARALLEL_WAL_BENCHTIME:-1000x}" - -mkdir -p "${ARTIFACT_DIR}" -: >"${SUMMARY}" - -write_summary() { - echo "$*" | tee -a "${SUMMARY}" >/dev/null -} - -metric() { - local benchmark="$1" - local writers="$2" - local unit="$3" - awk -v prefix="${benchmark}/writers_${writers}-" -v unit="${unit}" ' - index($1, prefix) == 1 { - for (i = 2; i <= NF; i++) { - if ($(i + 1) == unit) { - print $i - exit - } - } - } - ' "${BENCH}" -} - -require_metric() { - local value - value="$(metric "$1" "$2" "$3")" - if [[ -z "${value}" ]]; then - echo "missing metric benchmark=$1 writers=$2 unit=$3" >&2 - exit 1 - fi - printf '%s' "${value}" -} - -ratio() { - awk -v numerator="$1" -v denominator="$2" 'BEGIN { - if (numerator <= 0 || denominator <= 0) exit 1 - printf "%.3f", numerator / denominator - }' -} - -if [[ ! "${BENCHTIME}" =~ ^[0-9]+x$ ]]; then - echo "SW_BLOCK_PHASE167_PARALLEL_WAL_BENCHTIME must be a fixed iteration count" >&2 - exit 1 -fi -iterations="${BENCHTIME%x}" -if (( iterations < 512 || iterations > 8192 )); then - echo "benchmark iterations must be between 512 and 8192" >&2 - exit 1 -fi - -write_summary "phase167_parallel_wal_candidate_status=running" -write_summary "candidate=parallel-walstore" -write_summary "candidate_default=false" -write_summary "mounted_nvme_claim_allowed=false" -write_summary "performance_claim_allowed=false" - -cd "${ROOT}" -go test ./core/storage ./core/storage/parallelwal ./core/recovery ./core/transport \ - ./core/frontend/durable ./core/launcher ./cmd/blockvolume ./cmd/blockmaster \ - -count=1 >"${ARTIFACT_DIR}/affected-tests.log" 2>&1 -write_summary "affected_tests=pass" - -if command -v helm >/dev/null 2>&1; then - helm lint charts/seaweed-block \ - --set compat.launcherDurableImplFlag=true \ - --set blockmaster.durableImpl=parallel-walstore \ - >"${ARTIFACT_DIR}/helm-lint.log" 2>&1 - write_summary "helm_validation=lint" -else - python - <<'PY' >"${ARTIFACT_DIR}/helm-lint.log" -import json - -with open("charts/seaweed-block/values.schema.json", encoding="utf-8") as handle: - schema = json.load(handle) -allowed = schema["properties"]["blockmaster"]["properties"]["durableImpl"]["enum"] -if "parallel-walstore" not in allowed: - raise SystemExit("parallel-walstore is absent from blockmaster.durableImpl enum") -print("schema enum accepts parallel-walstore; helm binary unavailable") -PY - write_summary "helm_validation=schema_only_no_helm" -fi -write_summary "helm_candidate_schema=pass" - -go test ./core/storage/parallelwal \ - -run 'Test(CreateSyncRecoverAndScan|CrossLaneCompletionPublishesContiguousLSNs|SyncFencesWritesAdmittedBeforeCall|LowerLSNFailureBlocksCompletedHigherLane|CloseDrainsActiveAppenderAfterTerminalFailure|RecoverRejectsActiveAppender|UnsyncedTailIgnoredAfterCrash|OpenFallsBackFromCorruptLatestHeader|CommittedRecordCorruptionFailsClosed|RecoveryRejectsInvalidCommittedRecordSemantics|ApplyEntryAcceptsSourceFrontierJump|FailedApplyEntryDoesNotPublishSourceFrontierJump|SourceFrontierJumpPersistsWithoutFalseCheckpoint|ConcurrentSameLBAWritesRemainOrdered|WriteBatchDispatchesAcrossLanesBeforePublishing|ConcurrentSameLaneWritesCoalesceWALAppends|WriteBatchSplitsWALAppendAtRingWrap|WriteBatchRingWrapSecondChunkFailureIsNotDurable|RecycleStablePrefixCoalescesIntegrityReads|RecycleBatchedReadDetectsCorruptRecord|RingWrapRecyclesOnlyCheckpointedPrefix|AdvancedWALTailBeyondHeadSurvivesRecovery|RecoverReplaysDurableWALBeforeCheckpoint|DirectExtentFrontierPersistsWithoutSyntheticWAL|RetainedPreCheckpointWALDoesNotOverrideRebuiltExtent|BaseExtentHeaderFailureKeepsPriorAcknowledgedExtent|BeginBaseInstallClearsAbortedStage|AdvanceFrontierWithoutBaseStageKeepsExistingData|NextBaseStagePreservesHeaderFallbackToCurrentExtent|RecycledSlotsRemainRecoverableThroughHeaderFallback|HeaderValidationRejectsWrappedRecordSize)$' \ - -count=50 >"${ARTIFACT_DIR}/correctness-stress.log" 2>&1 -write_summary "correctness_stress=pass" -write_summary "dual_crc_header_fallback=pass" -write_summary "sync_admission_fence=pass" -write_summary "contiguous_completion_frontier=pass" -write_summary "lower_lsn_failure_fail_closed=pass" -write_summary "terminal_append_drain=pass" -write_summary "same_lane_wal_append_coalescing=pass" -write_summary "ring_wrap_batched_append_recovery=pass" -write_summary "ring_wrap_second_chunk_failure_fail_closed=pass" -write_summary "batched_recycle_crc_validation=pass" -write_summary "unsynced_tail_ignored=pass" -write_summary "committed_crc_corruption_fail_closed=pass" -write_summary "ring_wrap_retention=pass" -write_summary "stable_prefix_checkpoint=pass" -write_summary "rebuild_extent_precedence=pass" -write_summary "rebuild_cow_extent_commit=pass" -write_summary "failed_rebuild_keeps_acknowledged_extent=pass" -write_summary "aborted_rebuild_stage_reset=pass" -write_summary "reused_extent_header_fallback=pass" -write_summary "recycled_slot_header_fallback=pass" -write_summary "logical_storage_contract=pass" -write_summary "failed_source_jump_not_published=pass" -write_summary "source_jump_retention_floor=pass" -write_summary "record_semantics_validation=pass" -write_summary "persisted_geometry_overflow_validation=pass" -write_summary "partial_rmw_serialized=pass" - -if command -v strace >/dev/null 2>&1 && [[ "$(go env GOOS)" == "linux" ]]; then - syscall_test_bin="${ARTIFACT_DIR}/parallelwal-syscall.test" - go test -c -o "${syscall_test_bin}" ./core/storage/parallelwal - strace -qq -f -e trace=pwrite64 \ - -o "${ARTIFACT_DIR}/wal-append-coalescing.strace" \ - "${syscall_test_bin}" \ - -test.run '^TestConcurrentSameLaneWritesCoalesceWALAppends$' \ - -test.count=1 >"${ARTIFACT_DIR}/wal-append-coalescing-test.log" 2>&1 - append_pwrite_calls="$(grep -c 'pwrite64(' "${ARTIFACT_DIR}/wal-append-coalescing.strace" || true)" - awk -v value="${append_pwrite_calls}" 'BEGIN { if (value <= 0 || value >= 8) exit 1 }' - - strace -qq -f -e trace=pread64 \ - -o "${ARTIFACT_DIR}/wal-recycle-coalescing.strace" \ - "${syscall_test_bin}" \ - -test.run '^TestRecycleStablePrefixCoalescesIntegrityReads$' \ - -test.count=1 >"${ARTIFACT_DIR}/wal-recycle-coalescing-test.log" 2>&1 - recycle_pread_calls="$(grep -c 'pread64(' "${ARTIFACT_DIR}/wal-recycle-coalescing.strace" || true)" - awk -v value="${recycle_pread_calls}" 'BEGIN { if (value <= 0 || value >= 8) exit 1 }' - - write_summary "external_syscall_validation=strace" - write_summary "external_append_pwrite_calls=${append_pwrite_calls}" - write_summary "external_recycle_pread_calls=${recycle_pread_calls}" -else - write_summary "external_syscall_validation=not_available" -fi - -go test ./core/storage/parallelwal \ - -run '^$' \ - -bench '^BenchmarkPhase167(ParallelWALContention|ParallelWALBatchContention|LegacyWALContentionControl|LegacyWALBatchContentionControl)$' \ - -benchtime="${BENCHTIME}" \ - -count=1 >"${BENCH}" 2>&1 - -for writers in 1 2 4 8; do - candidate_mibps="$(require_metric BenchmarkPhase167ParallelWALContention "${writers}" MB/s)" - candidate_p99="$(require_metric BenchmarkPhase167ParallelWALContention "${writers}" p99_ns)" - active_lanes="$(require_metric BenchmarkPhase167ParallelWALContention "${writers}" active_lanes)" - checkpoint_write_ops="$(require_metric BenchmarkPhase167ParallelWALContention "${writers}" checkpoint_write_ops)" - recycle_read_ops="$(require_metric BenchmarkPhase167ParallelWALContention "${writers}" recycle_read_ops)" - wal_write_ops="$(require_metric BenchmarkPhase167ParallelWALContention "${writers}" wal_write_ops)" - wal_tail="$(require_metric BenchmarkPhase167ParallelWALContention "${writers}" wal_tail)" - legacy_mibps="$(require_metric BenchmarkPhase167LegacyWALContentionControl "${writers}" MB/s)" - write_summary "candidate_writers_${writers}_mibps=${candidate_mibps}" - write_summary "candidate_writers_${writers}_p99_ns=${candidate_p99}" - write_summary "candidate_writers_${writers}_active_lanes=${active_lanes}" - write_summary "candidate_writers_${writers}_checkpoint_write_ops=${checkpoint_write_ops}" - write_summary "candidate_writers_${writers}_recycle_read_ops=${recycle_read_ops}" - write_summary "candidate_writers_${writers}_wal_write_ops=${wal_write_ops}" - write_summary "candidate_writers_${writers}_wal_tail=${wal_tail}" - write_summary "legacy_writers_${writers}_mibps=${legacy_mibps}" -done - -active_four="$(require_metric BenchmarkPhase167ParallelWALContention 4 active_lanes)" -awk -v value="${active_four}" 'BEGIN { if (value < 2) exit 1 }' -write_summary "multiple_lanes_observed=true" -wal_tail_four="$(require_metric BenchmarkPhase167ParallelWALContention 4 wal_tail)" -awk -v value="${wal_tail_four}" 'BEGIN { if (value <= 1) exit 1 }' -write_summary "steady_state_recycle_observed=true" -checkpoint_ops_four="$(require_metric BenchmarkPhase167ParallelWALContention 4 checkpoint_write_ops)" -awk -v value="${checkpoint_ops_four}" -v writes="${iterations}" 'BEGIN { - if (value <= 0 || value >= writes / 16) exit 1 -}' -write_summary "checkpoint_write_coalescing_observed=true" -batch_mibps_four="$(require_metric BenchmarkPhase167ParallelWALBatchContention 4 MB/s)" -batch_blocks_four="$(require_metric BenchmarkPhase167ParallelWALBatchContention 4 batch_blocks)" -batch_recycle_read_ops_four="$(require_metric BenchmarkPhase167ParallelWALBatchContention 4 recycle_read_ops)" -batch_wal_ops_four="$(require_metric BenchmarkPhase167ParallelWALBatchContention 4 wal_write_ops)" -legacy_batch_mibps_four="$(require_metric BenchmarkPhase167LegacyWALBatchContentionControl 4 MB/s)" -batch_vs_legacy="$(ratio "${batch_mibps_four}" "${legacy_batch_mibps_four}")" -write_summary "candidate_batch_writers_4_mibps=${batch_mibps_four}" -write_summary "candidate_batch_writers_4_blocks=${batch_blocks_four}" -write_summary "candidate_batch_writers_4_recycle_read_ops=${batch_recycle_read_ops_four}" -write_summary "candidate_batch_writers_4_wal_write_ops=${batch_wal_ops_four}" -write_summary "legacy_batch_writers_4_mibps=${legacy_batch_mibps_four}" -write_summary "candidate_batch_four_writer_vs_legacy_ratio=${batch_vs_legacy}" -awk -v value="${batch_wal_ops_four}" -v writes="${iterations}" -v blocks="${batch_blocks_four}" 'BEGIN { - if (value <= 0 || value >= writes * blocks / 2) exit 1 -}' -write_summary "wal_append_coalescing_observed=true" -awk -v value="${batch_recycle_read_ops_four}" -v writes="${iterations}" -v blocks="${batch_blocks_four}" 'BEGIN { - if (value <= 0 || value >= writes * blocks / 16) exit 1 -}' -write_summary "wal_recycle_read_coalescing_observed=true" - -candidate_1="$(require_metric BenchmarkPhase167ParallelWALContention 1 MB/s)" -candidate_4="$(require_metric BenchmarkPhase167ParallelWALContention 4 MB/s)" -legacy_1="$(require_metric BenchmarkPhase167LegacyWALContentionControl 1 MB/s)" -legacy_4="$(require_metric BenchmarkPhase167LegacyWALContentionControl 4 MB/s)" -single_ratio="$(ratio "${candidate_1}" "${legacy_1}")" -four_scaling="$(ratio "${candidate_4}" "${candidate_1}")" -four_vs_legacy="$(ratio "${candidate_4}" "${legacy_4}")" -write_summary "candidate_single_writer_vs_legacy_ratio=${single_ratio}" -write_summary "candidate_four_writer_scaling_ratio=${four_scaling}" -write_summary "candidate_four_writer_vs_legacy_ratio=${four_vs_legacy}" - -claim_allowed="$( - awk -v single="${single_ratio}" -v scaling="${four_scaling}" 'BEGIN { - if (single >= 0.90 && scaling >= 1.50) print "true"; else print "false" - }' -)" -write_summary "performance_claim_allowed=${claim_allowed}" -if [[ "${claim_allowed}" == "true" ]]; then - write_summary "next_recommendation=rf3_and_mounted_candidate_gate" -else - write_summary "next_recommendation=local_execution_backend_redesign" -fi -write_summary "phase167_parallel_wal_candidate_status=ok" diff --git a/seaweed-block/scripts/test_phase163_backend_write_proof.py b/seaweed-block/scripts/test_phase163_backend_write_proof.py index f4b0bb1088..f6f8c31e22 100644 --- a/seaweed-block/scripts/test_phase163_backend_write_proof.py +++ b/seaweed-block/scripts/test_phase163_backend_write_proof.py @@ -15,7 +15,7 @@ class BackendProofTest(unittest.TestCase): 'address': '127.0.0.1:16334', 'status': {'Volumes': [{ 'VolumeID': 'v1', 'ReplicaID': 'r1', 'Epoch': 4, 'EndpointVersion': 2, 'Latched': True, 'Operational': True, 'Closed': False, - 'Path': '/tmp/run/store/v1', 'Impl': 'smartwal', + 'Path': '/tmp/run/store/v1', 'Impl': 'walstore', 'WriteProfile': {'BackendWriteOps': 7, 'BackendWriteBytes': 28672, 'BackendStorageWriteCalls': 7}}]}} self.after = copy.deepcopy(self.before) diff --git a/seaweed-block/testops/scenarios/helm-smartwal-corrupt-restart-chain.yaml b/seaweed-block/testops/scenarios/helm-smartwal-corrupt-restart-chain.yaml deleted file mode 100644 index 0c280ce9ac..0000000000 --- a/seaweed-block/testops/scenarios/helm-smartwal-corrupt-restart-chain.yaml +++ /dev/null @@ -1,325 +0,0 @@ -# Phase 34 D4: live SmartWAL dirty-failure gate. -# -# Goal: -# Prove a dirty storage fault is real evidence, not a self-proof grep: -# Helm installs blockvolumes with smartwal + hostPath, first PVC writes data, -# TestOps corrupts a real SmartWAL WAL record, then the product restarts and -# must not report false Ready=True from corrupted evidence. -# -# Expected current behavior: -# This gate is allowed to fail if the product does not yet surface a stable -# WAL-corruption reason. A green run is valid only if the corruption evidence -# exists and no status surface claims Ready=True afterward. - -name: helm-smartwal-corrupt-restart-chain -timeout: 32m - -env: - product_root: "/tmp/seaweed_block" - ssh_key: "C:\\work\\dev_server\\testdev_key" - helm_release: "sw-block" - helm_namespace: "kube-system" - single_node: "m02" - sw_block_image: "sw-block:local" - sw_block_csi_image: "sw-block-csi:local" - -topology: - nodes: - m02: - host: 192.168.1.184 - user: testdev - key: "{{ ssh_key }}" - -phases: - - name: pre_clean - actions: - - action: pre_run_cleanup - node: m02 - kill_patterns: "blockmaster,blockvolume,blockcsi,iscsi-target" - nvme_disconnect: "true" - iscsi_logout_prefix: "iqn.2026-05.io.seaweedfs" - - action: exec - node: m02 - timeout: 5m - cmd: "helm status {{ helm_release }} --namespace {{ helm_namespace }} >/dev/null 2>&1 && helm uninstall {{ helm_release }} --namespace {{ helm_namespace }} --wait --timeout 180s || true; kubectl -n default delete pod sw-block-example-reader sw-block-example-writer --ignore-not-found=true --wait=true --timeout=120s; kubectl -n default delete pvc sw-block-example-pvc --ignore-not-found=true --wait=true --timeout=120s; kubectl delete storageclass sw-block-example --ignore-not-found=true --wait=true --timeout=120s; kubectl delete clusterrole/sw-block-csi clusterrolebinding/sw-block-csi --ignore-not-found=true; sudo -n iscsiadm -m node 2>/dev/null | awk '/io.seaweedfs/ {print $1, $2}' | while read portal target; do sudo -n iscsiadm -m node -T \"$target\" -p \"$portal\" -o delete || true; done; sudo -n rm -rf /var/lib/sw-block/testops-{{ run_id }}-smartwal-corrupt; rm -rf /mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt && mkdir -p /mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/bin /mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/values /mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/install /mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/basic-app /mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/corrupt /mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/after-corrupt /mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/cleanup" - env.KUBECONFIG: "/etc/rancher/k3s/k3s.yaml" - - action: assert_no_active_iscsi_sessions - node: m02 - iqn_substr: "io.seaweedfs" - - action: assert_no_processes - node: m02 - pattern: "[/]blockmaster --|[/]blockvolume --|[/]blockcsi |[/]iscsi-target |^blockmaster |^blockvolume |^blockcsi |^iscsi-target " - - - name: build_tools_and_images - actions: - - action: exec - node: m02 - timeout: 8m - cmd: "cd {{ product_root }} && go build -o /mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/bin/sw-block ./cmd/sw-block && go build -o /mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/bin/sw-block-testutil ./cmd/sw-block-testutil && bash scripts/build-alpha-images.sh {{ product_root }}" - env.SW_BLOCK_IMPORT_K3S: "1" - env.SW_BLOCK_ARTIFACT_DIR: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/build" - - action: grep_log - node: m02 - path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/build/alpha-images.env" - pattern: "SW_BLOCK_IMAGE_ID=" - save_as: image_id_count - - action: assert_greater - actual: "{{ image_id_count }}" - threshold: "0" - - - name: generate_smartwal_values - actions: - - action: exec - node: m02 - timeout: 3m - cmd: | - set -e - out=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/values - /mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/bin/sw-block ops generate-helm-values \ - --kubeconfig /etc/rancher/k3s/k3s.yaml \ - --out "$out/values.smartwal.yaml" \ - --image {{ sw_block_image }} \ - --csi-image {{ sw_block_csi_image }} \ - --target-node {{ single_node }} \ - --node-limit 1 \ - --restart-persistence hostpath \ - --state-hostpath /var/lib/sw-block/testops-{{ run_id }}-smartwal-corrupt > "$out/generate.stdout.txt" - python3 - "$out/values.smartwal.yaml" <<'PY' - import sys - from pathlib import Path - path = Path(sys.argv[1]) - lines = path.read_text(encoding="utf-8").splitlines() - out = [] - inserted = False - for line in lines: - stripped = line.strip() - if stripped.startswith("durableImpl:"): - indent = line[: len(line) - len(line.lstrip())] - out.append(f"{indent}durableImpl: smartwal") - inserted = True - continue - out.append(line) - if not inserted and line.rstrip() == "blockmaster:": - out.append(" durableImpl: smartwal") - out.append(" nodeSelector:") - out.append(" kubernetes.io/hostname: {{ single_node }}") - inserted = True - if not inserted: - raise SystemExit("blockmaster block not found; cannot set durableImpl") - path.write_text("\n".join(out) + "\n", encoding="utf-8") - PY - env.KUBECONFIG: "/etc/rancher/k3s/k3s.yaml" - - action: grep_log - node: m02 - path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/values/values.smartwal.yaml" - pattern: "durableImpl: smartwal" - save_as: durable_impl_smartwal_count - - action: assert_greater - actual: "{{ durable_impl_smartwal_count }}" - threshold: "0" - - - name: helm_install_stack - actions: - - action: exec - node: m02 - timeout: 10m - cmd: "cd {{ product_root }} && helm lint charts/seaweed-block -f /mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/values/values.smartwal.yaml > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/install/helm-lint.txt && helm template {{ helm_release }} charts/seaweed-block -f /mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/values/values.smartwal.yaml > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/install/helm-template.yaml && grep -q -- '--launcher-durable-impl=smartwal' /mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/install/helm-template.yaml && helm install {{ helm_release }} charts/seaweed-block --namespace {{ helm_namespace }} --create-namespace -f /mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/values/values.smartwal.yaml --wait --timeout 10m > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/install/helm-install.txt && kubectl -n {{ helm_namespace }} rollout status deploy/sw-blockmaster --timeout=180s && kubectl -n {{ helm_namespace }} rollout status deploy/sw-block-csi-controller --timeout=180s && kubectl -n {{ helm_namespace }} rollout status ds/sw-block-csi-node --timeout=180s" - env.KUBECONFIG: "/etc/rancher/k3s/k3s.yaml" - - action: grep_log - node: m02 - path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/install/helm-install.txt" - pattern: "STATUS: deployed" - save_as: helm_deployed_count - - action: assert_greater - actual: "{{ helm_deployed_count }}" - threshold: "0" - - - name: first_volume_before_corruption - actions: - - action: exec - node: m02 - timeout: 10m - cmd: "cd {{ product_root }} && bash scripts/run-basic-app-example.sh {{ product_root }}" - env.KUBECONFIG: "/etc/rancher/k3s/k3s.yaml" - env.SW_BLOCK_ARTIFACT_DIR: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/basic-app" - env.SW_BLOCK_BASIC_APP_CLEANUP: "0" - env.SW_BLOCK_BASIC_APP_NODE_SELECTOR: "{{ single_node }}" - env.SW_BLOCK_INSTALL_MODE: "helm-single-node-smartwal-corrupt" - env.SW_BLOCK_HELM_RELEASE: "{{ helm_release }}" - env.SW_BLOCK_HELM_NAMESPACE: "{{ helm_namespace }}" - env.SW_BLOCK_HELM_VALUES_FILE: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/values/values.smartwal.yaml" - - action: grep_log - node: m02 - path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/basic-app/first-volume-summary.txt" - pattern: "^first_volume_status=ok$" - save_as: first_volume_ok_count - - action: assert_greater - actual: "{{ first_volume_ok_count }}" - threshold: "0" - - - name: corrupt_smartwal_and_reconcile - actions: - - action: exec - node: m02 - timeout: 8m - cmd: | - set -e - root=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt - out="$root/corrupt" - summary="$root/basic-app/first-volume-summary.txt" - vol=$(sed -n 's/^volume_id=//p' "$summary" | head -1) - test -n "$vol" - deploy=$(kubectl -n default get deploy -l app=sw-blockvolume,sw-block.seaweedfs.com/volume="$vol" -o jsonpath='{.items[0].metadata.name}') - test -n "$deploy" - store="/var/lib/sw-block/testops-{{ run_id }}-smartwal-corrupt/${vol}/r1/${vol}.bin" - echo "volume_id=$vol" > "$out/corrupt-context.txt" - echo "deployment=$deploy" >> "$out/corrupt-context.txt" - echo "store=$store" >> "$out/corrupt-context.txt" - test -f "$store" - kubectl -n default delete pod sw-block-example-reader sw-block-example-writer --ignore-not-found=true --wait=true --timeout=120s - kubectl -n default scale "deploy/$deploy" --replicas=0 - for i in $(seq 1 120); do - pods=$(kubectl -n default get pod -l sw-block.seaweedfs.com/volume="$vol" -o name 2>/dev/null | wc -l | tr -d ' ') - test "$pods" = "0" && break - sleep 1 - done - pods=$(kubectl -n default get pod -l sw-block.seaweedfs.com/volume="$vol" -o name 2>/dev/null | wc -l | tr -d ' ') - echo "pods_after_scale_zero=$pods" >> "$out/corrupt-context.txt" - test "$pods" = "0" - sudo -n /mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/bin/sw-block-testutil smartwal-corrupt-latest-record --path "$store" --out "$out" > "$out/smartwal-corruption.stdout.txt" 2> "$out/smartwal-corruption.stderr.txt" - kubectl -n default scale "deploy/$deploy" --replicas=1 - deployment_restarted=false - deployment_rollout_ready=false - for i in $(seq 1 180); do - if kubectl -n default get pod -l sw-block.seaweedfs.com/volume="$vol" -o name 2>/dev/null | grep -q .; then - deployment_restarted=true - fi - ready=$(kubectl -n default get "deploy/$deploy" -o jsonpath='{.status.readyReplicas}' 2>/dev/null || true) - if test "$ready" = "1"; then - deployment_rollout_ready=true - break - fi - sleep 1 - done - echo "deployment_restarted=$deployment_restarted" >> "$out/corrupt-context.txt" - echo "deployment_rollout_ready=$deployment_rollout_ready" >> "$out/corrupt-context.txt" - test "$deployment_restarted" = "true" - kubectl -n default rollout status "deploy/$deploy" --timeout=5s > "$out/wait-blockvolume-after-corrupt.txt" 2>&1 || true - kubectl -n default get pods,deploy,pvc,pv -o wide > "$out/default.after-corrupt.txt" - kubectl -n {{ helm_namespace }} get pods,deploy,svc -o wide > "$out/kube-system.after-corrupt.txt" - kubectl -n default describe "deploy/$deploy" > "$out/blockvolume-deploy.describe.txt" 2>&1 || true - kubectl -n default logs -l sw-block.seaweedfs.com/volume="$vol" --all-containers --tail=200 > "$out/blockvolume-pods.log" 2>&1 || true - env.KUBECONFIG: "/etc/rancher/k3s/k3s.yaml" - - action: grep_log - node: m02 - path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/corrupt/smartwal-corruption-evidence.txt" - pattern: "^target_offset_inside_wal=true$" - save_as: corrupt_inside_wal_count - - action: assert_greater - actual: "{{ corrupt_inside_wal_count }}" - threshold: "0" - - action: grep_log - node: m02 - path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/corrupt/smartwal-corruption-evidence.txt" - pattern: "^target_offset_inside_extent=false$" - save_as: corrupt_not_extent_count - - action: assert_greater - actual: "{{ corrupt_not_extent_count }}" - threshold: "0" - - - name: assert_no_false_ready_after_corruption - actions: - - action: exec - node: m02 - timeout: 5m - cmd: | - set -e - root=/mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt - out="$root/after-corrupt" - mkdir -p "$out" - port=$(python3 - <<'PY' - import socket - s=socket.socket(); s.bind(("127.0.0.1",0)); print(s.getsockname()[1]); s.close() - PY - ) - kubectl -n {{ helm_namespace }} port-forward deploy/sw-blockmaster ${port}:9333 > "$out/blockmaster-port-forward.log" 2>&1 & - pf=$! - trap 'kill $pf >/dev/null 2>&1 || true; wait $pf >/dev/null 2>&1 || true' EXIT - for i in $(seq 1 60); do if (echo >/dev/tcp/127.0.0.1/$port) >/dev/null 2>&1; then break; fi; sleep 1; done - /mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/bin/sw-block ops report --master-api 127.0.0.1:${port} --out "$out/report" --timeout 30s > "$out/report.stdout.txt" 2> "$out/report.stderr.txt" - python3 - "$root/basic-app/first-volume-summary.txt" "$out/report/operator-snapshot.json" "$out/corruption-status-summary.txt" <<'PY' - import json, sys - summary, snap_path, out_path = sys.argv[1:4] - volume_id = "" - for line in open(summary, encoding="utf-8"): - if line.startswith("volume_id="): - volume_id = line.strip().split("=", 1)[1] - break - if not volume_id: - raise SystemExit("volume_id missing") - snap = json.load(open(snap_path, encoding="utf-8")) - vols = snap.get("volumes") or [] - target = next((v for v in vols if (v.get("status") or {}).get("volume_id") == volume_id), None) - if target is None: - status = "ok" - reason = "volume_missing_after_corruption" - ready = False - blocked = False - else: - st = target.get("status") or {} - conditions = st.get("conditions") or [] - ready = any(c.get("type") == "Ready" and c.get("status") == "True" for c in conditions) - blocked = any(c.get("type") == "Blocked" and c.get("status") == "True" for c in conditions) - reason = st.get("reason_code", "unknown") - status = "failed" if ready else "ok" - with open(out_path, "w", encoding="utf-8") as f: - f.write(f"smartwal_corruption_status_surface={status}\n") - f.write(f"volume_id={volume_id}\n") - f.write(f"ready_true_after_corruption={str(ready).lower()}\n") - f.write(f"blocked_true_after_corruption={str(blocked).lower()}\n") - f.write(f"reason_after_corruption={reason}\n") - f.write("evidence=report/operator-snapshot.json\n") - if status != "ok": - raise SystemExit("false Ready=True after SmartWAL corruption") - PY - env.KUBECONFIG: "/etc/rancher/k3s/k3s.yaml" - - action: grep_log - node: m02 - path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/after-corrupt/corruption-status-summary.txt" - pattern: "^smartwal_corruption_status_surface=ok$" - save_as: no_false_ready_count - - action: assert_greater - actual: "{{ no_false_ready_count }}" - threshold: "0" - - - name: helm_uninstall_cleanup - always: true - actions: - - action: exec - node: m02 - timeout: 8m - cmd: "mkdir -p /mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/cleanup/diagnostics; kubectl -n {{ helm_namespace }} get pods,deploy,ds,svc -o wide > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/cleanup/diagnostics/kube-system.before-cleanup.txt 2>&1 || true; kubectl -n default get pods,deploy,pvc,pv -o wide > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/cleanup/diagnostics/default.before-cleanup.txt 2>&1 || true; helm status {{ helm_release }} --namespace {{ helm_namespace }} >/dev/null 2>&1 && helm uninstall {{ helm_release }} --namespace {{ helm_namespace }} --wait --timeout 300s > /mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/cleanup/helm-uninstall.txt || true; kubectl -n default delete pod sw-block-example-reader sw-block-example-writer --ignore-not-found=true --wait=true --timeout=120s; kubectl -n default delete pvc sw-block-example-pvc --ignore-not-found=true --wait=true --timeout=120s; kubectl delete storageclass sw-block-example --ignore-not-found=true --wait=true --timeout=120s; sudo -n iscsiadm -m node 2>/dev/null | awk '/io.seaweedfs/ {print $1, $2}' | while read portal target; do sudo -n iscsiadm -m node -T \"$target\" -p \"$portal\" -o delete || true; done; sudo -n rm -rf /var/lib/sw-block/testops-{{ run_id }}-smartwal-corrupt; cd {{ product_root }} && bash scripts/verify-helm-cleanup.sh" - env.KUBECONFIG: "/etc/rancher/k3s/k3s.yaml" - env.SW_BLOCK_ARTIFACT_DIR: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/cleanup/verify" - env.SW_BLOCK_HELM_RELEASE: "{{ helm_release }}" - env.SW_BLOCK_HELM_NAMESPACE: "{{ helm_namespace }}" - env.SW_BLOCK_CLEANUP_HOSTPATH_PREFIX: "testops-{{ run_id }}-smartwal-corrupt" - - action: assert_no_active_iscsi_sessions - node: m02 - iqn_substr: "io.seaweedfs" - - action: assert_no_processes - node: m02 - pattern: "[/]blockmaster --|[/]blockvolume --|[/]blockcsi |[/]iscsi-target |^blockmaster |^blockvolume |^blockcsi |^iscsi-target " - - action: grep_log - node: m02 - path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt/cleanup/verify/cleanup-summary.txt" - pattern: "^cleanup_status=ok$" - save_as: helm_cleanup_ok_count - - action: assert_greater - actual: "{{ helm_cleanup_ok_count }}" - threshold: "0" - - action: collect_path - node: m02 - path: "/mnt/smb/work/share/g15d-k8s/{{ run_id }}-smartwal-corrupt" - name: "remote-phases" - ignore_error: true