Files
seaweedfs/seaweed-block/core/frontend/testback/testback.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

248 lines
7.3 KiB
Go

// Package testback holds sw-owned test doubles for the T2
// frontend contract work. Used by BOTH core/frontend/iscsi and
// core/frontend/nvme test suites so the three canonical test
// fakes (RecordingBackend, StaleRejectingBackend, StaticProvider)
// don't get duplicated per-protocol.
//
// These are NOT production types. They live in a separate
// package so the boundary guard in core/frontend can still
// refuse any _test.go imports of authority/adapter — testback
// has no such imports by design.
package testback
import (
"context"
"sync"
"github.com/seaweedfs/seaweed-block/core/frontend"
)
// ---------- StaticProvider: returns a preconfigured backend. ----------
// StaticProvider is a frontend.Provider that returns a single,
// preconfigured backend on every Open. Used by L0 tests that
// want the backend handle directly without wiring a real
// AdapterProjectionView.
type StaticProvider struct{ Backend frontend.Backend }
// NewStaticProvider constructs a provider that hands out b on
// every Open.
func NewStaticProvider(b frontend.Backend) *StaticProvider { return &StaticProvider{Backend: b} }
// Open returns the statically-configured backend. ctx is
// ignored because the backend is already "ready".
func (p *StaticProvider) Open(_ context.Context, _ string) (frontend.Backend, error) {
return p.Backend, nil
}
// ---------- RecordingBackend: captures every Read/Write call. ----------
// ReadCall records one Read call's arguments.
type ReadCall struct {
Offset int64
Length int
}
// WriteCall records one Write call's arguments.
type WriteCall struct {
Offset int64
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
// to the frontend backend with exactly these args".
//
// 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
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, operational: true}
}
func (r *RecordingBackend) Identity() frontend.Identity { return r.id }
func (r *RecordingBackend) Close() error {
r.mu.Lock()
defer r.mu.Unlock()
r.closed = true
return nil
}
func (r *RecordingBackend) Read(_ context.Context, offset int64, p []byte) (int, error) {
r.mu.Lock()
defer r.mu.Unlock()
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
}
return copy(p, r.data[offset:]), nil
}
func (r *RecordingBackend) Write(_ context.Context, offset int64, p []byte) (int, error) {
r.mu.Lock()
defer r.mu.Unlock()
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})
if offset < 0 {
return 0, frontend.ErrStalePrimary // shouldn't be called; caller contract
}
need := int(offset) + len(p)
if need > len(r.data) {
r.data = append(r.data, make([]byte, need-len(r.data))...)
}
return copy(r.data[offset:], p), nil
}
// WriteCount returns the number of Write calls so far.
func (r *RecordingBackend) WriteCount() int {
r.mu.Lock()
defer r.mu.Unlock()
return len(r.writes)
}
// ReadCount returns the number of Read calls so far.
func (r *RecordingBackend) ReadCount() int {
r.mu.Lock()
defer r.mu.Unlock()
return len(r.reads)
}
// WriteAt returns the i-th recorded write, panicking if out of
// range. Matches the pattern QA's L0 spec uses.
func (r *RecordingBackend) WriteAt(i int) WriteCall {
r.mu.Lock()
defer r.mu.Unlock()
return r.writes[i]
}
// ReadAt returns the i-th recorded read.
func (r *RecordingBackend) ReadAt(i int) ReadCall {
r.mu.Lock()
defer r.mu.Unlock()
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
// Write always return frontend.ErrStalePrimary. Used by L0
// tests that assert the protocol target maps ErrStalePrimary
// to the correct protocol failure (SCSI CHECK CONDITION /
// NVMe CQE error status).
//
// Identity is fixed at construction so Identity() still returns
// a stable lineage — the backend exists in the sense of
// "opened", it just refuses every I/O.
type StaleRejectingBackend struct {
id frontend.Identity
}
// NewStaleRejectingBackend builds one. Identity defaults to a
// non-zero lineage so callers can't accidentally conflate with
// "never opened".
func NewStaleRejectingBackend() *StaleRejectingBackend {
return &StaleRejectingBackend{
id: frontend.Identity{
VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1,
},
}
}
// NewStaleRejectingBackendAt builds one with a specific Identity.
func NewStaleRejectingBackendAt(id frontend.Identity) *StaleRejectingBackend {
return &StaleRejectingBackend{id: id}
}
func (s *StaleRejectingBackend) Identity() frontend.Identity { return s.id }
func (s *StaleRejectingBackend) Close() error { return nil }
func (s *StaleRejectingBackend) Read(_ context.Context, _ int64, _ []byte) (int, error) {
return 0, frontend.ErrStalePrimary
}
func (s *StaleRejectingBackend) Write(_ context.Context, _ int64, _ []byte) (int, error) {
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)
_ frontend.Backend = (*StaleRejectingBackend)(nil)
_ frontend.Provider = (*StaticProvider)(nil)
)