durable: remove the smartwal and parallel-walstore engines

- The provider refuses the removed names and, under every selector and
  before any selector comparison, a volume carrying their magic (SWAW;
  SWPW in either header slot), reading the file read-only and never
  modifying it. blockvolume --durable-impl and the launcher refuse the
  names with the same advice; the chart schema allows walstore only.
- core/storage/smartwal, core/storage/parallelwal and
  cmd/sw-block-testutil (whose one command corrupted smartwal records)
  are deleted, with the helm smartwal-corruption scenario and the
  parallel-walstore gate script.
- The replication harness runs on walstore; tests that ran on a removed
  engine only because a stub needed some store move to walstore, and the
  state_convergence label test moves to the in-memory BlockStore.
- sw-block cluster.check drops the removed engines' cases.
- Ledger: INV-OPEN-REMOVED-ENGINE-REFUSED-001 and
  INV-OPEN-REMOVED-ENGINE-NAME-REFUSED-001, an OpenRefused edge in M1, and
  the rows citing the removed tests updated. Docs: block-design 1.3 now
  describes the removal, the smartwal deep-dive and figure are gone, the
  scripts default to walstore, and the v1.1 notes carry the removal.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
pingqiuandClaude Opus 5.5 committed 2026-11-30 20:38:54 -08:00
1 parent 565a91b6dc
commit 68045d9698
110 files changed
+250 -9262

No files matched your search

