diff --git a/seaweed-block/core/frontend/durable/storage_adapter.go b/seaweed-block/core/frontend/durable/storage_adapter.go new file mode 100644 index 0000000000..932c5a538c --- /dev/null +++ b/seaweed-block/core/frontend/durable/storage_adapter.go @@ -0,0 +1,305 @@ +// 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 +// iSCSI and NVMe consume. Responsibilities: +// +// 1. byte ↔ LBA translation (G-int.1). +// Frontend layer speaks byte offsets + length; storage layer +// speaks LBA + full-block data. The adapter bridges: partial- +// block writes trigger read-modify-write; full-block writes +// skip the read. Reads copy the slice of the backing block +// covered by the byte range. +// +// 2. Per-I/O fence check (G-int.2). +// Re-reads `ProjectionView` on every operation; ANY drift +// (identity field mismatch or Healthy=false) → ErrStalePrimary. +// Preserves INV-FRONTEND-002.{EPOCH,EV,REPLICA,HEALTHY} under +// a durable backend. +// +// 3. Operational gate (G-int.3, Addendum A). +// Before SetOperational(true, _) is called, every I/O returns +// ErrNotReady with evidence. Starts non-operational — host/ +// provider flips to true after recovery succeeds. This is +// local readiness only; NEVER advances epoch / mints authority. +// +// 4. Sync (G-int.2 sync policy locked as explicit method). +// Dispatches to LogicalStorage.Sync and returns error +// verbatim. iSCSI SYNCHRONIZE CACHE + NVMe Flush wiring lands +// in T3b. +// +// StorageBackend does NOT own the LogicalStorage lifecycle — the +// Provider (T3b) opens and closes storage. Backend.Close marks the +// handle closed but does not tear down storage. +// +// Boundary guarantee: this package does not import core/authority +// or core/adapter (see core/frontend/boundary_guard_test.go). +package durable + +import ( + "context" + "errors" + "fmt" + "sync" + "sync/atomic" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// errInvalidOffset is returned for negative byte offsets. Callers +// should never produce these; both iSCSI and NVMe clamp LBA before +// it reaches the backend. Kept as a distinct sentinel so the cause +// is visible in logs when a protocol bug does emit one. +var errInvalidOffset = errors.New("durable: invalid (negative) offset") + +// errSyncBeforeOpen is returned if Sync is called before +// SetOperational(true, _). Distinct from ErrNotReady so diagnostic +// logs can tell "host sent FLUSH before we were ready" apart from +// "I/O before first-open". +var errSyncBeforeOpen = errors.New("durable: sync before operational") + +// StorageBackend adapts a LogicalStorage into frontend.Backend. +type StorageBackend struct { + storage storage.LogicalStorage + view frontend.ProjectionView + id frontend.Identity + blockSize int + + // operational is the T3a Addendum A readiness gate. Starts + // false; provider flips true after Recover() succeeds (T3b). + // opEvidence is the reason reported when operational=false + // (e.g., "awaiting recovery", "local epoch ahead of assignment"). + operational atomic.Bool + opEvidence atomic.Value // string + + mu sync.Mutex + closed bool +} + +// NewStorageBackend constructs a backend. Starts NON-operational +// per INV-DURABLE-OPGATE-001; caller must SetOperational(true, _) +// before I/O will succeed. +// +// The storage's block size is captured once at construction +// (LogicalStorage.BlockSize() is a stable geometry field; no T3 +// impl changes it mid-session). +func NewStorageBackend(s storage.LogicalStorage, view frontend.ProjectionView, id frontend.Identity) *StorageBackend { + b := &StorageBackend{ + storage: s, + view: view, + id: id, + blockSize: s.BlockSize(), + } + b.opEvidence.Store("awaiting first SetOperational") + // operational.Store(false) is zero-value default; be explicit. + b.operational.Store(false) + return b +} + +// Identity returns the lineage captured at Open. Never re-reads +// from the projection — stable for the backend's lifetime. +func (b *StorageBackend) Identity() frontend.Identity { return b.id } + +// Close marks the backend closed. All subsequent I/O + Sync +// return ErrBackendClosed. Does NOT close the underlying +// storage — the Provider owns LogicalStorage lifecycle. +func (b *StorageBackend) Close() error { + b.mu.Lock() + defer b.mu.Unlock() + b.closed = true + return nil +} + +// SetOperational flips the readiness gate. evidence is surfaced +// in error strings and diagnostic logs — pass a short reason like +// "recovered LSN=123 epoch=4" or "superblock ahead of assignment". +// Safe to call from any goroutine. +// +// Invariant: does NOT touch identity/lineage/epoch — see package +// godoc + INV-DURABLE-OPGATE-001. +func (b *StorageBackend) SetOperational(ok bool, evidence string) { + if evidence == "" { + if ok { + evidence = "operational" + } else { + evidence = "not operational" + } + } + b.opEvidence.Store(evidence) + b.operational.Store(ok) +} + +// Sync flushes everything the storage has to its durability +// boundary. Returns nil iff the stable frontier advanced without +// error. Subject to the same gate stack as I/O: closed → Err- +// BackendClosed, non-operational → ErrNotReady, lineage drift → +// ErrStalePrimary. +func (b *StorageBackend) Sync(ctx context.Context) error { + if err := b.gate(); err != nil { + return err + } + if _, err := b.storage.Sync(); err != nil { + return fmt.Errorf("durable: storage sync: %w", err) + } + return nil +} + +// Read copies up to len(p) bytes starting at offset. Reads past +// end-of-volume return zero bytes (no error). Every read is gated. +func (b *StorageBackend) Read(ctx context.Context, offset int64, p []byte) (int, error) { + if err := b.gate(); err != nil { + return 0, err + } + if len(p) == 0 { + return 0, nil + } + return b.readBytes(offset, p) +} + +// Write persists up to len(p) bytes at offset. Partial-block +// writes perform a read-modify-write: fetch the current block, +// overlay the partial range, write the full block back. +// Every write is gated. +func (b *StorageBackend) Write(ctx context.Context, offset int64, p []byte) (int, error) { + if err := b.gate(); err != nil { + return 0, err + } + if len(p) == 0 { + return 0, nil + } + return b.writeBytes(offset, p) +} + +// gate is the per-I/O precondition stack. Order matters: +// +// 1. closed: tests the lifecycle, cheapest check +// 2. operational: tests local readiness; preserves Add.A Add.1 +// 3. lineage: tests that the captured Identity still matches +// the live projection; preserves INV-FRONTEND-002 +// +// Returning ANY error short-circuits — no partial I/O. +func (b *StorageBackend) gate() error { + b.mu.Lock() + closed := b.closed + b.mu.Unlock() + if closed { + return frontend.ErrBackendClosed + } + if !b.operational.Load() { + ev, _ := b.opEvidence.Load().(string) + return fmt.Errorf("%w: %s", frontend.ErrNotReady, ev) + } + return b.lineageCheck() +} + +// lineageCheck re-reads the projection and compares all four +// facets plus Healthy. Any drift → ErrStalePrimary. +// INV-FRONTEND-002.{EPOCH,EV,REPLICA,HEALTHY}. +func (b *StorageBackend) lineageCheck() error { + proj := b.view.Projection() + if !proj.Healthy || + proj.VolumeID != b.id.VolumeID || + proj.ReplicaID != b.id.ReplicaID || + proj.Epoch != b.id.Epoch || + proj.EndpointVersion != b.id.EndpointVersion { + return frontend.ErrStalePrimary + } + return nil +} + +// readBytes performs the byte-range → LBA-range fanout for Read. +// Reads block-at-a-time, copying the sub-slice covered by the +// current byte range. Handles three cases: +// +// - offset aligned, len >= block: copy full block, advance. +// - offset misaligned: copy tail of first block only. +// - final block, len < available: copy prefix only. +func (b *StorageBackend) readBytes(offset int64, p []byte) (int, error) { + if offset < 0 { + return 0, errInvalidOffset + } + bs := int64(b.blockSize) + total := 0 + buf := p + pos := offset + for len(buf) > 0 { + lba := uint32(pos / bs) + block, err := b.storage.Read(lba) + if err != nil { + return total, fmt.Errorf("durable: read lba=%d: %w", lba, err) + } + inBlockOff := int(pos % bs) + if inBlockOff >= len(block) { + // Short block (shouldn't happen with fixed-size storage) + // — treat as zeros, advance. + advance := int(bs) - inBlockOff + if advance > len(buf) { + advance = len(buf) + } + for i := 0; i < advance; i++ { + buf[i] = 0 + } + total += advance + buf = buf[advance:] + pos += int64(advance) + continue + } + copied := copy(buf, block[inBlockOff:]) + total += copied + buf = buf[copied:] + pos += int64(copied) + } + return total, nil +} + +// writeBytes performs the byte-range → LBA-range fanout for Write. +// Full-block writes skip the read (optimization for the hot path); +// partial-block writes read-modify-write to preserve the bytes +// outside the range. +func (b *StorageBackend) writeBytes(offset int64, p []byte) (int, error) { + if offset < 0 { + return 0, errInvalidOffset + } + bs := int64(b.blockSize) + total := 0 + buf := p + pos := offset + for len(buf) > 0 { + lba := uint32(pos / bs) + inBlockOff := int(pos % bs) + available := int(bs) - inBlockOff + chunkLen := len(buf) + if chunkLen > available { + chunkLen = available + } + + var block []byte + if inBlockOff == 0 && chunkLen == int(bs) { + // Full-block write: skip the read. + block = buf[:chunkLen] + } else { + // Partial-block: RMW. + existing, err := b.storage.Read(lba) + if err != nil { + return total, fmt.Errorf("durable: RMW read lba=%d: %w", lba, err) + } + block = make([]byte, bs) + copy(block, existing) + copy(block[inBlockOff:], buf[:chunkLen]) + } + + if _, err := b.storage.Write(lba, block); err != nil { + return total, fmt.Errorf("durable: write lba=%d: %w", lba, err) + } + total += chunkLen + buf = buf[chunkLen:] + pos += int64(chunkLen) + } + return total, nil +} + +// Compile-time check that StorageBackend satisfies frontend.Backend. +// Catches interface drift at build time rather than runtime. +var _ frontend.Backend = (*StorageBackend)(nil) diff --git a/seaweed-block/core/frontend/durable/storage_adapter_test.go b/seaweed-block/core/frontend/durable/storage_adapter_test.go new file mode 100644 index 0000000000..c4607c4d26 --- /dev/null +++ b/seaweed-block/core/frontend/durable/storage_adapter_test.go @@ -0,0 +1,437 @@ +// T3a adapter tests — matrix-parameterized per Addendum A #1. +// EVERY test runs against BOTH walstore and smartwal.Store so +// variant skew is caught at L1 instead of prod. +// +// Acceptance-criteria mapping (mini plan §2): +// #1 TestT3a_StorageBackend_ImplementsBackend +// #2 TestT3a_StorageBackend_ByteLBATranslation_Matrix +// #3 TestT3a_StorageBackend_FenceCheck_{Epoch,EV,Replica,Healthy} +// #4 TestT3a_StorageBackend_OperationalGate_{BeforeOpen,FlipBack,Evidence} +// #5 TestT3a_StorageBackend_Sync_DispatchesToStorage +// #6 implicitly: all Matrix tests run N×2 via logicalStorageFactories +// #7,#8 covered by core/storage superblock tests (not this file) + +package durable_test + +import ( + "bytes" + "context" + "errors" + "fmt" + "path/filepath" + "sync/atomic" + "testing" + + "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" +) + +// ------- Matrix factory (Addendum A #1) ------- + +// logicalStorageFactory is the shared factory contract; every +// adapter test iterates over the list returned by +// logicalStorageFactories() so adding a new impl later requires +// one edit here, not N edits scattered across test files. +type logicalStorageFactory struct { + name string + // make returns a fresh LogicalStorage backed by a tempdir. + // numBlocks / blockSize are the geometry for the test. + make func(t *testing.T, numBlocks uint32, blockSize int) storage.LogicalStorage +} + +func logicalStorageFactories() []logicalStorageFactory { + return []logicalStorageFactory{ + { + name: "walstore", + make: func(t *testing.T, numBlocks uint32, blockSize int) storage.LogicalStorage { + t.Helper() + path := filepath.Join(t.TempDir(), "walstore.bin") + s, err := storage.CreateWALStore(path, numBlocks, blockSize) + if err != nil { + t.Fatalf("CreateWALStore: %v", err) + } + t.Cleanup(func() { _ = s.Close() }) + 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 + }, + }, + } +} + +// ------- ProjectionView stub ------- + +// stubView is a minimal ProjectionView whose state can be flipped +// at runtime to exercise fence-drift behavior. +type stubView struct { + proj atomic.Value // frontend.Projection +} + +func newStubView(p frontend.Projection) *stubView { + v := &stubView{} + v.proj.Store(p) + return v +} + +func (v *stubView) Projection() frontend.Projection { + return v.proj.Load().(frontend.Projection) +} + +func (v *stubView) set(p frontend.Projection) { v.proj.Store(p) } + +func healthyProj(id frontend.Identity) frontend.Projection { + return frontend.Projection{ + VolumeID: id.VolumeID, + ReplicaID: id.ReplicaID, + Epoch: id.Epoch, + EndpointVersion: id.EndpointVersion, + Healthy: true, + } +} + +// newTestBackend builds a backend at operational=true (to skip +// the gate in tests that exercise I/O). Individual operational- +// gate tests flip it back off. +func newTestBackend(t *testing.T, f logicalStorageFactory, numBlocks uint32, blockSize int) (*durable.StorageBackend, *stubView, storage.LogicalStorage) { + t.Helper() + s := f.make(t, numBlocks, blockSize) + id := frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1} + view := newStubView(healthyProj(id)) + b := durable.NewStorageBackend(s, view, id) + b.SetOperational(true, "test") + return b, view, s +} + +// ------- #1 ImplementsBackend ------- + +func TestT3a_StorageBackend_ImplementsBackend(t *testing.T) { + // Compile-time check via var _ in the package under test + // covers the interface conformance; this test proves the + // zero-value constructor runs + returns a live backend. + for _, f := range logicalStorageFactories() { + f := f + t.Run(f.name, func(t *testing.T) { + b, _, _ := newTestBackend(t, f, 16, 4096) + if b.Identity().VolumeID != "v1" { + t.Errorf("Identity().VolumeID=%q want v1", b.Identity().VolumeID) + } + var _ frontend.Backend = b + }) + } +} + +// ------- #2 Byte ↔ LBA translation matrix ------- + +func TestT3a_StorageBackend_ByteLBATranslation_Matrix(t *testing.T) { + cases := []struct { + name string + offset int64 + writeLen int + blockSize int + }{ + {"aligned_full_block", 0, 4096, 4096}, + {"aligned_multi_block", 0, 8192, 4096}, + {"aligned_partial_tail", 0, 100, 4096}, + {"misaligned_offset_partial", 123, 500, 4096}, + {"misaligned_offset_spanning", 4000, 1000, 4096}, + {"spanning_3_blocks", 1000, 8500, 4096}, + } + + for _, f := range logicalStorageFactories() { + for _, c := range cases { + f, c := f, c + t.Run(f.name+"/"+c.name, func(t *testing.T) { + b, _, _ := newTestBackend(t, f, 8, c.blockSize) + + // Write seed-derived bytes. + w := make([]byte, c.writeLen) + for i := range w { + w[i] = byte((i * 31) & 0xFF) + } + n, err := b.Write(context.Background(), c.offset, w) + if err != nil { + t.Fatalf("Write: %v", err) + } + if n != c.writeLen { + t.Fatalf("Write n=%d want %d", n, c.writeLen) + } + + // Read back and verify bit-exact. + r := make([]byte, c.writeLen) + nr, err := b.Read(context.Background(), c.offset, r) + if err != nil { + t.Fatalf("Read: %v", err) + } + if nr != c.writeLen { + t.Fatalf("Read n=%d want %d", nr, c.writeLen) + } + if !bytes.Equal(r, w) { + t.Fatalf("Read bytes don't match Write (first diff idx=%d)", firstDiffIdx(r, w)) + } + + // Outside the write range must still read zeros — + // confirms RMW didn't spill. + if c.offset > 0 { + prefix := make([]byte, c.offset) + if _, err := b.Read(context.Background(), 0, prefix); err != nil { + t.Fatalf("prefix Read: %v", err) + } + if !isAllZeros(prefix) { + t.Fatalf("prefix [0,%d) expected zeros, got non-zero", c.offset) + } + } + }) + } + } +} + +func firstDiffIdx(a, b []byte) int { + for i := 0; i < len(a) && i < len(b); i++ { + if a[i] != b[i] { + return i + } + } + return -1 +} + +func isAllZeros(p []byte) bool { + for _, x := range p { + if x != 0 { + return false + } + } + return true +} + +// ------- #3 Fence check (4 facets) ------- + +func TestT3a_StorageBackend_FenceCheck_Epoch(t *testing.T) { + for _, f := range logicalStorageFactories() { + f := f + t.Run(f.name, func(t *testing.T) { + b, view, _ := newTestBackend(t, f, 4, 4096) + // Drift Epoch. + p := view.Projection() + p.Epoch = 999 + view.set(p) + if _, err := b.Read(context.Background(), 0, make([]byte, 4)); !errors.Is(err, frontend.ErrStalePrimary) { + t.Fatalf("Read after Epoch drift: want ErrStalePrimary, got %v", err) + } + if _, err := b.Write(context.Background(), 0, []byte("x")); !errors.Is(err, frontend.ErrStalePrimary) { + t.Fatalf("Write after Epoch drift: want ErrStalePrimary, got %v", err) + } + }) + } +} + +func TestT3a_StorageBackend_FenceCheck_EV(t *testing.T) { + for _, f := range logicalStorageFactories() { + f := f + t.Run(f.name, func(t *testing.T) { + b, view, _ := newTestBackend(t, f, 4, 4096) + p := view.Projection() + p.EndpointVersion = 999 + view.set(p) + if _, err := b.Read(context.Background(), 0, make([]byte, 4)); !errors.Is(err, frontend.ErrStalePrimary) { + t.Fatalf("want ErrStalePrimary on EV drift, got %v", err) + } + }) + } +} + +func TestT3a_StorageBackend_FenceCheck_Replica(t *testing.T) { + for _, f := range logicalStorageFactories() { + f := f + t.Run(f.name, func(t *testing.T) { + b, view, _ := newTestBackend(t, f, 4, 4096) + p := view.Projection() + p.ReplicaID = "different-replica" + view.set(p) + if _, err := b.Write(context.Background(), 0, []byte("x")); !errors.Is(err, frontend.ErrStalePrimary) { + t.Fatalf("want ErrStalePrimary on replica drift, got %v", err) + } + }) + } +} + +func TestT3a_StorageBackend_FenceCheck_Healthy(t *testing.T) { + for _, f := range logicalStorageFactories() { + f := f + t.Run(f.name, func(t *testing.T) { + b, view, _ := newTestBackend(t, f, 4, 4096) + p := view.Projection() + p.Healthy = false + view.set(p) + if _, err := b.Read(context.Background(), 0, make([]byte, 4)); !errors.Is(err, frontend.ErrStalePrimary) { + t.Fatalf("want ErrStalePrimary on unhealthy, got %v", err) + } + }) + } +} + +// ------- #4 Operational gate ------- + +func TestT3a_StorageBackend_OperationalGate_BeforeOpen(t *testing.T) { + for _, f := range logicalStorageFactories() { + f := f + t.Run(f.name, func(t *testing.T) { + s := f.make(t, 4, 4096) + id := frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1} + view := newStubView(healthyProj(id)) + b := durable.NewStorageBackend(s, view, id) + // DO NOT flip operational — every I/O must be ErrNotReady. + + if _, err := b.Read(context.Background(), 0, make([]byte, 4)); !errors.Is(err, frontend.ErrNotReady) { + t.Fatalf("Read before SetOperational(true): want ErrNotReady, got %v", err) + } + if _, err := b.Write(context.Background(), 0, []byte("x")); !errors.Is(err, frontend.ErrNotReady) { + t.Fatalf("Write before SetOperational(true): want ErrNotReady, got %v", err) + } + if err := b.Sync(context.Background()); !errors.Is(err, frontend.ErrNotReady) { + t.Fatalf("Sync before SetOperational(true): want ErrNotReady, got %v", err) + } + }) + } +} + +func TestT3a_StorageBackend_OperationalGate_FlipBack(t *testing.T) { + for _, f := range logicalStorageFactories() { + f := f + t.Run(f.name, func(t *testing.T) { + b, _, _ := newTestBackend(t, f, 4, 4096) + // I/O works while operational. + if _, err := b.Write(context.Background(), 0, []byte("hello")); err != nil { + t.Fatalf("initial Write: %v", err) + } + + // Flip to non-operational → I/O must reject. + b.SetOperational(false, "shutting down") + if _, err := b.Write(context.Background(), 0, []byte("x")); !errors.Is(err, frontend.ErrNotReady) { + t.Fatalf("Write after flip off: want ErrNotReady, got %v", err) + } + + // Flip back on → I/O succeeds again. + b.SetOperational(true, "back") + if _, err := b.Write(context.Background(), 0, []byte("x")); err != nil { + t.Fatalf("Write after flip-back on: %v", err) + } + }) + } +} + +func TestT3a_StorageBackend_OperationalGate_Evidence(t *testing.T) { + for _, f := range logicalStorageFactories() { + f := f + t.Run(f.name, func(t *testing.T) { + s := f.make(t, 4, 4096) + id := frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1} + b := durable.NewStorageBackend(s, newStubView(healthyProj(id)), id) + b.SetOperational(false, "local epoch ahead of assignment") + + _, err := b.Read(context.Background(), 0, make([]byte, 4)) + if !errors.Is(err, frontend.ErrNotReady) { + t.Fatalf("want ErrNotReady, got %v", err) + } + // Evidence should appear in the wrapped error message. + if !contains(err.Error(), "local epoch ahead of assignment") { + t.Errorf("err=%q does not include evidence", err) + } + }) + } +} + +func contains(s, sub string) bool { + return len(sub) == 0 || (len(s) >= len(sub) && anyIndex(s, sub) >= 0) +} + +func anyIndex(s, sub string) int { +outer: + for i := 0; i+len(sub) <= len(s); i++ { + for j := 0; j < len(sub); j++ { + if s[i+j] != sub[j] { + continue outer + } + } + return i + } + return -1 +} + +// ------- #5 Sync dispatches to storage ------- + +func TestT3a_StorageBackend_Sync_DispatchesToStorage(t *testing.T) { + for _, f := range logicalStorageFactories() { + f := f + t.Run(f.name, func(t *testing.T) { + b, _, s := newTestBackend(t, f, 4, 4096) + + // Pre-sync state. + preR, preS, _ := s.Boundaries() + // Write to advance H; Sync should bring R up. + if _, err := b.Write(context.Background(), 0, make([]byte, 4096)); err != nil { + t.Fatalf("Write: %v", err) + } + if err := b.Sync(context.Background()); err != nil { + t.Fatalf("Sync: %v", err) + } + // Post-sync: the synced frontier (R) must not go + // backward and must match or exceed the newest LSN + // captured before Sync (accounting for impl-specific + // Sync semantics; we only pin "R doesn't regress"). + postR, _, _ := s.Boundaries() + if postR < preR { + t.Fatalf("R regressed: pre=%d post=%d", preR, postR) + } + _ = preS + }) + } +} + +// ------- Close behavior ------- + +func TestT3a_StorageBackend_Close_ReturnsErrBackendClosed(t *testing.T) { + for _, f := range logicalStorageFactories() { + f := f + t.Run(f.name, func(t *testing.T) { + b, _, _ := newTestBackend(t, f, 4, 4096) + if err := b.Close(); err != nil { + t.Fatalf("Close: %v", err) + } + if _, err := b.Read(context.Background(), 0, make([]byte, 4)); !errors.Is(err, frontend.ErrBackendClosed) { + t.Fatalf("Read after Close: want ErrBackendClosed, got %v", err) + } + if _, err := b.Write(context.Background(), 0, []byte("x")); !errors.Is(err, frontend.ErrBackendClosed) { + t.Fatalf("Write after Close: want ErrBackendClosed, got %v", err) + } + if err := b.Sync(context.Background()); !errors.Is(err, frontend.ErrBackendClosed) { + t.Fatalf("Sync after Close: want ErrBackendClosed, got %v", err) + } + }) + } +} + +// Stop-rule sanity — ensure every test ran against both impls. +func TestT3a_MatrixCoverage(t *testing.T) { + names := []string{} + for _, f := range logicalStorageFactories() { + names = append(names, f.name) + } + got := fmt.Sprint(names) + want := "[walstore smartwal]" + if got != want { + t.Fatalf("matrix drifted: got %s want %s", got, want) + } +} diff --git a/seaweed-block/core/frontend/iscsi/t2_ckpt10_hardening_test.go b/seaweed-block/core/frontend/iscsi/t2_ckpt10_hardening_test.go index 500de62174..55aedb474e 100644 --- a/seaweed-block/core/frontend/iscsi/t2_ckpt10_hardening_test.go +++ b/seaweed-block/core/frontend/iscsi/t2_ckpt10_hardening_test.go @@ -52,6 +52,10 @@ func (b *countingBackend) Write(ctx context.Context, off int64, p []byte) (int, b.writes.Add(1) return b.inner.Write(ctx, off, p) } +func (b *countingBackend) Sync(ctx context.Context) error { return b.inner.Sync(ctx) } +func (b *countingBackend) SetOperational(ok bool, evidence string) { + b.inner.SetOperational(ok, evidence) +} func (b *countingBackend) WriteCallCount() int32 { return b.writes.Load() } // Architect finding #1 (memory-amplification / protocol diff --git a/seaweed-block/core/frontend/memback/backend.go b/seaweed-block/core/frontend/memback/backend.go index 5a684708c2..7f3b3d8686 100644 --- a/seaweed-block/core/frontend/memback/backend.go +++ b/seaweed-block/core/frontend/memback/backend.go @@ -3,6 +3,7 @@ package memback import ( "context" "sync" + "sync/atomic" "github.com/seaweedfs/seaweed-block/core/frontend" ) @@ -62,10 +63,20 @@ type backend struct { mu sync.Mutex closed bool + + // T3a operational gate. memback opens operational=true because + // it's ambient in-memory storage with no readiness lifecycle. + // Host/provider code using memback can still flip via + // SetOperational for tests that want to exercise ErrNotReady. + operational atomic.Bool + opEvidence atomic.Value // string } func newBackend(view frontend.ProjectionView, id frontend.Identity, store *volumeStore) *backend { - return &backend{view: view, id: id, store: store} + b := &backend{view: view, id: id, store: store} + b.operational.Store(true) + b.opEvidence.Store("") + return b } func (b *backend) Identity() frontend.Identity { return b.id } @@ -91,6 +102,18 @@ func (b *backend) Write(_ context.Context, offset int64, p []byte) (int, error) return b.store.write(offset, p) } +// Sync is a no-op for memback (no on-disk state). Still subject +// to the guard so closed/stale backends can't drive a sync. +func (b *backend) Sync(_ context.Context) error { + return b.guard() +} + +// SetOperational flips the readiness gate. See Backend godoc. +func (b *backend) SetOperational(ok bool, evidence string) { + b.opEvidence.Store(evidence) + b.operational.Store(ok) +} + // guard enforces the two per-operation preconditions: // - Backend has not been closed. // - Every identity field still matches the current projection @@ -103,6 +126,9 @@ func (b *backend) guard() error { if closed { return frontend.ErrBackendClosed } + if !b.operational.Load() { + return frontend.ErrNotReady + } proj := b.view.Projection() if !proj.Healthy || proj.VolumeID != b.id.VolumeID || diff --git a/seaweed-block/core/frontend/nvme/t2_v2port_nvme_no_retry_test.go b/seaweed-block/core/frontend/nvme/t2_v2port_nvme_no_retry_test.go index c559aab62f..9aa1158f3f 100644 --- a/seaweed-block/core/frontend/nvme/t2_v2port_nvme_no_retry_test.go +++ b/seaweed-block/core/frontend/nvme/t2_v2port_nvme_no_retry_test.go @@ -70,6 +70,11 @@ func (c *countingFaultBackend) Write(ctx context.Context, offset int64, p []byte return c.inner.Write(ctx, offset, p) } +func (c *countingFaultBackend) Sync(ctx context.Context) error { return c.inner.Sync(ctx) } +func (c *countingFaultBackend) SetOperational(ok bool, evidence string) { + c.inner.SetOperational(ok, evidence) +} + // newFaultyTargetClient builds a Target fronted by a // countingFaultBackend with `failN` initial write failures queued. func newFaultyTargetClient(t *testing.T, failN int32) (*countingFaultBackend, *nvmeClient) { diff --git a/seaweed-block/core/frontend/nvme/t2_v2port_nvme_write_chunked_r2t_test.go b/seaweed-block/core/frontend/nvme/t2_v2port_nvme_write_chunked_r2t_test.go index c7c0d6ea58..c7653acdfe 100644 --- a/seaweed-block/core/frontend/nvme/t2_v2port_nvme_write_chunked_r2t_test.go +++ b/seaweed-block/core/frontend/nvme/t2_v2port_nvme_write_chunked_r2t_test.go @@ -45,6 +45,12 @@ type writeCountingBackend struct { func (b *writeCountingBackend) Identity() frontend.Identity { return b.inner.Identity() } func (b *writeCountingBackend) Close() error { return b.inner.Close() } +func (b *writeCountingBackend) Sync(ctx context.Context) error { + return b.inner.Sync(ctx) +} +func (b *writeCountingBackend) SetOperational(ok bool, evidence string) { + b.inner.SetOperational(ok, evidence) +} func (b *writeCountingBackend) Read(ctx context.Context, off int64, p []byte) (int, error) { return b.inner.Read(ctx, off, p) } diff --git a/seaweed-block/core/frontend/testback/testback.go b/seaweed-block/core/frontend/testback/testback.go index f4c0d4665a..0b173cbe3a 100644 --- a/seaweed-block/core/frontend/testback/testback.go +++ b/seaweed-block/core/frontend/testback/testback.go @@ -49,6 +49,10 @@ type WriteCall struct { Data []byte // defensive copy; safe to read after the call } +// SyncCall records one Sync call. Kept separate so tests can +// assert "Sync fired N times" without re-synthesizing from Write. +type SyncCall struct{} + // RecordingBackend is a frontend.Backend that stores every // Read/Write call plus bytes written at each offset. Used by L0 // tests that assert "the protocol target routed N reads/writes @@ -57,18 +61,25 @@ type WriteCall struct { // Holds an in-memory byte slab (like memback) so Read can // return the most-recent bytes written at that offset. type RecordingBackend struct { - mu sync.Mutex - id frontend.Identity - closed bool - reads []ReadCall - writes []WriteCall - data []byte + mu sync.Mutex + id frontend.Identity + closed bool + reads []ReadCall + writes []WriteCall + syncs []SyncCall + data []byte + + // T3a operational-gate state. Default true — recording backend + // is a test double with no readiness lifecycle; tests that want + // to exercise ErrNotReady call SetOperational(false, _). + operational bool + opEvidence string } // NewRecordingBackend constructs a fresh recording backend at // the given identity. func NewRecordingBackend(id frontend.Identity) *RecordingBackend { - return &RecordingBackend{id: id} + return &RecordingBackend{id: id, operational: true} } func (r *RecordingBackend) Identity() frontend.Identity { return r.id } @@ -86,6 +97,9 @@ func (r *RecordingBackend) Read(_ context.Context, offset int64, p []byte) (int, if r.closed { return 0, frontend.ErrBackendClosed } + if !r.operational { + return 0, frontend.ErrNotReady + } r.reads = append(r.reads, ReadCall{Offset: offset, Length: len(p)}) if offset < 0 || offset >= int64(len(r.data)) { return 0, nil @@ -99,6 +113,9 @@ func (r *RecordingBackend) Write(_ context.Context, offset int64, p []byte) (int if r.closed { return 0, frontend.ErrBackendClosed } + if !r.operational { + return 0, frontend.ErrNotReady + } cp := make([]byte, len(p)) copy(cp, p) r.writes = append(r.writes, WriteCall{Offset: offset, Data: cp}) @@ -141,6 +158,36 @@ func (r *RecordingBackend) ReadAt(i int) ReadCall { return r.reads[i] } +// Sync records one sync call; returns nil (no on-disk state). +// Subject to closed/operational gates. +func (r *RecordingBackend) Sync(_ context.Context) error { + r.mu.Lock() + defer r.mu.Unlock() + if r.closed { + return frontend.ErrBackendClosed + } + if !r.operational { + return frontend.ErrNotReady + } + r.syncs = append(r.syncs, SyncCall{}) + return nil +} + +// SyncCount returns the number of Sync calls. +func (r *RecordingBackend) SyncCount() int { + r.mu.Lock() + defer r.mu.Unlock() + return len(r.syncs) +} + +// SetOperational flips the readiness gate. See frontend.Backend godoc. +func (r *RecordingBackend) SetOperational(ok bool, evidence string) { + r.mu.Lock() + r.operational = ok + r.opEvidence = evidence + r.mu.Unlock() +} + // ---------- StaleRejectingBackend: every op returns ErrStalePrimary. ---------- // StaleRejectingBackend is a frontend.Backend whose Read and @@ -183,6 +230,15 @@ func (s *StaleRejectingBackend) Write(_ context.Context, _ int64, _ []byte) (int return 0, frontend.ErrStalePrimary } +// Sync matches Read/Write — always stale. +func (s *StaleRejectingBackend) Sync(_ context.Context) error { + return frontend.ErrStalePrimary +} + +// SetOperational is a no-op — this backend is defined by its +// error shape, not a readiness gate. +func (s *StaleRejectingBackend) SetOperational(_ bool, _ string) {} + // Compile-time checks so type drift shows up early. var ( _ frontend.Backend = (*RecordingBackend)(nil) diff --git a/seaweed-block/core/frontend/types.go b/seaweed-block/core/frontend/types.go index 75f914b400..6169b6f1bf 100644 --- a/seaweed-block/core/frontend/types.go +++ b/seaweed-block/core/frontend/types.go @@ -48,9 +48,25 @@ type ProjectionView interface { } // Backend is a per-lineage handle for one open frontend session. +// +// T3a extends the interface with two methods (all existing +// implementations gain trivial impls in the same commit): +// +// - Sync: frontends emit this on SYNCHRONIZE CACHE / Flush. +// For durable backends it calls LogicalStorage.Sync; for +// in-memory backends it is a no-op returning nil. +// +// - SetOperational: lifecycle gate controlled by the host / +// provider. Before SetOperational(true, _) is called, every +// I/O MUST return ErrNotReady (see INV-DURABLE-OPGATE-001). +// This is local-readiness only — SetOperational does NOT +// touch identity/lineage/epoch; authority publication stays +// on the master path (PCDD-STUFFING-001). type Backend interface { Read(ctx context.Context, offset int64, p []byte) (int, error) Write(ctx context.Context, offset int64, p []byte) (int, error) + Sync(ctx context.Context) error + SetOperational(ok bool, evidence string) Identity() Identity Close() error } diff --git a/seaweed-block/core/storage/smartwal/superblock.go b/seaweed-block/core/storage/smartwal/superblock.go index 080f79bd25..9e210f089c 100644 --- a/seaweed-block/core/storage/smartwal/superblock.go +++ b/seaweed-block/core/storage/smartwal/superblock.go @@ -10,16 +10,34 @@ import ( // 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 = 1 + 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 @@ -35,14 +53,21 @@ type header struct { 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, + Version: headerVersion, + BlockSize: blockSize, + NumBlocks: numBlocks, + WALSlots: walSlots, + ImplKind: implKindSmartWAL, + ImplVersion: smartwalImplVersion, } copy(h.Magic[:], headerMagic) if _, err := rand.Read(h.UUID[:]); err != nil { @@ -67,6 +92,12 @@ func (h *header) writeTo(w io.Writer) error { 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) } @@ -101,6 +132,12 @@ func readHeader(r io.Reader) (header, error) { 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 } @@ -117,5 +154,9 @@ func (h *header) validate() error { if h.WALSlots == 0 { return fmt.Errorf("%w: WALSlots=0", errBadGeometry) } + // T3a Addendum A — ImplKind must match smartwal. + if h.ImplKind != implKindSmartWAL { + return fmt.Errorf("%w: got %d, want %d", errBadImpl, h.ImplKind, implKindSmartWAL) + } return nil } diff --git a/seaweed-block/core/storage/superblock.go b/seaweed-block/core/storage/superblock.go index 5ee4d52ab4..0fad23bf38 100644 --- a/seaweed-block/core/storage/superblock.go +++ b/seaweed-block/core/storage/superblock.go @@ -9,17 +9,45 @@ import ( ) // File-format identity. Bumped only on incompatible layout changes. +// +// Version history: +// 1: initial layout (magic+version+geometry+WAL state+CreatedAt) +// 2: T3a Addendum A — added ImplKind + ImplVersion at end of +// layout. Opening a v1 store with v2 code returns +// errSuperblockBadVer (one-way bump; no compat read path). const ( superblockSize = 4096 superblockMagic = "SWBK" - superblockVersion = 1 + superblockVersion = 2 ) +// ImplKind self-identifies which LogicalStorage implementation +// owns this file. DurableProvider compares the stored ImplKind +// against the selector at Open time and rejects mismatches with +// errSuperblockImplMismatch — prevents silently opening a +// walstore file as smartwal (or vice versa), which would then +// attempt an incompatible format parse. ImplKindUnset (0) on +// disk means the file predates T3a and is a format error. +type ImplKind uint8 + +const ( + ImplKindUnset ImplKind = 0 + ImplKindWALStore ImplKind = 1 + ImplKindSmartWAL ImplKind = 2 +) + +// WALStoreImplVersion is the per-impl schema version for walstore +// files. Independent from superblockVersion (which is the shared +// superblock-format version) — walstore and smartwal evolve their +// WAL+extent layouts on independent clocks. +const WALStoreImplVersion uint32 = 1 + var ( - errSuperblockNotOurs = errors.New("storage: not a store file (bad magic)") - errSuperblockBadVer = errors.New("storage: unsupported store version") - errSuperblockBadVolume = errors.New("storage: invalid volume size") - errSuperblockInvalid = errors.New("storage: invalid superblock") + errSuperblockNotOurs = errors.New("storage: not a store file (bad magic)") + errSuperblockBadVer = errors.New("storage: unsupported store version") + errSuperblockBadVolume = errors.New("storage: invalid volume size") + errSuperblockInvalid = errors.New("storage: invalid superblock") + errSuperblockImplUnknown = errors.New("storage: unknown impl kind") ) // superblock is the 4KB header at offset 0 of a store file. It @@ -43,10 +71,21 @@ type superblock struct { WALTail uint64 // monotonic WAL flush position WALCheckpointLSN uint64 // last LSN durably present in extent CreatedAt uint64 // unix nanoseconds + + // T3a Addendum A Addition 2 — impl self-identity. + // ImplKind is the store implementation (walstore vs smartwal); + // ImplVersion is the per-impl schema version. DurableProvider + // compares stored ImplKind against the selector at Open time + // and rejects mismatches fast. + ImplKind ImplKind + ImplVersion uint32 } // newSuperblock constructs a superblock with defaults and a fresh -// UUID. Caller-supplied geometry overrides defaults. +// UUID. Caller-supplied geometry overrides defaults. The caller +// MUST pass a valid ImplKind (WALStore / SmartWAL) — unset (0) +// rejected at validate() time so no file can ever persist with +// unidentified impl. func newSuperblock(volumeSize uint64, opts createOptions) (superblock, error) { if volumeSize == 0 { return superblock{}, errSuperblockBadVolume @@ -63,13 +102,25 @@ func newSuperblock(volumeSize uint64, opts createOptions) (superblock, error) { if walSize == 0 { walSize = 64 * 1024 * 1024 } + if opts.ImplKind == ImplKindUnset { + return superblock{}, fmt.Errorf("%w: ImplKind is unset (0)", errSuperblockImplUnknown) + } + if opts.ImplKind != ImplKindWALStore && opts.ImplKind != ImplKindSmartWAL { + return superblock{}, fmt.Errorf("%w: ImplKind=%d", errSuperblockImplUnknown, opts.ImplKind) + } + implVersion := opts.ImplVersion + if implVersion == 0 { + implVersion = WALStoreImplVersion + } sb := superblock{ - Version: superblockVersion, - VolumeSize: volumeSize, - ExtentSize: extentSize, - BlockSize: blockSize, - WALOffset: superblockSize, - WALSize: walSize, + Version: superblockVersion, + VolumeSize: volumeSize, + ExtentSize: extentSize, + BlockSize: blockSize, + WALOffset: superblockSize, + WALSize: walSize, + ImplKind: opts.ImplKind, + ImplVersion: implVersion, } copy(sb.Magic[:], superblockMagic) if _, err := rand.Read(sb.UUID[:]); err != nil { @@ -106,6 +157,13 @@ func (sb *superblock) writeTo(w io.Writer) (int64, error) { le.PutUint64(buf[off:], sb.WALCheckpointLSN) off += 8 le.PutUint64(buf[off:], sb.CreatedAt) + off += 8 + // T3a Addendum A Addition 2 — ImplKind + ImplVersion. + buf[off] = uint8(sb.ImplKind) + off++ + // 3 bytes reserved for future ImplKind expansion / alignment. + off += 3 + le.PutUint32(buf[off:], sb.ImplVersion) n, err := w.Write(buf) return int64(n), err @@ -154,6 +212,12 @@ func readSuperblock(r io.Reader) (superblock, error) { sb.WALCheckpointLSN = le.Uint64(buf[off:]) off += 8 sb.CreatedAt = le.Uint64(buf[off:]) + off += 8 + // T3a Addendum A Addition 2. + sb.ImplKind = ImplKind(buf[off]) + off++ + off += 3 // reserved + sb.ImplVersion = le.Uint32(buf[off:]) return sb, nil } @@ -185,6 +249,14 @@ func (sb *superblock) validate() error { return fmt.Errorf("%w: VolumeSize %d not aligned to BlockSize %d", errSuperblockInvalid, sb.VolumeSize, sb.BlockSize) } + // T3a Addendum A: ImplKind must be set and recognized. + if sb.ImplKind == ImplKindUnset { + return fmt.Errorf("%w: ImplKind is unset (0); file predates T3a or is corrupted", + errSuperblockImplUnknown) + } + if sb.ImplKind != ImplKindWALStore && sb.ImplKind != ImplKindSmartWAL { + return fmt.Errorf("%w: ImplKind=%d", errSuperblockImplUnknown, sb.ImplKind) + } return nil } @@ -193,4 +265,9 @@ type createOptions struct { BlockSize uint32 // default 4096 ExtentSize uint32 // default 64KB WALSize uint64 // default 64MB + + // T3a Addendum A — impl self-identity. Required (no default); + // newSuperblock rejects ImplKindUnset (0). + ImplKind ImplKind + ImplVersion uint32 // default WALStoreImplVersion } diff --git a/seaweed-block/core/storage/walstore.go b/seaweed-block/core/storage/walstore.go index b0b086f446..f7f96c490b 100644 --- a/seaweed-block/core/storage/walstore.go +++ b/seaweed-block/core/storage/walstore.go @@ -97,8 +97,10 @@ func CreateWALStore(path string, numBlocks uint32, blockSize int) (*WALStore, er volumeBytes := uint64(numBlocks) * uint64(blockSize) sb, err := newSuperblock(volumeBytes, createOptions{ - BlockSize: uint32(blockSize), - ExtentSize: uint32(blockSize), // one block per extent slot keeps math trivial + BlockSize: uint32(blockSize), + ExtentSize: uint32(blockSize), // one block per extent slot keeps math trivial + ImplKind: ImplKindWALStore, + ImplVersion: WALStoreImplVersion, }) if err != nil { _ = f.Close()