From faceab21d3f56057993cfd4dc7d6724569f6e726 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 06:45:24 -0800 Subject: [PATCH 01/12] test(nvme): reproduce reads during delayed chunk attachment --- .../durable/takeover_read_ready_test.go | 66 +++++++++++++++++++ .../frontend/nvme/read_ready_retry_test.go | 45 +++++++++++++ 2 files changed, 111 insertions(+) create mode 100644 seaweed-block/core/frontend/durable/takeover_read_ready_test.go create mode 100644 seaweed-block/core/frontend/nvme/read_ready_retry_test.go 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..c10221bc3f --- /dev/null +++ b/seaweed-block/core/frontend/durable/takeover_read_ready_test.go @@ -0,0 +1,66 @@ +package durable_test + +import ( + "bytes" + "context" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/nvme" +) + +// The frontend can connect after authority arrives but before the fresh +// host finishes attaching HEAD. That window must not become a read EIO. +func TestWALStoreChunk_TakeoverReadBeforeAttachIsRetryable(t *testing.T) { + remote := newGated(seededRemote(t)) + remote.holdGetHead = make(chan struct{}) + view := newStubView(frontend.Projection{VolumeID: "v1", ReplicaID: "r1"}) + p := chunkProvider(t, t.TempDir(), remote, view, 0) + // Release before provider cleanup joins the authority/attach worker. + defer remote.release() + 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})) + waitEntered(t, remote, "gethead") + backend, err := p.Open(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + handler := nvme.NewIOHandler(nvme.HandlerConfig{Backend: backend, BlockSize: 4096, VolumeSize: pcBlocks * 4096, NSID: 1}) + command := nvme.IOCommand{Opcode: 0x02, NSID: 1, SLBA: 33, NLB: 1} + start := time.Now() + result := handler.Handle(context.Background(), command) + elapsed := time.Since(start) + // Keep the actual deferred attach parked for the takeover race interval. + time.Sleep(2500 * time.Millisecond) + remote.release() + if result.SCT != nvme.SCTGeneric || result.SC != nvme.SCNamespaceNotReady || len(result.Data) != 0 { + t.Fatalf("read before HEAD attach: SCT=%#x SC=%#x data=%d reason=%s; want retryable namespace not ready", result.SCT, result.SC, len(result.Data), result.Reason) + } + if elapsed >= 5*time.Second { + t.Fatalf("read before attach took %s", elapsed) + } + deadline := time.Now().Add(5 * time.Second) + for { + result = handler.Handle(context.Background(), command) + if result.AsError() == nil { + break + } + if result.SCT != nvme.SCTGeneric || result.SC != nvme.SCNamespaceNotReady { + t.Fatalf("read while attach settles: %v", result.AsError()) + } + if time.Now().After(deadline) { + t.Fatal("attach did not make the same read operational") + } + time.Sleep(10 * time.Millisecond) + } + if !bytes.Equal(result.Data, block(0x33)) { + t.Fatal("first operational read did not return exact HEAD bytes") + } + t.Logf("pre-attach read returned in %s; same read recovered exact HEAD bytes after 2.5s attach delay", elapsed) +} 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..ea34c9f88b --- /dev/null +++ b/seaweed-block/core/frontend/nvme/read_ready_retry_test.go @@ -0,0 +1,45 @@ +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}, + {"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) + } + }) + } +} From 93529c04fdc67d238d71670b85b8ef7cb0723099 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 06:46:42 -0800 Subject: [PATCH 02/12] test(durable): hold takeover after visible HEAD claim --- .../durable/takeover_read_ready_test.go | 44 ++++++++++++++++--- 1 file changed, 39 insertions(+), 5 deletions(-) diff --git a/seaweed-block/core/frontend/durable/takeover_read_ready_test.go b/seaweed-block/core/frontend/durable/takeover_read_ready_test.go index c10221bc3f..aa70b911f7 100644 --- a/seaweed-block/core/frontend/durable/takeover_read_ready_test.go +++ b/seaweed-block/core/frontend/durable/takeover_read_ready_test.go @@ -3,22 +3,48 @@ package durable_test import ( "bytes" "context" + "sync" "testing" "time" "github.com/seaweedfs/seaweed-block/core/frontend" "github.com/seaweedfs/seaweed-block/core/frontend/nvme" + "github.com/seaweedfs/seaweed-block/core/storage" ) +// Hold the return from a successful takeover CAS: an external observer can +// see the new owner while provider attachment is still in flight. +type heldTakeoverClaim struct { + storage.ChunkRemote + claimed chan struct{} + release chan struct{} + once sync.Once +} + +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) }) + select { + case <-r.release: + return gen, nil + case <-ctx.Done(): + return gen, ctx.Err() + } +} + // The frontend can connect after authority arrives but before the fresh // host finishes attaching HEAD. That window must not become a read EIO. func TestWALStoreChunk_TakeoverReadBeforeAttachIsRetryable(t *testing.T) { - remote := newGated(seededRemote(t)) - remote.holdGetHead = make(chan struct{}) + remote := &heldTakeoverClaim{ChunkRemote: seededRemote(t), claimed: make(chan struct{}), release: make(chan struct{})} + var releaseOnce sync.Once + release := func() { releaseOnce.Do(func() { close(remote.release) }) } view := newStubView(frontend.Projection{VolumeID: "v1", ReplicaID: "r1"}) p := chunkProvider(t, t.TempDir(), remote, view, 0) // Release before provider cleanup joins the authority/attach worker. - defer remote.release() + defer release() if _, err := p.EnsureStorage("v1"); err != nil { t.Fatal(err) } @@ -26,7 +52,15 @@ func TestWALStoreChunk_TakeoverReadBeforeAttachIsRetryable(t *testing.T) { t.Fatal(err) } view.set(healthyProj(frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 4, EndpointVersion: 2})) - waitEntered(t, remote, "gethead") + 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) @@ -38,7 +72,7 @@ func TestWALStoreChunk_TakeoverReadBeforeAttachIsRetryable(t *testing.T) { elapsed := time.Since(start) // Keep the actual deferred attach parked for the takeover race interval. time.Sleep(2500 * time.Millisecond) - remote.release() + release() if result.SCT != nvme.SCTGeneric || result.SC != nvme.SCNamespaceNotReady || len(result.Data) != 0 { t.Fatalf("read before HEAD attach: SCT=%#x SC=%#x data=%d reason=%s; want retryable namespace not ready", result.SCT, result.SC, len(result.Data), result.Reason) } From bdf45a43f8d0bfe1a14334ad1c7de73c1a7ded92 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 06:47:49 -0800 Subject: [PATCH 03/12] fix(nvme): retry reads while the backend is not ready --- seaweed-block/core/frontend/errors.go | 3 ++- seaweed-block/core/frontend/nvme/io.go | 8 ++++++-- seaweed-block/core/frontend/nvme/read_ready_retry_test.go | 2 ++ seaweed-block/docs/design/invariants.md | 1 + 4 files changed, 11 insertions(+), 3 deletions(-) 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 4615b3d08a..d2ac487081 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) } @@ -296,7 +296,8 @@ func (h *IOHandler) write(ctx context.Context, cmd IOCommand) 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 { @@ -317,6 +318,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 index ea34c9f88b..92c6536202 100644 --- a/seaweed-block/core/frontend/nvme/read_ready_retry_test.go +++ b/seaweed-block/core/frontend/nvme/read_ready_retry_test.go @@ -25,6 +25,8 @@ func TestSessionReadNotReadyIsRetryable(t *testing.T) { 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}, diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 6ee4916e12..bf9e12bfba 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -54,6 +54,7 @@ stateDiagram-v2 | From | To | Guard | Enforced in | Protects | |---|---|---|---|---| | — | Opened | v3 A/B descriptors and owned-map dependencies valid, exclusive file ownership acquired; legacy formats refused; backend starts not operational | `core/storage/walstore.go` `OpenWALStoreWithOptions`; `core/frontend/durable/provider.go` `openOrCreate` | `INV-WAL-OPGATE-001` | +| `INV-FE-NVME-READY-001` | An NVMe I/O refused with `ErrNotReady` 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` | — | ACTIVE | | Opened | Recovering | the volume is open in the provider | `core/frontend/durable/provider.go` `RecoverVolume` | `INV-WAL-OPGATE-001` | | Recovering | Serving | v3 nonce/cursor-bound physical prefix satisfies its W/BASE gate; rollback fence and rebuilt bounds publish before reuse; `Recover` aborts/drains an open COW window before lower locks, holds the capture barrier and invalidates proofs at start/end (legacy LSN scan remains fixture-only) | `core/storage/walstore_v3.go` `recoverV3`; `core/storage/walstore.go` `WALStore.Recover` | `INV-WAL-SYNCED-RECOVERED-001`, `INV-WAL-REPLAY-LWW-001`, `INV-WAL-FRONTIER-GAP-001`, `INV-CUT-RECOVER-BARRIER-001` | | Recovering | RecoveryFailed | a WAL integrity failure or an I/O error; the backend stays not operational and the host blocks local readiness with `wal_corrupt` or `io_error` | `cmd/blockvolume/durable_startup.go` `openAndRecoverDurable`; `core/host/volume/recovery_watchdog.go` `LocalRecoveryHealthReason` | `INV-WAL-TYPED-FAILCLOSED-001`, `INV-WAL-OPGATE-001` | From 25ef2bbbb0eebe86fc767fd2497a160d1dbbf05b Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 07:04:53 -0800 Subject: [PATCH 04/12] test(durable): model host retry exhaustion during attachment --- .../durable/takeover_read_ready_test.go | 103 ++++++++++++------ 1 file changed, 67 insertions(+), 36 deletions(-) diff --git a/seaweed-block/core/frontend/durable/takeover_read_ready_test.go b/seaweed-block/core/frontend/durable/takeover_read_ready_test.go index aa70b911f7..7866a30a52 100644 --- a/seaweed-block/core/frontend/durable/takeover_read_ready_test.go +++ b/seaweed-block/core/frontend/durable/takeover_read_ready_test.go @@ -3,48 +3,57 @@ 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" ) -// Hold the return from a successful takeover CAS: an external observer can -// see the new owner while provider attachment is still in flight. +// 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 sync.Once + claimed chan struct{} + release chan struct{} + once, releaseOnce sync.Once + holdFor time.Duration } +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 { + 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() } } -// The frontend can connect after authority arrives but before the fresh -// host finishes attaching HEAD. That window must not become a read EIO. -func TestWALStoreChunk_TakeoverReadBeforeAttachIsRetryable(t *testing.T) { - remote := &heldTakeoverClaim{ChunkRemote: seededRemote(t), claimed: make(chan struct{}), release: make(chan struct{})} - var releaseOnce sync.Once - release := func() { releaseOnce.Do(func() { close(remote.release) }) } +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} view := newStubView(frontend.Projection{VolumeID: "v1", ReplicaID: "r1"}) p := chunkProvider(t, t.TempDir(), remote, view, 0) - // Release before provider cleanup joins the authority/attach worker. - defer release() + // Registered after provider cleanup, so release precedes its worker join. + t.Cleanup(remote.unblock) if _, err := p.EnsureStorage("v1"); err != nil { t.Fatal(err) } @@ -66,35 +75,57 @@ func TestWALStoreChunk_TakeoverReadBeforeAttachIsRetryable(t *testing.T) { t.Fatal(err) } 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() - result := handler.Handle(context.Background(), command) - elapsed := time.Since(start) - // Keep the actual deferred attach parked for the takeover race interval. - time.Sleep(2500 * time.Millisecond) - release() - if result.SCT != nvme.SCTGeneric || result.SC != nvme.SCNamespaceNotReady || len(result.Data) != 0 { - t.Fatalf("read before HEAD attach: SCT=%#x SC=%#x data=%d reason=%s; want retryable namespace not ready", result.SCT, result.SC, len(result.Data), result.Reason) - } - if elapsed >= 5*time.Second { - t.Fatalf("read before attach took %s", elapsed) - } - deadline := time.Now().Add(5 * time.Second) - for { - result = handler.Handle(context.Background(), command) + for attempt := 0; attempt <= 5; attempt++ { + result := handler.Handle(context.Background(), command) if result.AsError() == nil { - break + 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("read while attach settles: %v", result.AsError()) + t.Fatalf("guest read terminal status: %v", result.AsError()) } - if time.Now().After(deadline) { - t.Fatal("attach did not make the same read operational") - } - time.Sleep(10 * time.Millisecond) } - if !bytes.Equal(result.Data, block(0x33)) { - t.Fatal("first operational read did not return exact HEAD bytes") + 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) } - t.Logf("pre-attach read returned in %s; same read recovered exact HEAD bytes after 2.5s attach delay", elapsed) + if elapsed < 3500*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") + } } From dcf85fb41f0dcbe8c466ba241a9649f0e636565c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 07:07:58 -0800 Subject: [PATCH 05/12] fix(durable): wait for chunk read readiness before host retries --- .../core/frontend/durable/provider.go | 1 + .../frontend/durable/read_ready_wait_test.go | 60 ++++++++++++++ .../core/frontend/durable/storage_adapter.go | 78 ++++++++++++++++++- seaweed-block/docs/design/invariants.md | 2 +- 4 files changed, 138 insertions(+), 3 deletions(-) create mode 100644 seaweed-block/core/frontend/durable/read_ready_wait_test.go diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index 2e89b88c45..df35c996ee 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -820,6 +820,7 @@ func (p *DurableProvider) wrap(volumeID, path string, impl ImplName, s storage.L EndpointVersion: proj.EndpointVersion, } b := NewStorageBackend(s, p.view, id) + b.waitReadReady = p.cfg.Impl == ImplWALStoreChunk return &volHandle{storage: s, backend: b, path: path, impl: impl}, 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..e9296bca88 --- /dev/null +++ b/seaweed-block/core/frontend/durable/read_ready_wait_test.go @@ -0,0 +1,60 @@ +package durable + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" +) + +func TestReadReadinessWaitDoesNotHoldAdmissionAndCloseWakesIt(t *testing.T) { + // No storage is needed: this read must never pass the operational gate. + b := &StorageBackend{waitReadReady: true} + b.opEvidence.Store("attachment pending") + done := make(chan error, 1) + joined := make(chan struct{}) + t.Cleanup(func() { + _ = b.Close() + select { + case <-joined: + case <-time.After(time.Second): + t.Error("pending read did not settle after Close") + } + }) + go func() { + defer close(joined) + _, err := b.Read(context.Background(), 0, make([]byte, 4096)) + done <- err + }() + deadline := time.Now().Add(time.Second) + for { + b.mu.Lock() + registered := b.readyChanged != nil + b.mu.Unlock() + if registered { + break + } + if time.Now().After(deadline) { + t.Fatal("read did not register a readiness notification") + } + time.Sleep(time.Millisecond) + } + 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) + } + if err := b.Close(); err != nil { + t.Fatal(err) + } + select { + case err := <-done: + if !errors.Is(err, frontend.ErrBackendClosed) { + t.Fatalf("Close wake error=%v", err) + } + case <-time.After(time.Second): + t.Fatal("Close did not wake registered read") + } +} diff --git a/seaweed-block/core/frontend/durable/storage_adapter.go b/seaweed-block/core/frontend/durable/storage_adapter.go index 2aab01a159..84c754d49f 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter.go +++ b/seaweed-block/core/frontend/durable/storage_adapter.go @@ -159,8 +159,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 + // Chunk-managed reads may wait before admission for attachment to finish. + // waitReadReady is fixed at provider construction; readyChanged is under mu. + waitReadReady 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 @@ -343,6 +347,7 @@ func (b *StorageBackend) Close() error { b.mu.Lock() defer b.mu.Unlock() b.closed = true + b.notifyReadReadyLocked() return nil } @@ -371,12 +376,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 } @@ -401,6 +408,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 } @@ -444,8 +452,11 @@ func (b *StorageBackend) SetOperational(ok bool, evidence string) { evidence = "not operational" } } + b.mu.Lock() b.opEvidence.Store(evidence) b.operational.Store(ok) + b.notifyReadReadyLocked() + b.mu.Unlock() } // StopIO makes the backend refuse every new Read, Write and Sync with @@ -532,6 +543,12 @@ func (b *StorageBackend) Sync(ctx context.Context) error { // 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() + if err != nil && b.waitReadReady && errors.Is(err, frontend.ErrNotReady) { + var cancel context.CancelFunc + ctx, cancel = context.WithTimeout(ctx, 4*time.Second) + defer cancel() + release, err = b.awaitReadAdmission(ctx) + } if err != nil { return 0, err } @@ -539,9 +556,66 @@ func (b *StorageBackend) Read(ctx context.Context, offset int64, p []byte) (int, if len(p) == 0 { return 0, nil } + if b.waitReadReady && ctx.Err() != nil { + return 0, b.readReadyTimeout(ctx.Err()) + } return b.readBytes(offset, p) } +// notifyReadReadyLocked wakes readers 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 + } +} + +// awaitReadAdmission waits only after a gate refusal, before any storage I/O. +// The four-second readiness allowance is capped by an earlier caller deadline. +func (b *StorageBackend) awaitReadAdmission(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.mu.Unlock() + if err := ctx.Err(); err != nil { + return nil, b.readReadyTimeout(err) + } + release, err := b.admit() + if err == nil { + if cause := ctx.Err(); cause != nil { + release() + return nil, b.readReadyTimeout(cause) + } + return release, nil + } + if !errors.Is(err, frontend.ErrNotReady) || terminal || b.operational.Load() { + return release, err + } + select { + case <-changed: + case <-ctx.Done(): + return nil, b.readReadyTimeout(ctx.Err()) + } + } +} + +func (b *StorageBackend) readReadyTimeout(cause error) error { + // A concurrent Close, fence or observer failure must retain its gate error. + err := b.readyCheck() + 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. diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index bf9e12bfba..e0a5b5e425 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -54,7 +54,7 @@ stateDiagram-v2 | From | To | Guard | Enforced in | Protects | |---|---|---|---|---| | — | Opened | v3 A/B descriptors and owned-map dependencies valid, exclusive file ownership acquired; legacy formats refused; backend starts not operational | `core/storage/walstore.go` `OpenWALStoreWithOptions`; `core/frontend/durable/provider.go` `openOrCreate` | `INV-WAL-OPGATE-001` | -| `INV-FE-NVME-READY-001` | An NVMe I/O refused with `ErrNotReady` 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` | — | ACTIVE | +| `INV-FE-NVME-READY-001` | Chunk-managed reads wait up to 4s (or an earlier caller deadline) for operational 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` | — | ACTIVE | | Opened | Recovering | the volume is open in the provider | `core/frontend/durable/provider.go` `RecoverVolume` | `INV-WAL-OPGATE-001` | | Recovering | Serving | v3 nonce/cursor-bound physical prefix satisfies its W/BASE gate; rollback fence and rebuilt bounds publish before reuse; `Recover` aborts/drains an open COW window before lower locks, holds the capture barrier and invalidates proofs at start/end (legacy LSN scan remains fixture-only) | `core/storage/walstore_v3.go` `recoverV3`; `core/storage/walstore.go` `WALStore.Recover` | `INV-WAL-SYNCED-RECOVERED-001`, `INV-WAL-REPLAY-LWW-001`, `INV-WAL-FRONTIER-GAP-001`, `INV-CUT-RECOVER-BARRIER-001` | | Recovering | RecoveryFailed | a WAL integrity failure or an I/O error; the backend stays not operational and the host blocks local readiness with `wal_corrupt` or `io_error` | `cmd/blockvolume/durable_startup.go` `openAndRecoverDurable`; `core/host/volume/recovery_watchdog.go` `LocalRecoveryHealthReason` | `INV-WAL-TYPED-FAILCLOSED-001`, `INV-WAL-OPGATE-001` | From f12c8f73582e9dd6e3e593877553ff6e3458cb65 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 07:08:58 -0800 Subject: [PATCH 06/12] test(durable): witness pending read before drain and close --- .../frontend/durable/read_ready_wait_test.go | 106 ++++++++++-------- .../core/frontend/durable/storage_adapter.go | 5 + 2 files changed, 66 insertions(+), 45 deletions(-) diff --git a/seaweed-block/core/frontend/durable/read_ready_wait_test.go b/seaweed-block/core/frontend/durable/read_ready_wait_test.go index e9296bca88..36b4b41bc1 100644 --- a/seaweed-block/core/frontend/durable/read_ready_wait_test.go +++ b/seaweed-block/core/frontend/durable/read_ready_wait_test.go @@ -3,6 +3,7 @@ package durable import ( "context" "errors" + "sync" "testing" "time" @@ -10,51 +11,66 @@ import ( ) func TestReadReadinessWaitDoesNotHoldAdmissionAndCloseWakesIt(t *testing.T) { - // No storage is needed: this read must never pass the operational gate. - b := &StorageBackend{waitReadReady: true} - b.opEvidence.Store("attachment pending") - done := make(chan error, 1) - joined := make(chan struct{}) - t.Cleanup(func() { - _ = b.Close() - select { - case <-joined: - case <-time.After(time.Second): - t.Error("pending read did not settle after Close") + for _, drain := range []bool{false, true} { + name := "close" + if drain { + name = "drain-then-close" } - }) - go func() { - defer close(joined) - _, err := b.Read(context.Background(), 0, make([]byte, 4096)) - done <- err - }() - deadline := time.Now().Add(time.Second) - for { - b.mu.Lock() - registered := b.readyChanged != nil - b.mu.Unlock() - if registered { - break - } - if time.Now().After(deadline) { - t.Fatal("read did not register a readiness notification") - } - time.Sleep(time.Millisecond) - } - 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) - } - if err := b.Close(); err != nil { - t.Fatal(err) - } - select { - case err := <-done: - if !errors.Is(err, frontend.ErrBackendClosed) { - t.Fatalf("Close wake error=%v", err) - } - case <-time.After(time.Second): - t.Fatal("Close did not wake registered read") + t.Run(name, func(t *testing.T) { + // No storage is needed: this read must never pass the operational gate. + b := &StorageBackend{waitReadReady: 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) + _, 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 drain { + 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) + } + } + if err := b.Close(); err != nil { + t.Fatal(err) + } + release() + select { + case err := <-done: + if !errors.Is(err, frontend.ErrBackendClosed) { + t.Fatalf("Close wake error=%v", err) + } + case <-time.After(time.Second): + t.Fatal("Close did not wake registered read") + } + }) } } diff --git a/seaweed-block/core/frontend/durable/storage_adapter.go b/seaweed-block/core/frontend/durable/storage_adapter.go index 84c754d49f..5737aebd1a 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter.go +++ b/seaweed-block/core/frontend/durable/storage_adapter.go @@ -149,6 +149,8 @@ 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() storage storage.LogicalStorage view frontend.ProjectionView @@ -596,6 +598,9 @@ func (b *StorageBackend) awaitReadAdmission(ctx context.Context) (func(), error) 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(): From 7da8006648fb376b965e20da3fb6b6c3c0cf2f6c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 07:09:58 -0800 Subject: [PATCH 07/12] test(nvme): pin zero retry delay for readiness policy --- .../frontend/nvme/read_ready_retry_test.go | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/seaweed-block/core/frontend/nvme/read_ready_retry_test.go b/seaweed-block/core/frontend/nvme/read_ready_retry_test.go index 92c6536202..0b89d1dfad 100644 --- a/seaweed-block/core/frontend/nvme/read_ready_retry_test.go +++ b/seaweed-block/core/frontend/nvme/read_ready_retry_test.go @@ -45,3 +45,21 @@ func TestSessionReadNotReadyIsRetryable(t *testing.T) { }) } } + +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) + } +} From eb698f98fd0ea3284fcbd5c087df5192ea5dd004 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 07:28:16 -0800 Subject: [PATCH 08/12] test: require pending takeover writes to await attachment --- .../frontend/durable/takeover_read_ready_test.go | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/seaweed-block/core/frontend/durable/takeover_read_ready_test.go b/seaweed-block/core/frontend/durable/takeover_read_ready_test.go index 7866a30a52..5a34305758 100644 --- a/seaweed-block/core/frontend/durable/takeover_read_ready_test.go +++ b/seaweed-block/core/frontend/durable/takeover_read_ready_test.go @@ -129,3 +129,19 @@ func TestWALStoreChunk_PendingReadHonoursEarlierDeadline(t *testing.T) { 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) + } +} From 486289c30a595258135fd9d06cd22016ae427a7a Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 07:30:15 -0800 Subject: [PATCH 09/12] fix: wait for chunk attachment before admitting takeover reads and writes --- .../core/frontend/durable/provider.go | 3 +- .../frontend/durable/read_ready_wait_test.go | 29 +++++--- .../core/frontend/durable/storage_adapter.go | 74 ++++++++++++------- .../durable/takeover_read_ready_test.go | 28 ++++++- seaweed-block/docs/design/invariants.md | 2 +- 5 files changed, 97 insertions(+), 39 deletions(-) diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index df35c996ee..17d3e64aac 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -820,7 +820,6 @@ func (p *DurableProvider) wrap(volumeID, path string, impl ImplName, s storage.L EndpointVersion: proj.EndpointVersion, } b := NewStorageBackend(s, p.view, id) - b.waitReadReady = p.cfg.Impl == ImplWALStoreChunk return &volHandle{storage: s, backend: b, path: path, impl: impl}, nil } @@ -878,7 +877,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 index 36b4b41bc1..9127a3932a 100644 --- a/seaweed-block/core/frontend/durable/read_ready_wait_test.go +++ b/seaweed-block/core/frontend/durable/read_ready_wait_test.go @@ -11,14 +11,11 @@ import ( ) func TestReadReadinessWaitDoesNotHoldAdmissionAndCloseWakesIt(t *testing.T) { - for _, drain := range []bool{false, true} { - name := "close" - if drain { - name = "drain-then-close" - } + 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{waitReadReady: true} + b := &StorageBackend{waitAttachReady: true} b.opEvidence.Store("attachment pending") registered := make(chan struct{}, 1) resume := make(chan struct{}) @@ -44,7 +41,12 @@ func TestReadReadinessWaitDoesNotHoldAdmissionAndCloseWakesIt(t *testing.T) { }) go func() { defer close(joined) - _, err := b.Read(context.Background(), 0, make([]byte, 4096)) + 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 { @@ -52,20 +54,27 @@ func TestReadReadinessWaitDoesNotHoldAdmissionAndCloseWakesIt(t *testing.T) { case <-time.After(time.Second): t.Fatal("read did not register a readiness notification") } - if drain { + 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) } } - if err := b.Close(); err != nil { + 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, frontend.ErrBackendClosed) { + if !errors.Is(err, want) { t.Fatalf("Close wake error=%v", err) } case <-time.After(time.Second): diff --git a/seaweed-block/core/frontend/durable/storage_adapter.go b/seaweed-block/core/frontend/durable/storage_adapter.go index 5737aebd1a..9aa62d7176 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter.go +++ b/seaweed-block/core/frontend/durable/storage_adapter.go @@ -161,12 +161,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"). - // Chunk-managed reads may wait before admission for attachment to finish. - // waitReadReady is fixed at provider construction; readyChanged is under mu. - waitReadReady bool - readyChanged chan struct{} - 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 @@ -457,6 +457,7 @@ func (b *StorageBackend) SetOperational(ok bool, evidence string) { b.mu.Lock() b.opEvidence.Store(evidence) b.operational.Store(ok) + b.waitAttachReady = false b.notifyReadReadyLocked() b.mu.Unlock() } @@ -544,13 +545,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() - if err != nil && b.waitReadReady && errors.Is(err, frontend.ErrNotReady) { - var cancel context.CancelFunc - ctx, cancel = context.WithTimeout(ctx, 4*time.Second) - defer cancel() - release, err = b.awaitReadAdmission(ctx) - } + release, err := b.admitAfterAttach(ctx) if err != nil { return 0, err } @@ -558,13 +553,39 @@ func (b *StorageBackend) Read(ctx context.Context, offset int64, p []byte) (int, if len(p) == 0 { return 0, nil } - if b.waitReadReady && ctx.Err() != nil { - return 0, b.readReadyTimeout(ctx.Err()) + if ctx.Err() != nil { + return 0, b.attachReadyTimeout(ctx.Err()) } return b.readBytes(offset, p) } -// notifyReadReadyLocked wakes readers without making them hold ioMu while +// 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 + } + b.mu.Lock() + pending := b.waitAttachReady + b.mu.Unlock() + if !pending { + return release, err + } + 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 { @@ -573,25 +594,25 @@ func (b *StorageBackend) notifyReadReadyLocked() { } } -// awaitReadAdmission waits only after a gate refusal, before any storage I/O. -// The four-second readiness allowance is capped by an earlier caller deadline. -func (b *StorageBackend) awaitReadAdmission(ctx context.Context) (func(), error) { +// 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 + terminal := b.closed || b.observerErr != nil || !b.waitAttachReady b.mu.Unlock() if err := ctx.Err(); err != nil { - return nil, b.readReadyTimeout(err) + return nil, b.attachReadyTimeout(err) } release, err := b.admit() if err == nil { if cause := ctx.Err(); cause != nil { release() - return nil, b.readReadyTimeout(cause) + return nil, b.attachReadyTimeout(cause) } return release, nil } @@ -604,12 +625,12 @@ func (b *StorageBackend) awaitReadAdmission(ctx context.Context) (func(), error) select { case <-changed: case <-ctx.Done(): - return nil, b.readReadyTimeout(ctx.Err()) + return nil, b.attachReadyTimeout(ctx.Err()) } } } -func (b *StorageBackend) readReadyTimeout(cause error) error { +func (b *StorageBackend) attachReadyTimeout(cause error) error { // A concurrent Close, fence or observer failure must retain its gate error. err := b.readyCheck() b.mu.Lock() @@ -628,7 +649,7 @@ func (b *StorageBackend) readReadyTimeout(cause error) error { func (b *StorageBackend) Write(ctx context.Context, offset int64, p []byte) (int, error) { 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 @@ -637,6 +658,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 index 5a34305758..e4ef2d6708 100644 --- a/seaweed-block/core/frontend/durable/takeover_read_ready_test.go +++ b/seaweed-block/core/frontend/durable/takeover_read_ready_test.go @@ -111,7 +111,7 @@ func TestWALStoreChunk_PendingReadWaitIsBounded(t *testing.T) { if result.SCT != nvme.SCTGeneric || result.SC != nvme.SCNamespaceNotReady || len(result.Data) != 0 { t.Fatalf("pending read result: %+v", result) } - if elapsed < 3500*time.Millisecond || elapsed >= 5*time.Second { + if elapsed < 2500*time.Millisecond || elapsed >= 5*time.Second { t.Fatalf("pending read wait=%s; want bounded readiness wait below5s", elapsed) } } @@ -145,3 +145,29 @@ func TestWALStoreChunk_TakeoverWriteWaitsForAttach(t *testing.T) { 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/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index e0a5b5e425..7cc2239ab8 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -54,7 +54,7 @@ stateDiagram-v2 | From | To | Guard | Enforced in | Protects | |---|---|---|---|---| | — | Opened | v3 A/B descriptors and owned-map dependencies valid, exclusive file ownership acquired; legacy formats refused; backend starts not operational | `core/storage/walstore.go` `OpenWALStoreWithOptions`; `core/frontend/durable/provider.go` `openOrCreate` | `INV-WAL-OPGATE-001` | -| `INV-FE-NVME-READY-001` | Chunk-managed reads wait up to 4s (or an earlier caller deadline) for operational 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` | — | 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 | | Opened | Recovering | the volume is open in the provider | `core/frontend/durable/provider.go` `RecoverVolume` | `INV-WAL-OPGATE-001` | | Recovering | Serving | v3 nonce/cursor-bound physical prefix satisfies its W/BASE gate; rollback fence and rebuilt bounds publish before reuse; `Recover` aborts/drains an open COW window before lower locks, holds the capture barrier and invalidates proofs at start/end (legacy LSN scan remains fixture-only) | `core/storage/walstore_v3.go` `recoverV3`; `core/storage/walstore.go` `WALStore.Recover` | `INV-WAL-SYNCED-RECOVERED-001`, `INV-WAL-REPLAY-LWW-001`, `INV-WAL-FRONTIER-GAP-001`, `INV-CUT-RECOVER-BARRIER-001` | | Recovering | RecoveryFailed | a WAL integrity failure or an I/O error; the backend stays not operational and the host blocks local readiness with `wal_corrupt` or `io_error` | `cmd/blockvolume/durable_startup.go` `openAndRecoverDurable`; `core/host/volume/recovery_watchdog.go` `LocalRecoveryHealthReason` | `INV-WAL-TYPED-FAILCLOSED-001`, `INV-WAL-OPGATE-001` | From c8abeec62db9f8291337ca568cb0462472f737f9 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 07:36:47 -0800 Subject: [PATCH 10/12] docs: place readiness invariant in the frontend ledger --- seaweed-block/docs/design/invariants.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 7cc2239ab8..ff41a1e2ea 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -54,7 +54,6 @@ stateDiagram-v2 | From | To | Guard | Enforced in | Protects | |---|---|---|---|---| | — | Opened | v3 A/B descriptors and owned-map dependencies valid, exclusive file ownership acquired; legacy formats refused; backend starts not operational | `core/storage/walstore.go` `OpenWALStoreWithOptions`; `core/frontend/durable/provider.go` `openOrCreate` | `INV-WAL-OPGATE-001` | -| `INV-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 | | Opened | Recovering | the volume is open in the provider | `core/frontend/durable/provider.go` `RecoverVolume` | `INV-WAL-OPGATE-001` | | Recovering | Serving | v3 nonce/cursor-bound physical prefix satisfies its W/BASE gate; rollback fence and rebuilt bounds publish before reuse; `Recover` aborts/drains an open COW window before lower locks, holds the capture barrier and invalidates proofs at start/end (legacy LSN scan remains fixture-only) | `core/storage/walstore_v3.go` `recoverV3`; `core/storage/walstore.go` `WALStore.Recover` | `INV-WAL-SYNCED-RECOVERED-001`, `INV-WAL-REPLAY-LWW-001`, `INV-WAL-FRONTIER-GAP-001`, `INV-CUT-RECOVER-BARRIER-001` | | Recovering | RecoveryFailed | a WAL integrity failure or an I/O error; the backend stays not operational and the host blocks local readiness with `wal_corrupt` or `io_error` | `cmd/blockvolume/durable_startup.go` `openAndRecoverDurable`; `core/host/volume/recovery_watchdog.go` `LocalRecoveryHealthReason` | `INV-WAL-TYPED-FAILCLOSED-001`, `INV-WAL-OPGATE-001` | @@ -305,7 +304,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. @@ -315,6 +314,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 | From b967075b56c90a2a31548a256b2dca46b6fd6b82 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 07:44:52 -0800 Subject: [PATCH 11/12] test: witness attach readiness races and start holds at the first waiter --- .../frontend/durable/export_chunk_test.go | 5 ++++ .../frontend/durable/read_ready_wait_test.go | 27 +++++++++++++++++++ .../core/frontend/durable/storage_adapter.go | 4 +++ .../durable/takeover_read_ready_test.go | 12 ++++++++- 4 files changed, 47 insertions(+), 1 deletion(-) 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/read_ready_wait_test.go b/seaweed-block/core/frontend/durable/read_ready_wait_test.go index 9127a3932a..c19c8c1373 100644 --- a/seaweed-block/core/frontend/durable/read_ready_wait_test.go +++ b/seaweed-block/core/frontend/durable/read_ready_wait_test.go @@ -83,3 +83,30 @@ func TestReadReadinessWaitDoesNotHoldAdmissionAndCloseWakesIt(t *testing.T) { }) } } + +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 9aa62d7176..3859070cf9 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter.go +++ b/seaweed-block/core/frontend/durable/storage_adapter.go @@ -151,6 +151,7 @@ type StorageBackend struct { testBeforeIOLock func() // Runs outside locks after a read registers its readiness notification. testBeforeReadReadyWait func() + testAfterAttachRefusal func() storage storage.LogicalStorage view frontend.ProjectionView @@ -574,6 +575,9 @@ func (b *StorageBackend) admitAfterAttach(ctx context.Context) (func(), error) { 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() diff --git a/seaweed-block/core/frontend/durable/takeover_read_ready_test.go b/seaweed-block/core/frontend/durable/takeover_read_ready_test.go index e4ef2d6708..e2278f7b30 100644 --- a/seaweed-block/core/frontend/durable/takeover_read_ready_test.go +++ b/seaweed-block/core/frontend/durable/takeover_read_ready_test.go @@ -22,6 +22,7 @@ type heldTakeoverClaim 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) }) } @@ -33,6 +34,13 @@ func (r *heldTakeoverClaim) CASHead(ctx context.Context, expected storage.ChunkH 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 @@ -49,7 +57,7 @@ func (r *heldTakeoverClaim) CASHead(ctx context.Context, expected storage.ChunkH 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} + 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. @@ -74,6 +82,8 @@ func pendingTakeoverRead(t *testing.T, hold time.Duration) (*durable.DurableProv 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 } From d49f7553af83780d2b503864b183626e45d31737 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 07:45:45 -0800 Subject: [PATCH 12/12] fix: recheck readiness and stale lineage at attach admission boundaries --- seaweed-block/core/frontend/durable/storage_adapter.go | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/seaweed-block/core/frontend/durable/storage_adapter.go b/seaweed-block/core/frontend/durable/storage_adapter.go index 3859070cf9..7cb579c256 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter.go +++ b/seaweed-block/core/frontend/durable/storage_adapter.go @@ -582,7 +582,8 @@ func (b *StorageBackend) admitAfterAttach(ctx context.Context) (func(), error) { pending := b.waitAttachReady b.mu.Unlock() if !pending { - return release, err + // Readiness may have published after the initial refusal. + return b.admit() } ctx, cancel := context.WithTimeout(ctx, 3*time.Second) defer cancel() @@ -636,7 +637,7 @@ func (b *StorageBackend) awaitAttachAdmission(ctx context.Context) (func(), erro func (b *StorageBackend) attachReadyTimeout(cause error) error { // A concurrent Close, fence or observer failure must retain its gate error. - err := b.readyCheck() + err := b.gate() b.mu.Lock() observerFailed := b.observerErr != nil b.mu.Unlock()