Files
seaweedfs/seaweed-block/core/frontend/memback/backend.go
T
wzcheng99andClaude Opus 4.7 10cd117bb4 T3a: StorageBackend adapter + Backend interface extension + superblock impl-identity
Atomic per T3a mini plan §3 stop rules #1-#3:
  - Adapter file atomic (G-int.1 + G-int.2 + G-int.3 one commit)
  - Interface extension atomic with all consumers
  - Superblock schema bump one-way with migration discipline

## Scope delivered (mini plan §0)

### 1. core/frontend/durable/storage_adapter.go (NEW)

StorageBackend wraps any LogicalStorage and exposes the full
frontend.Backend surface. Four responsibilities:

  - byte↔LBA translation with RMW on partial blocks (G-int.1)
  - per-I/O fence check preserving INV-FRONTEND-002.* (G-int.2)
  - operational gate preserving INV-DURABLE-OPGATE-001 (G-int.3)
  - Sync dispatches to LogicalStorage.Sync (G-int.2 policy)

Storage lifecycle NOT owned by backend — Close marks the handle
closed but does not tear down LogicalStorage (Provider owns that,
lands in T3b).

### 2. Backend interface extension (core/frontend/types.go)

Two new methods: Sync(ctx) error + SetOperational(ok, evidence).
SetOperational godoc pins the invariant: does NOT touch identity
/lineage/epoch — local readiness only; authority publication stays
on the master path (PCDD-STUFFING-001).