+3 -3
View File
@@ -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).
@@ -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" },
+1 -1
View File
@@ -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")
@@ -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 {
@@ -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) {
@@ -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)
}
}
@@ -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)
}
}
+11 -10
View File
@@ -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")
-129
View File
@@ -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 <store.bin> --out <dir>")
}
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
}
@@ -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))
}
}
+3 -3
View File
@@ -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 {
@@ -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.
//
@@ -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
@@ -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()
@@ -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}
@@ -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)
@@ -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() {
+32 -57
View File
@@ -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)
}
@@ -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)
@@ -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)
}
}
@@ -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)
@@ -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).
@@ -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)
}
@@ -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 {
@@ -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
@@ -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} {
@@ -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)
}
@@ -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,
+4 -2
View File
@@ -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)
@@ -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)
}
}
}
@@ -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,
@@ -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,
@@ -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,
@@ -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")
@@ -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()
@@ -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.
@@ -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()
@@ -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().
@@ -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().
@@ -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))
})
@@ -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
@@ -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
@@ -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
@@ -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"
@@ -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)
})
@@ -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},
}
@@ -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
},
},
}
}
@@ -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):
//
@@ -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
@@ -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.
@@ -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")
}
@@ -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)
}
})
}
@@ -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
}
@@ -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
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -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)
}
}
@@ -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):
@@ -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.
@@ -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)
}
}
})
}
}
@@ -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
}
@@ -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)
}
}
@@ -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
}
@@ -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 ""
}
@@ -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
}
@@ -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
}
@@ -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
@@ -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
}
@@ -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)
}
}
@@ -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)
}
}
}
@@ -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) }
@@ -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)
}
}
}
@@ -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
}
@@ -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)
}
}
+2 -2
View File
@@ -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.
@@ -1,93 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="720" viewBox="0 0 1200 720" font-family="Inter, Segoe UI, Helvetica, Arial, sans-serif">
<title>smartwal (experimental) layout: data written in place in the extent, plus a ring of 32-byte metadata records indexed by LSN modulo capacity</title>
<defs>
<marker id="arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="8" markerHeight="8" orient="auto-start-reverse">
<path d="M0,0 L10,5 L0,10 z" fill="#475569"/>
</marker>
<marker id="arrowR" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="8" markerHeight="8" orient="auto-start-reverse">
<path d="M0,0 L10,5 L0,10 z" fill="#b91c1c"/>
</marker>
</defs>
<rect width="1200" height="720" rx="18" fill="#f8fafc"/>
<text x="40" y="52" font-size="26" font-weight="700" fill="#0f172a">smartwal · in-place data plus a metadata record ring</text>
<rect x="790" y="30" width="140" height="28" rx="14" fill="#fef3c7" stroke="#f59e0b"/>
<text x="860" y="49" font-size="13" font-weight="700" fill="#92400e" text-anchor="middle">EXPERIMENTAL</text>
<text x="40" y="80" font-size="15" fill="#475569">Not a default and no chunk snapshots · core/storage/smartwal/store.go (Store), record.go, ring.go, recovery.go</text>
<!-- file regions -->
<text x="40" y="122" font-size="14" font-weight="700" fill="#0f172a">File regions (not to scale)</text>
<rect x="40" y="134" width="170" height="74" rx="8" fill="#eef2ff" stroke="#6366f1" stroke-width="1.5"/>
<text x="125" y="164" font-size="14" font-weight="600" fill="#312e81" text-anchor="middle">header</text>
<text x="125" y="184" font-size="12" fill="#4338ca" text-anchor="middle">4 KiB · offset 0</text>
<rect x="214" y="134" width="360" height="74" rx="8" fill="#fffbeb" stroke="#f59e0b" stroke-width="1.5"/>
<text x="394" y="164" font-size="14" font-weight="600" fill="#92400e" text-anchor="middle">record ring</text>
<text x="394" y="184" font-size="12" fill="#b45309" text-anchor="middle">slots × 32 bytes (65,536 slots = 2 MiB default)</text>
<rect x="578" y="134" width="582" height="74" rx="8" fill="#ecfdf5" stroke="#10b981" stroke-width="1.5"/>
<text x="869" y="164" font-size="14" font-weight="600" fill="#065f46" text-anchor="middle">extent: the data, written in place</text>
<text x="869" y="184" font-size="12" fill="#047857" text-anchor="middle">numBlocks × BlockSize · reads always come from here</text>
<!-- record byte map: 30 px per byte, x0 = 120 -->
<rect x="40" y="232" width="1120" height="170" rx="14" fill="#ffffff" stroke="#cbd5e1" stroke-width="1.5"/>
<text x="60" y="260" font-size="15" font-weight="700" fill="#0f172a">One ring slot: a 32-byte record (record.go encode)</text>
<rect x="120" y="280" width="30" height="44" fill="#eef2ff" stroke="#6366f1"/>
<rect x="150" y="280" width="30" height="44" fill="#eef2ff" stroke="#6366f1"/>
<rect x="180" y="280" width="60" height="44" fill="#f1f5f9" stroke="#cbd5e1"/>
<rect x="240" y="280" width="120" height="44" fill="#fde68a" stroke="#f59e0b"/>
<rect x="360" y="280" width="240" height="44" fill="#fde68a" stroke="#f59e0b"/>
<rect x="600" y="280" width="240" height="44" fill="#f1f5f9" stroke="#cbd5e1"/>
<rect x="840" y="280" width="120" height="44" fill="#d1fae5" stroke="#10b981"/>
<rect x="960" y="280" width="120" height="44" fill="#eef2ff" stroke="#6366f1"/>
<text x="135" y="307" font-size="10.5" fill="#312e81" text-anchor="middle">mg</text>
<text x="165" y="307" font-size="10.5" fill="#312e81" text-anchor="middle">fl</text>
<text x="210" y="307" font-size="10.5" fill="#64748b" text-anchor="middle">rsv</text>
<text x="300" y="307" font-size="12" font-weight="600" fill="#92400e" text-anchor="middle">LBA u32</text>
<text x="480" y="307" font-size="12" font-weight="600" fill="#92400e" text-anchor="middle">LSN u64</text>
<text x="720" y="307" font-size="12" fill="#64748b" text-anchor="middle">reserved2 (zero)</text>
<text x="900" y="307" font-size="12" font-weight="600" fill="#065f46" text-anchor="middle">dataCRC32</text>
<text x="1020" y="307" font-size="12" font-weight="600" fill="#312e81" text-anchor="middle">recCRC32</text>
<text x="120" y="340" font-size="11" fill="#64748b" text-anchor="middle">0</text>
<text x="150" y="340" font-size="11" fill="#64748b" text-anchor="middle">1</text>
<text x="180" y="340" font-size="11" fill="#64748b" text-anchor="middle">2</text>
<text x="240" y="340" font-size="11" fill="#64748b" text-anchor="middle">4</text>
<text x="360" y="340" font-size="11" fill="#64748b" text-anchor="middle">8</text>
<text x="600" y="340" font-size="11" fill="#64748b" text-anchor="middle">16</text>
<text x="840" y="340" font-size="11" fill="#64748b" text-anchor="middle">24</text>
<text x="960" y="340" font-size="11" fill="#64748b" text-anchor="middle">28</text>
<text x="1080" y="340" font-size="11" fill="#64748b" text-anchor="middle">32</text>
<text x="60" y="366" font-size="12" fill="#334155">mg = magic 0xAC (anything else is an empty slot) · fl = flags (write 0x01, trim 0x02, barrier 0x04) · rsv = reserved · little-endian</text>
<text x="60" y="386" font-size="12" fill="#334155">dataCRC32 = CRC32 of the data block in the extent · recCRC32 = CRC32 of bytes 0..27 · slot index = LSN mod capacity (ring.go appendAt)</text>
<!-- write order -->
<text x="40" y="440" font-size="15" font-weight="700" fill="#0f172a">Write order (Store.writeAt) and Sync</text>
<rect x="40" y="454" width="250" height="96" rx="10" fill="#f1f5f9" stroke="#94a3b8" stroke-width="1.5"/>
<text x="56" y="480" font-size="13.5" font-weight="700" fill="#0f172a">1 · read the old block</text>
<text x="56" y="502" font-size="12" fill="#334155">kept in memory for rollback</text>
<rect x="320" y="454" width="250" height="96" rx="10" fill="#ecfdf5" stroke="#10b981" stroke-width="1.5"/>
<text x="336" y="480" font-size="13.5" font-weight="700" fill="#065f46">2 · pwrite data in place</text>
<text x="336" y="502" font-size="12" fill="#334155">the extent slot of the LBA</text>
<rect x="600" y="454" width="250" height="96" rx="10" fill="#fffbeb" stroke="#f59e0b" stroke-width="1.5"/>
<text x="616" y="480" font-size="13.5" font-weight="700" fill="#92400e">3 · append the record</text>
<text x="616" y="502" font-size="12" fill="#334155">slot = LSN mod capacity; on failure</text>
<text x="616" y="520" font-size="12" fill="#334155">the old block is written back</text>
<rect x="880" y="454" width="280" height="96" rx="10" fill="#eef2ff" stroke="#6366f1" stroke-width="1.5"/>
<text x="896" y="480" font-size="13.5" font-weight="700" fill="#312e81">4 · Sync: one fsync</text>
<text x="896" y="502" font-size="12" fill="#334155">covers data and record together</text>
<text x="896" y="520" font-size="12" fill="#334155">(same file)</text>
<line x1="291" y1="502" x2="318" y2="502" stroke="#475569" stroke-width="1.6" marker-end="url(#arrow)"/>
<line x1="571" y1="502" x2="598" y2="502" stroke="#475569" stroke-width="1.6" marker-end="url(#arrow)"/>
<line x1="851" y1="502" x2="878" y2="502" stroke="#475569" stroke-width="1.6" marker-end="url(#arrow)"/>
<!-- crash window -->
<path d="M585,556 L585,580" stroke="#b91c1c" stroke-width="2" marker-end="url(#arrowR)"/>
<rect x="380" y="586" width="410" height="50" rx="10" fill="#fef2f2" stroke="#ef4444" stroke-width="1.5"/>
<text x="585" y="607" font-size="12.5" font-weight="700" fill="#991b1b" text-anchor="middle">Known crash window between 2 and 3</text>
<text x="585" y="625" font-size="11.5" fill="#991b1b" text-anchor="middle">extent newer than the ring: CRC check fails, volume does not open</text>
<!-- recovery -->
<rect x="40" y="652" width="1120" height="52" rx="10" fill="#ffffff" stroke="#cbd5e1" stroke-width="1.5"/>
<text x="60" y="676" font-size="12.5" font-weight="700" fill="#0f172a">Recovery (runRecoveryCounting):</text>
<text x="280" y="676" font-size="12.5" fill="#334155">scan every slot (a bad recCRC is skipped and counted as a warning) → highest LSN per LBA →</text>
<text x="280" y="694" font-size="12.5" fill="#334155">check the extent block against dataCRC32; a mismatch fails closed as a WAL integrity failure → frontier = highest verified LSN</text>
</svg>

Before

Width:  |  Height:  |  Size: 8.1 KiB

+6 -172
View File
@@ -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`).
<p align="center">
<img src="../assets/smartwal-layout.svg" alt="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" width="100%">
</p>
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.
+7 -3
View File
@@ -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 |
@@ -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 |
@@ -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
1 version component placement field bits source action
6 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
7 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
8 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
9 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
10 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
11 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
+1 -1
View File
@@ -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 |
+2 -3
View File
@@ -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 | `<volume>.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
`<volume>.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
`<volume>.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
+1
View File
@@ -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)
+8
View File
@@ -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.
+3 -4
View File
@@ -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
+1 -1
View File
@@ -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 |
+1 -2
View File
@@ -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` |
@@ -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.
-1
View File
@@ -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)
+1 -1
View File
@@ -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
+1 -2
View File
@@ -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 |
@@ -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)
@@ -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.",
-1
View File
@@ -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
+2 -2
View File
@@ -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 "
+1 -1
View File
@@ -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`. |
@@ -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}" \
@@ -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}" \
@@ -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}" \
@@ -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
Loaded 100 of 110 files, more files were not shown because too many files have changed in this diff. Show more