diff --git a/seaweed-block/core/frontend/durable/export_chunk_test.go b/seaweed-block/core/frontend/durable/export_chunk_test.go index 7a499b43d7..7c74e579b7 100644 --- a/seaweed-block/core/frontend/durable/export_chunk_test.go +++ b/seaweed-block/core/frontend/durable/export_chunk_test.go @@ -24,3 +24,8 @@ func SetTestDetachTrace(p *DurableProvider, f func(stage string, deadline time.T // SetTestBeforeIOLock runs f in the backend's admission, right before the I/O // lock (test-only). func SetTestBeforeIOLock(b frontend.Backend, f func()) { b.(*StorageBackend).testBeforeIOLock = f } + +// SetTestBeforeAttachWait observes the first registered readiness wait. +func SetTestBeforeAttachWait(b frontend.Backend, f func()) { + b.(*StorageBackend).testBeforeReadReadyWait = f +} diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index 2fa5faf8bb..72ba48299c 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -878,7 +878,7 @@ func (p *DurableProvider) RecoverVolume(ctx context.Context, volumeID string) (R // Recovered; I/O stays refused until the layer attaches under // the master's assignment (the authority wait flips it). report.Evidence += "; chunk layer awaiting master authority" - h.backend.SetOperational(false, report.Evidence) + h.backend.setChunkAttachPending(report.Evidence) return report, nil } if err := chunkFenced(volumeID, h); err != nil { diff --git a/seaweed-block/core/frontend/durable/read_ready_wait_test.go b/seaweed-block/core/frontend/durable/read_ready_wait_test.go new file mode 100644 index 0000000000..c19c8c1373 --- /dev/null +++ b/seaweed-block/core/frontend/durable/read_ready_wait_test.go @@ -0,0 +1,112 @@ +package durable + +import ( + "context" + "errors" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" +) + +func TestReadReadinessWaitDoesNotHoldAdmissionAndCloseWakesIt(t *testing.T) { + for _, mode := range []string{"close", "drain-then-close", "fence", "write-close"} { + name := mode + t.Run(name, func(t *testing.T) { + // No storage is needed: this read must never pass the operational gate. + b := &StorageBackend{waitAttachReady: true} + b.opEvidence.Store("attachment pending") + registered := make(chan struct{}, 1) + resume := make(chan struct{}) + var once sync.Once + release := func() { once.Do(func() { close(resume) }) } + b.testBeforeReadReadyWait = func() { + select { + case registered <- struct{}{}: + default: + } + <-resume + } + done := make(chan error, 1) + joined := make(chan struct{}) + t.Cleanup(func() { + release() + _ = b.Close() + select { + case <-joined: + case <-time.After(5 * time.Second): + t.Error("pending read did not settle after release and Close") + } + }) + go func() { + defer close(joined) + var err error + if mode == "write-close" { + _, err = b.Write(context.Background(), 0, make([]byte, 4096)) + } else { + _, err = b.Read(context.Background(), 0, make([]byte, 4096)) + } + done <- err + }() + select { + case <-registered: + case <-time.After(time.Second): + t.Fatal("read did not register a readiness notification") + } + if mode == "drain-then-close" { + ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) + defer cancel() + if err := b.StopIO(ctx, "attachment still pending"); err != nil { + t.Fatalf("waiting read held I/O admission: %v", err) + } + } + want := frontend.ErrBackendClosed + if mode == "fence" { + b.mu.Lock() + b.chunkFenced = func() bool { return true } + b.mu.Unlock() + b.SetOperational(false, "fenced") + want = frontend.ErrStalePrimary + } else if err := b.Close(); err != nil { + t.Fatal(err) + } + release() + select { + case err := <-done: + if !errors.Is(err, want) { + t.Fatalf("Close wake error=%v", err) + } + case <-time.After(time.Second): + t.Fatal("Close did not wake registered read") + } + }) + } +} + +type readinessProjection frontend.Projection + +func (p readinessProjection) Projection() frontend.Projection { return frontend.Projection(p) } + +func TestAttachReadinessTimeoutPreservesStaleLineage(t *testing.T) { + id := frontend.Identity{VolumeID: "v", ReplicaID: "r", Epoch: 1, EndpointVersion: 1} + b := &StorageBackend{id: id, view: readinessProjection{VolumeID: "v", ReplicaID: "r", Epoch: 2, EndpointVersion: 1, Healthy: true}} + b.setChunkAttachPending("pending") + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + b.testBeforeReadReadyWait = func() { b.SetOperational(true, "attached under another epoch"); cancel() } + _, err := b.Read(ctx, 0, make([]byte, 4096)) + if !errors.Is(err, frontend.ErrStalePrimary) { + t.Fatalf("timeout lost stale lineage: %v", err) + } +} + +func TestAttachReadinessPublicationRetriesAdmission(t *testing.T) { + id := frontend.Identity{VolumeID: "v", ReplicaID: "r", Epoch: 1, EndpointVersion: 1} + b := &StorageBackend{id: id, view: readinessProjection{VolumeID: "v", ReplicaID: "r", Epoch: 1, EndpointVersion: 1, Healthy: true}} + b.setChunkAttachPending("pending") + b.testAfterAttachRefusal = func() { b.SetOperational(true, "attached") } + if _, err := b.Read(context.Background(), 0, nil); err != nil { + t.Fatalf("readiness publication returned the old refusal: %v", err) + } +} diff --git a/seaweed-block/core/frontend/durable/storage_adapter.go b/seaweed-block/core/frontend/durable/storage_adapter.go index c7ec6169e9..b607073763 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter.go +++ b/seaweed-block/core/frontend/durable/storage_adapter.go @@ -149,6 +149,9 @@ type StorageBackend struct { // testBeforeIOLock, test-only, runs in admit after the readiness check, // right before the I/O lock (an arrival handshake for queued I/O). testBeforeIOLock func() + // Runs outside locks after a read registers its readiness notification. + testBeforeReadReadyWait func() + testAfterAttachRefusal func() storage storage.LogicalStorage view frontend.ProjectionView @@ -159,8 +162,12 @@ type StorageBackend struct { // 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 + // Only a successfully recovered chunk volume awaiting attachment may wait. + // waitAttachReady and readyChanged are protected by mu. + waitAttachReady bool + readyChanged chan struct{} + operational atomic.Bool + opEvidence atomic.Value // string // ioMu is the I/O admission boundary: every Read, Write and Sync holds // its read side for the whole operation, gate included, so StopIO can @@ -351,6 +358,7 @@ func (b *StorageBackend) Close() error { b.mu.Lock() defer b.mu.Unlock() b.closed = true + b.notifyReadReadyLocked() return nil } @@ -379,12 +387,14 @@ func (b *StorageBackend) SetWriteObserver(obs WriteObserver) error { err = fmt.Errorf("durable: write observer not installed: ship LSN: %w", err) b.mu.Lock() b.observerErr = err + b.notifyReadReadyLocked() b.mu.Unlock() return err } } b.mu.Lock() b.observer, b.observerErr = obs, nil + b.notifyReadReadyLocked() b.mu.Unlock() return nil } @@ -409,6 +419,7 @@ func (b *StorageBackend) seedAndRebase(seed func() error) error { err = fmt.Errorf("durable: write observer ship LSN after the frontier seed: %w", err) b.mu.Lock() b.observerErr = err + b.notifyReadReadyLocked() b.mu.Unlock() return err } @@ -452,8 +463,12 @@ func (b *StorageBackend) SetOperational(ok bool, evidence string) { evidence = "not operational" } } + b.mu.Lock() b.opEvidence.Store(evidence) b.operational.Store(ok) + b.waitAttachReady = false + b.notifyReadReadyLocked() + b.mu.Unlock() } // StopIO makes the backend refuse every new Read, Write and Sync with @@ -539,7 +554,7 @@ func (b *StorageBackend) Sync(ctx context.Context) error { // 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) { - release, err := b.admit() + release, err := b.admitAfterAttach(ctx) if err != nil { return 0, err } @@ -547,9 +562,99 @@ func (b *StorageBackend) Read(ctx context.Context, offset int64, p []byte) (int, if len(p) == 0 { return 0, nil } + if ctx.Err() != nil { + return 0, b.attachReadyTimeout(ctx.Err()) + } return b.readBytes(offset, p) } +// setChunkAttachPending is used only after successful local recovery. +func (b *StorageBackend) setChunkAttachPending(evidence string) { + b.mu.Lock() + b.opEvidence.Store(evidence) + b.operational.Store(false) + b.waitAttachReady = true + b.notifyReadReadyLocked() + b.mu.Unlock() +} + +func (b *StorageBackend) admitAfterAttach(ctx context.Context) (func(), error) { + release, err := b.admit() + if !errors.Is(err, frontend.ErrNotReady) { + return release, err + } + if hook := b.testAfterAttachRefusal; hook != nil { + hook() + } + b.mu.Lock() + pending := b.waitAttachReady + b.mu.Unlock() + if !pending { + // Readiness may have published after the initial refusal. + return b.admit() + } + ctx, cancel := context.WithTimeout(ctx, 3*time.Second) + defer cancel() + return b.awaitAttachAdmission(ctx) +} + +// notifyReadReadyLocked wakes waiting I/O without making them hold ioMu while +// the provider is attaching or draining the backend. Caller holds mu. +func (b *StorageBackend) notifyReadReadyLocked() { + if b.readyChanged != nil { + close(b.readyChanged) + b.readyChanged = nil + } +} + +// awaitAttachAdmission waits only after a gate refusal, before any storage I/O. +// The three-second readiness allowance is capped by an earlier caller deadline. +func (b *StorageBackend) awaitAttachAdmission(ctx context.Context) (func(), error) { + for { + b.mu.Lock() + if b.readyChanged == nil { + b.readyChanged = make(chan struct{}) + } + changed := b.readyChanged + terminal := b.closed || b.observerErr != nil || !b.waitAttachReady + b.mu.Unlock() + if err := ctx.Err(); err != nil { + return nil, b.attachReadyTimeout(err) + } + release, err := b.admit() + if err == nil { + if cause := ctx.Err(); cause != nil { + release() + return nil, b.attachReadyTimeout(cause) + } + return release, nil + } + if !errors.Is(err, frontend.ErrNotReady) || terminal || b.operational.Load() { + return release, err + } + if hook := b.testBeforeReadReadyWait; hook != nil { + hook() + } + select { + case <-changed: + case <-ctx.Done(): + return nil, b.attachReadyTimeout(ctx.Err()) + } + } +} + +func (b *StorageBackend) attachReadyTimeout(cause error) error { + // A concurrent Close, fence or observer failure must retain its gate error. + err := b.gate() + b.mu.Lock() + observerFailed := b.observerErr != nil + b.mu.Unlock() + if err != nil && (!errors.Is(err, frontend.ErrNotReady) || observerFailed) { + return err + } + return fmt.Errorf("%w: %w: chunk attachment readiness: %w", frontend.ErrNotReady, frontend.ErrBackendBusy, cause) +} + // 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. @@ -559,7 +664,7 @@ func (b *StorageBackend) Write(ctx context.Context, offset int64, p []byte) (int defer cancel() iolatency.BackendEnter(ctx) defer iolatency.BackendExit(ctx) - release, err := b.admit() + release, err := b.admitAfterAttach(ctx) if err != nil { log.Printf("durable: StorageBackend.Write gate-rejected offset=%d: %v", offset, err) return 0, err @@ -568,6 +673,9 @@ func (b *StorageBackend) Write(ctx context.Context, offset int64, p []byte) (int if len(p) == 0 { return 0, nil } + if ctx.Err() != nil { + return 0, b.attachReadyTimeout(ctx.Err()) + } b.profile.recordBackendWriteRequest(len(p)) start := time.Now() n, err := b.writeBytes(ctx, offset, p) diff --git a/seaweed-block/core/frontend/durable/takeover_read_ready_test.go b/seaweed-block/core/frontend/durable/takeover_read_ready_test.go new file mode 100644 index 0000000000..e2278f7b30 --- /dev/null +++ b/seaweed-block/core/frontend/durable/takeover_read_ready_test.go @@ -0,0 +1,183 @@ +package durable_test + +import ( + "bytes" + "context" + "errors" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/frontend/nvme" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// External observers see the committed takeover HEAD while attachment is +// held in the provider-owned worker, without a separate test goroutine. +type heldTakeoverClaim struct { + storage.ChunkRemote + claimed chan struct{} + release chan struct{} + once, releaseOnce sync.Once + holdFor time.Duration + readRegistered chan struct{} +} + +func (r *heldTakeoverClaim) unblock() { r.releaseOnce.Do(func() { close(r.release) }) } +func (r *heldTakeoverClaim) CASHead(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead) (uint64, error) { + gen, err := r.ChunkRemote.CASHead(ctx, expected, next) + if err != nil || next.Epoch != 4 { + return gen, err + } + r.once.Do(func() { close(r.claimed) }) + var expired <-chan time.Time + if r.holdFor > 0 { + select { + case <-r.readRegistered: + case <-r.release: + return gen, nil + case <-ctx.Done(): + return gen, ctx.Err() + } + timer := time.NewTimer(r.holdFor) + defer timer.Stop() + expired = timer.C + } + select { + case <-r.release: + return gen, nil + case <-expired: + return gen, nil + case <-ctx.Done(): + return gen, ctx.Err() + } +} + +func pendingTakeoverRead(t *testing.T, hold time.Duration) (*durable.DurableProvider, frontend.Backend, *nvme.IOHandler) { + t.Helper() + remote := &heldTakeoverClaim{ChunkRemote: seededRemote(t), claimed: make(chan struct{}), release: make(chan struct{}), holdFor: hold, readRegistered: make(chan struct{})} + view := newStubView(frontend.Projection{VolumeID: "v1", ReplicaID: "r1"}) + p := chunkProvider(t, t.TempDir(), remote, view, 0) + // Registered after provider cleanup, so release precedes its worker join. + t.Cleanup(remote.unblock) + if _, err := p.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + if _, err := p.RecoverVolume(context.Background(), "v1"); err != nil { + t.Fatal(err) + } + view.set(healthyProj(frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 4, EndpointVersion: 2})) + select { + case <-remote.claimed: + case <-time.After(10 * time.Second): + t.Fatal("takeover CAS never became visible") + } + head, err := remote.GetHead(context.Background()) + if err != nil || head.Epoch != 4 || head.Holder != "r1" { + t.Fatalf("takeover HEAD: %+v, %v", head, err) + } + backend, err := p.Open(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + var firstWait sync.Once + durable.SetTestBeforeAttachWait(backend, func() { firstWait.Do(func() { close(remote.readRegistered) }) }) + handler := nvme.NewIOHandler(nvme.HandlerConfig{Backend: backend, BlockSize: 4096, VolumeSize: pcBlocks * 4096, NSID: 1}) + return p, backend, handler +} + +// Model Linux max_retries=5 and CRD=0: at most six attempts, no sleeps. +// A status-only fix exhausts them during attachment and becomes guest EIO. +func TestWALStoreChunk_TakeoverReadBeforeAttachIsRetryable(t *testing.T) { + _, _, handler := pendingTakeoverRead(t, 2500*time.Millisecond) + command := nvme.IOCommand{Opcode: 0x02, NSID: 1, SLBA: 33, NLB: 1} + start := time.Now() + for attempt := 0; attempt <= 5; attempt++ { + result := handler.Handle(context.Background(), command) + if result.AsError() == nil { + if !bytes.Equal(result.Data, block(0x33)) { + t.Fatal("guest read returned incorrect HEAD bytes") + } + if elapsed := time.Since(start); elapsed >= 5*time.Second { + t.Fatalf("guest read took %s", elapsed) + } + t.Logf("guest read succeeded on attempt%d after%s (max5 immediate retries)", attempt+1, time.Since(start)) + return + } + if result.SCT != nvme.SCTGeneric || result.SC != nvme.SCNamespaceNotReady { + t.Fatalf("guest read terminal status: %v", result.AsError()) + } + } + t.Fatal("guest EIO: all six immediate attempts exhausted before chunk attach") +} + +func TestWALStoreChunk_PendingReadWaitIsBounded(t *testing.T) { + _, _, handler := pendingTakeoverRead(t, 0) + start := time.Now() + result := handler.Handle(context.Background(), nvme.IOCommand{Opcode: 0x02, NSID: 1, SLBA: 33, NLB: 1}) + elapsed := time.Since(start) + if result.SCT != nvme.SCTGeneric || result.SC != nvme.SCNamespaceNotReady || len(result.Data) != 0 { + t.Fatalf("pending read result: %+v", result) + } + if elapsed < 2500*time.Millisecond || elapsed >= 5*time.Second { + t.Fatalf("pending read wait=%s; want bounded readiness wait below5s", elapsed) + } +} + +func TestWALStoreChunk_PendingReadHonoursEarlierDeadline(t *testing.T) { + _, backend, _ := pendingTakeoverRead(t, 0) + ctx, cancel := context.WithTimeout(context.Background(), 40*time.Millisecond) + defer cancel() + start := time.Now() + n, err := backend.Read(ctx, 33*4096, make([]byte, 4096)) + if n != 0 || !errors.Is(err, frontend.ErrBackendBusy) || !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("deadline read: n=%d err=%v", n, err) + } + if time.Since(start) >= time.Second { + t.Fatal("read ignored earlier deadline") + } +} + +func TestWALStoreChunk_TakeoverWriteWaitsForAttach(t *testing.T) { + _, backend, _ := pendingTakeoverRead(t, 2500*time.Millisecond) + start := time.Now() + n, err := backend.Write(context.Background(), 33*4096, block(0x74)) + if err != nil || n != 4096 { + t.Fatalf("pending write: n=%d err=%v", n, err) + } + if elapsed := time.Since(start); elapsed >= 5*time.Second { + t.Fatalf("write waited %s", elapsed) + } + got := make([]byte, 4096) + if n, err := backend.Read(context.Background(), 33*4096, got); err != nil || n != 4096 || !bytes.Equal(got, block(0x74)) { + t.Fatalf("attached write readback: n=%d err=%v", n, err) + } +} + +func TestWALStoreChunk_PendingWriteHonoursEarlierDeadline(t *testing.T) { + _, backend, _ := pendingTakeoverRead(t, 0) + ctx, cancel := context.WithTimeout(context.Background(), 40*time.Millisecond) + defer cancel() + n, err := backend.Write(ctx, 33*4096, block(0x74)) + if n != 0 || !errors.Is(err, frontend.ErrBackendBusy) || !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("pending write deadline: n=%d err=%v", n, err) + } +} + +func TestWALStoreChunk_PendingAttachBeyondHostRetryBudget(t *testing.T) { + _, _, handler := pendingTakeoverRead(t, 0) + for attempt := 0; attempt <= 5; attempt++ { + start := time.Now() + result := handler.Handle(context.Background(), nvme.IOCommand{Opcode: 0x02, NSID: 1, SLBA: 33, NLB: 1}) + if result.SCT != nvme.SCTGeneric || result.SC != nvme.SCNamespaceNotReady || len(result.Data) != 0 { + t.Fatalf("attempt%d exposed data or terminal status: %+v", attempt, result) + } + if elapsed := time.Since(start); elapsed < 2500*time.Millisecond || elapsed >= 5*time.Second { + t.Fatalf("attempt%d wait=%s", attempt, elapsed) + } + } + // A permanently unavailable backend still exhausts a finite host retry policy; + // this control promises retryable completions and no bytes, not infinite availability. +} diff --git a/seaweed-block/core/frontend/errors.go b/seaweed-block/core/frontend/errors.go index 0368d64e3e..84691012a8 100644 --- a/seaweed-block/core/frontend/errors.go +++ b/seaweed-block/core/frontend/errors.go @@ -9,7 +9,8 @@ import "errors" var ErrStalePrimary = errors.New("frontend: stale primary lineage") // ErrNotReady is returned by Provider.Open when the projection -// never reports healthy before the context deadline. +// never reports healthy before the context deadline, and by a Backend +// while local recovery or chunk attachment is not yet operational. var ErrNotReady = errors.New("frontend: volume not ready") // ErrBackendClosed is returned by Backend.Read / Backend.Write diff --git a/seaweed-block/core/frontend/nvme/io.go b/seaweed-block/core/frontend/nvme/io.go index 8505b0627e..437737aa49 100644 --- a/seaweed-block/core/frontend/nvme/io.go +++ b/seaweed-block/core/frontend/nvme/io.go @@ -76,7 +76,7 @@ type IOResult struct { SC uint8 Data []byte // read payload (nil for writes / errors) Reason string - retryable bool // only transient backend pressure clears wire DNR + retryable bool // transient pressure or readiness refusal clears wire DNR } func (r IOResult) completionStatus() uint16 { return MakeStatusField(r.SCT, r.SC, !r.retryable) } @@ -307,7 +307,8 @@ func mapWriteBudgetError(ctx context.Context, err error, op string) IOResult { // mapBackendError translates frontend errors into NVMe CQE // status tuples. ErrStalePrimary → ANA Transition; -// ErrBackendClosed → ANA Inaccessible; anything else → Internal +// ErrBackendClosed → ANA Inaccessible; ErrNotReady → retryable Namespace +// Not Ready; anything else → Internal // Error (fail-closed; real-backend-specific mapping lands with // T3). func mapBackendError(err error, op string) IOResult { @@ -328,6 +329,9 @@ func mapBackendError(err error, op string) IOResult { Reason: "backend closed on " + op, } } + if errors.Is(err, frontend.ErrNotReady) { + return IOResult{SCT: SCTGeneric, SC: SCNamespaceNotReady, Reason: "backend not ready on " + op + ": " + err.Error(), retryable: true} + } return IOResult{ SCT: SCTGeneric, SC: SCInternalError, diff --git a/seaweed-block/core/frontend/nvme/read_ready_retry_test.go b/seaweed-block/core/frontend/nvme/read_ready_retry_test.go new file mode 100644 index 0000000000..0b89d1dfad --- /dev/null +++ b/seaweed-block/core/frontend/nvme/read_ready_retry_test.go @@ -0,0 +1,65 @@ +package nvme + +import ( + "context" + "errors" + "fmt" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/testback" +) + +type readyReadBackend struct { + frontend.Backend + err error +} + +func (b *readyReadBackend) Read(context.Context, int64, []byte) (int, error) { return 0, b.err } + +func TestSessionReadNotReadyIsRetryable(t *testing.T) { + for _, tc := range []struct { + name string + err error + sct, sc uint8 + dnr bool + }{ + {"attach-pending", fmt.Errorf("awaiting HEAD attach: %w", frontend.ErrNotReady), SCTGeneric, SCNamespaceNotReady, false}, + {"not-ready-closed", errors.Join(frontend.ErrNotReady, frontend.ErrBackendClosed), SCTPathRelated, SCPathAsymAccessInaccessible, true}, + {"not-ready-stale", errors.Join(frontend.ErrNotReady, frontend.ErrStalePrimary), SCTPathRelated, SCPathAsymAccessTransition, true}, + {"physical-fault", errors.New("physical read failure"), SCTGeneric, SCInternalError, true}, + {"closed", frontend.ErrBackendClosed, SCTPathRelated, SCPathAsymAccessInaccessible, true}, + {"stale", frontend.ErrStalePrimary, SCTPathRelated, SCPathAsymAccessTransition, true}, + } { + t.Run(tc.name, func(t *testing.T) { + backend := &readyReadBackend{Backend: testback.NewRecordingBackend(frontend.Identity{VolumeID: "v1"}), err: tc.err} + s := &Session{handler: NewIOHandler(HandlerConfig{Backend: backend}), respCh: make(chan *response, 1), done: make(chan struct{})} + req := &Request{} + req.capsule.OpCode = ioRead + req.capsule.NSID = 1 + s.handleRead(context.Background(), req) + resp := <-s.respCh + if want := MakeStatusField(tc.sct, tc.sc, tc.dnr); resp.resp.Status != want { + t.Fatalf("wire status=%#x want=%#x", resp.resp.Status, want) + } + }) + } +} + +func TestReadinessRetryDelayIsNotAdvertised(t *testing.T) { + s := &Session{target: &Target{cfg: TargetConfig{VolumeID: "v1"}}, handler: &IOHandler{}, ctrl: &adminController{}, respCh: make(chan *response, 1), done: make(chan struct{})} + controller := s.buildIdentifyController() + for offset := 128; offset < 134; offset++ { + if controller[offset] != 0 { + t.Fatalf("CRDT byte%d=%d; host-policy control assumes no retry delay", offset, controller[offset]) + } + } + req := &Request{} + req.capsule.D10 = 0x16 // Host Behavior Support, including ACRE. + if err := s.handleSetFeatures(req); err != nil { + t.Fatal(err) + } + if got := (<-s.respCh).resp.Status; got != MakeStatusField(SCTGeneric, SCInvalidField, true) { + t.Fatalf("unsupported Host Behavior status=%#x", got) + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 71a6273f44..e34a286148 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -307,7 +307,7 @@ snapshot lifetime; local persistence does not bypass it. ## Part B. Invariant ledger -80 rows: 69 ACTIVE, 11 STUB; 15 kept from the internal ledger, 65 new. +81 rows: 70 ACTIVE, 11 STUB; 15 kept from the internal ledger, 66 new. The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger. @@ -317,6 +317,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w |---|---|---|---|---|---|---| | `INV-WAL-SYNCED-RECOVERED-001` | After a crash without media corruption, `Recover` returns every write that a `Sync` acknowledged. | M1 Recovering → Serving | `core/storage/recovery.go` `recoverWAL`; `core/storage/walstore.go` `WALStore.Recover` | `TestWALStoreAppendDuringFlushThenTornWrapKeepsSyncedRecords`, `TestWALStoreFullFlushThenTornWrapKeepsSyncedRecords` (`core/storage/walstore_persisted_tail_test.go`) | `WALRecovery` `I1` | 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` | Reads and writes on successfully recovered chunk volumes awaiting attachment wait up to 3s (or an earlier caller deadline) for attachment readiness before storage admission; NVMe readiness timeout/refusal returns Namespace Not Ready (SC0x82), DNR=0, without reading or mutating storage; closed/stale lineage retain their ANA errors and physical I/O faults retain Internal Error. | M1 Opened / Recovering → Serving | `core/frontend/durable/storage_adapter.go` `readyCheck`; `core/frontend/nvme/io.go` `mapBackendError` | `TestWALStoreChunk_TakeoverReadBeforeAttachIsRetryable`; `TestSessionReadNotReadyIsRetryable`; `TestWALStoreChunk_PendingReadWaitIsBounded`; `TestWALStoreChunk_PendingReadHonoursEarlierDeadline`; `TestReadReadinessWaitDoesNotHoldAdmissionAndCloseWakesIt`; `TestWALStoreChunk_TakeoverWriteWaitsForAttach`; `TestWALStoreChunk_PendingAttachBeyondHostRetryBudget` | — | ACTIVE | | `INV-WAL-REPLAY-LWW-001` | Replay applies the highest LSN per LBA, independent of the physical scan order. | M1 Recovering | `core/storage/dirty_map.go` `putAtIfNewer` | `TestWALStoreRecoverLastWriterWinsAcrossScanOrder` (`core/storage/walstore_recovery_lww_test.go`) | `WALRecovery` `ReplayLastWriter` | ACTIVE | | `INV-WAL-REUSE-PERSISTED-TAIL-001` | The WAL writer reuses only bytes that the on-disk superblock has already released. | M1 write lifecycle: Checkpointed → Reusable | `core/storage/wal_writer.go` `spaceUsed`, `tailPersisted`; `core/storage/walstore.go` `persistCheckpointReleasing` | `TestWALWriterReuseIsBoundedByTheDurableTail`, `TestWALStoreRecoverBoundsPersistFailureRefusesAppendsUntilRetry` (`core/storage/walstore_persisted_tail_test.go`) | `WALRecovery` `I1` | ACTIVE | | `INV-WAL-CHECKPOINT-SNAPSHOT-001` | A checkpoint never passes a synced write that is not yet in the extent. | M1 write lifecycle: InExtent → Checkpointed | `core/storage/flusher.go` `flushOnceInternal` | `TestFlusherSnapshotCutPreservesSyncedWrites` (`core/storage/flusher_snapshot_cut_test.go`); `TestWALStoreCheckpointSIGKILLCrashWindows` (`core/storage/walstore_checkpoint_crash_linux_test.go`) | `WALRecovery` `I1` | ACTIVE |