All 6 existing Backend implementations gain trivial impls in the
same commit (stop rule #2):
  - memback.backend (Sync no-op, SetOperational state-flip)
  - testback.RecordingBackend (SyncCall recording, SyncCount)
  - testback.StaleRejectingBackend (Sync returns ErrStalePrimary)
  - iscsi countingBackend (delegates)
  - nvme countingFaultBackend (delegates)
  - nvme writeCountingBackend (delegates)

### 3. Superblock impl-identity (Addendum A Addition 2)

Both walstore (core/storage/superblock.go) and smartwal
(core/storage/smartwal/superblock.go) headers gain ImplKind +
ImplVersion fields. superblockVersion/headerVersion bumped 1→2.

  - newSuperblock rejects ImplKindUnset (0) at create time
  - readSuperblock + validate reject unknown ImplKind
  - CreateWALStore passes ImplKindWALStore=1 + WALStoreImplVersion=1
  - smartwal.newHeader passes implKindSmartWAL=2 + smartwalImplVersion=1

Stop rule #3 (one-way bump): no compat read path for v1; opening
a v1 file with v2 code returns errSuperblockBadVer. No existing
on-disk production data expected since T3 hasn't shipped.

### 4. Matrix test infrastructure (Addendum A Addition 1)

core/frontend/durable/storage_adapter_test.go uses a single shared
logicalStorageFactories() helper returning {walstore, smartwal}
factories. Every adapter test iterates over it — adding a new impl
later = one edit (stop rule #4). TestT3a_MatrixCoverage is a
sanity canary that trips if the factory list drifts.

## Tests landed (mini plan §2 acceptance)

  #1 TestT3a_StorageBackend_ImplementsBackend          ✅ walstore + smartwal
  #2 TestT3a_StorageBackend_ByteLBATranslation_Matrix  ✅ 6 shape subtests × 2 impls
  #3 TestT3a_StorageBackend_FenceCheck_{Epoch,EV,Replica,Healthy} ✅ 4×2
  #4 TestT3a_StorageBackend_OperationalGate_{BeforeOpen,FlipBack,Evidence} ✅ 3×2
  #5 TestT3a_StorageBackend_Sync_DispatchesToStorage   ✅ 2 impls
  #6 All tests matrix-parameterized — N×2 execution
     TestT3a_MatrixCoverage canary pins factory count
  #7/#8 Superblock schema bump covered by existing core/storage tests:
        - newSuperblock rejects ImplKindUnset at create
        - readSuperblock rejects unknown ImplKind at open
        - CurrentVersion bump is forward-only
  #9 Full regression green: 17 core packages, incl. prior T0/T1/T2 suites
  #10 boundary_guard_test.go auto-covers core/frontend/durable/
      (TestFrontendCannotMintAuthority_BoundaryGuard walks the whole
      frontend tree recursively; no explicit extension needed)

## Regression

  go test ./core/... -count=1 → 17/17 packages ok
  - core/frontend: 17.7s
  - core/frontend/durable: 0.3s (22 subtests all green)
  - core/frontend/iscsi: 31.3s (no regression)
  - core/frontend/nvme: 61.1s (no regression)
  - core/storage: 7.2s (schema bump accepted)
  - core/storage/smartwal: 0.3s
  - core/host: 122.4s
  - All others sub-second

## Out of T3a per mini plan

  - DurableProvider (T3b)
  - Recovery integration (T3b)
  - iSCSI SYNCHRONIZE CACHE / NVMe Flush wiring (T3b)
  - 4 G6 scenarios + perf baseline (T3c)

## Ledger rows queued ACTIVE at T3a close

  - INV-DURABLE-OPGATE-001 (operational gate preserves INV-FRONTEND-002.*)
  - INV-DURABLE-IMPL-IDENTITY-001 (superblock self-identifies; mismatch fails fast)

## References

  sw-block/design/v3-phase-15-t3-port-audit.md (T3.0 LOCKED)
  sw-block/design/v3-phase-15-t3a-mini-plan.md (this batch spec)
  feedback_porting_discipline.md (port-model discipline)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 17:21:41 -07:00

142 lines
3.7 KiB
Go

package memback
import (
"context"
"sync"
"sync/atomic"
"github.com/seaweedfs/seaweed-block/core/frontend"
)
// volumeStore is a trivial byte slice addressed by offset.
// Grows on Write; Read returns zeros past end-of-store. Shared
// across all backends opened against the same Identity.
type volumeStore struct {
mu sync.Mutex
data []byte
}
func newVolumeStore() *volumeStore { return &volumeStore{} }
// ErrInvalidOffset is returned from Read/Write when the caller
// passes a negative offset. Kept distinct from ErrStalePrimary /
// ErrBackendClosed because it's a caller-input defect, not a
// lineage or lifecycle fault.
var ErrInvalidOffset = errInvalidOffset{}
type errInvalidOffset struct{}
func (errInvalidOffset) Error() string { return "memback: invalid (negative) offset" }
func (s *volumeStore) read(offset int64, p []byte) (int, error) {
if offset < 0 {
return 0, ErrInvalidOffset
}
s.mu.Lock()
defer s.mu.Unlock()
if offset >= int64(len(s.data)) {
return 0, nil
}
return copy(p, s.data[offset:]), nil
}
func (s *volumeStore) write(offset int64, p []byte) (int, error) {
if offset < 0 {
return 0, ErrInvalidOffset
}
s.mu.Lock()
defer s.mu.Unlock()
need := int(offset) + len(p)
if need > len(s.data) {
s.data = append(s.data, make([]byte, need-len(s.data))...)
}
return copy(s.data[offset:], p), nil
}
// backend is the per-open memback Backend. Holds a frozen
// Identity captured at Open time and re-reads the projection on
// every I/O to fence stale primary (sketch §7).
type backend struct {
view frontend.ProjectionView
id frontend.Identity
store *volumeStore
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 {
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 }
func (b *backend) Close() error {
b.mu.Lock()
defer b.mu.Unlock()
b.closed = true
return nil
}
func (b *backend) Read(_ context.Context, offset int64, p []byte) (int, error) {
if err := b.guard(); err != nil {
return 0, err
}
return b.store.read(offset, p)
}
func (b *backend) Write(_ context.Context, offset int64, p []byte) (int, error) {
if err := b.guard(); err != nil {
return 0, err
}
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
// AND the projection is healthy. ANY drift returns
// ErrStalePrimary; partial matches do not count.
func (b *backend) guard() error {
b.mu.Lock()
closed := b.closed
b.mu.Unlock()
if closed {
return frontend.ErrBackendClosed
}
if !b.operational.Load() {
return frontend.ErrNotReady
}
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
}