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 c19c8c1373..073fd1a8b6 100644 --- a/seaweed-block/core/frontend/durable/read_ready_wait_test.go +++ b/seaweed-block/core/frontend/durable/read_ready_wait_test.go @@ -5,11 +5,44 @@ import ( "errors" "sync" "testing" + "testing/synctest" "time" "github.com/seaweedfs/seaweed-block/core/frontend" ) +func TestAttachReadinessReadAndWriteHonourCallerCancellation(t *testing.T) { + for _, write := range []bool{false, true} { + name := "read" + if write { + name = "write" + } + t.Run(name, func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + // A nil store makes any access before attachment an immediate failure. + b := &StorageBackend{waitAttachReady: true} + b.opEvidence.Store("attachment pending") + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + b.testBeforeReadReadyWait = cancel + started := time.Now() + var err error + if write { + _, err = b.Write(ctx, 0, make([]byte, 4096)) + } else { + _, err = b.Read(ctx, 0, make([]byte, 4096)) + } + if !errors.Is(err, context.Canceled) { + t.Fatalf("cancelled readiness wait returned %v", err) + } + if elapsed := time.Since(started); elapsed != 0 { + t.Fatalf("cancelled wait consumed the readiness allowance: %s", elapsed) + } + }) + }) + } +} + func TestReadReadinessWaitDoesNotHoldAdmissionAndCloseWakesIt(t *testing.T) { for _, mode := range []string{"close", "drain-then-close", "fence", "write-close"} { name := mode diff --git a/seaweed-block/core/frontend/nvme/target.go b/seaweed-block/core/frontend/nvme/target.go index 5415e3f572..61aa254de4 100644 --- a/seaweed-block/core/frontend/nvme/target.go +++ b/seaweed-block/core/frontend/nvme/target.go @@ -244,6 +244,9 @@ func (t *Target) handleConn(conn net.Conn) { go func() { select { case <-t.closed: + // Open can still be waiting for provider readiness before a session + // starts. Closing the socket alone cannot wake that wait. + cancel() _ = conn.Close() case <-ctx.Done(): } diff --git a/seaweed-block/core/frontend/nvme/target_cancel_test.go b/seaweed-block/core/frontend/nvme/target_cancel_test.go new file mode 100644 index 0000000000..31f882e6bd --- /dev/null +++ b/seaweed-block/core/frontend/nvme/target_cancel_test.go @@ -0,0 +1,189 @@ +package nvme_test + +import ( + "bufio" + "bytes" + "context" + "fmt" + "io" + "log" + "net" + "os" + "os/exec" + "sync" + "testing" + "testing/synctest" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/frontend/nvme" +) + +type cancelProviderFunc func(context.Context, string) (frontend.Backend, error) + +func (f cancelProviderFunc) Open(ctx context.Context, volume string) (frontend.Backend, error) { + return f(ctx, volume) +} + +type pendingOpenView struct{ observed chan struct{} } + +func (v pendingOpenView) Projection() frontend.Projection { + select { + case v.observed <- struct{}{}: + default: + } + return frontend.Projection{VolumeID: "v1"} // Never healthy during this test. +} + +type cancelTestListener struct { + conns chan net.Conn + done chan struct{} + once sync.Once +} + +func (l *cancelTestListener) Accept() (net.Conn, error) { + select { + case c := <-l.conns: + return c, nil + case <-l.done: + return nil, net.ErrClosed + } +} +func (l *cancelTestListener) Close() error { l.once.Do(func() { close(l.done) }); return nil } +func (l *cancelTestListener) Addr() net.Addr { return &net.TCPAddr{} } + +func pendingReadinessTarget(t *testing.T) (*nvme.Target, context.CancelFunc) { + t.Helper() + view := pendingOpenView{observed: make(chan struct{}, 1)} + provider, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStore, StorageRoot: t.TempDir(), + NumBlocks: 32, BlockSize: 4096, OpenTimeout: time.Hour, + }, view) + if err != nil { + t.Fatal(err) + } + + // Only failure cleanup may release the wait independently of the target. + abort, release := context.WithCancel(context.Background()) + + wrapped := cancelProviderFunc(func(ctx context.Context, volume string) (frontend.Backend, error) { + ctx, cancel := context.WithCancel(ctx) + defer cancel() + stop := context.AfterFunc(abort, cancel) + defer stop() + return provider.Open(ctx, volume) + }) + listener := &cancelTestListener{conns: make(chan net.Conn), done: make(chan struct{})} + target := nvme.NewTarget(nvme.TargetConfig{ + VolumeID: "v1", Provider: wrapped, Logger: log.New(io.Discard, "", 0), + ListenerFactory: func(nvme.Transport, string) (net.Listener, error) { return listener, nil }, + }) + if _, err := target.Start(); err != nil { + t.Fatal(err) + } + client, server := net.Pipe() + + listener.conns <- server + <-view.observed // The real DurableProvider is inside its readiness wait. + t.Cleanup(func() { release(); _ = client.Close(); _ = target.Close(); _ = provider.Close() }) + return target, release +} + +func TestTargetCloseCancelsPendingProviderReadiness(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + target, release := pendingReadinessTarget(t) + closed := make(chan error, 1) + go func() { closed <- target.Close() }() + synctest.Wait() + select { + case err := <-closed: + if err != nil { + t.Fatal(err) + } + default: + t.Error("target Close waits for provider readiness instead of cancelling it") + release() + <-closed // Join even when the cancellation assertion fails. + } + }) +} + +// This child owns the same real Target and DurableProvider as the holder. Its +// stdin EOF is the stop event; no readiness publication or provider close may +// help the target finish. This is a component process, not a blockvolume replay. +func TestNVMeReadinessCancelProcess(t *testing.T) { + if os.Getenv("SWBLOCK_NVME_CANCEL_HELPER") == "1" { + target, _ := pendingReadinessTarget(t) + fmt.Println("provider-readiness-wait") + if _, err := io.Copy(io.Discard, os.Stdin); err != nil { + t.Fatal(err) + } + if err := target.Close(); err != nil { + t.Fatal(err) + } + return + } + executable, err := os.Executable() + if err != nil { + t.Fatal(err) + } + ctx, kill := context.WithCancel(context.Background()) + defer kill() + cmd := exec.CommandContext(ctx, executable, "-test.run=^TestNVMeReadinessCancelProcess$", "-test.count=1") + cmd.Env = append(os.Environ(), "SWBLOCK_NVME_CANCEL_HELPER=1") + input, err := cmd.StdinPipe() + if err != nil { + t.Fatal(err) + } + output, err := cmd.StdoutPipe() + if err != nil { + t.Fatal(err) + } + var stderr bytes.Buffer + cmd.Stderr = &stderr + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + done := make(chan struct{}) + var waitErr error + go func() { waitErr = cmd.Wait(); close(done) }() + t.Cleanup(func() { + kill() + select { + case <-done: + case <-time.After(10 * time.Second): + t.Error("child did not join after kill") + } + }) + observed := make(chan bool, 1) + go func() { + scanner := bufio.NewScanner(output) + for scanner.Scan() { + if scanner.Text() == "provider-readiness-wait" { + observed <- true + return + } + } + observed <- false + }() + select { + case ok := <-observed: + if !ok { + t.Fatal("child did not enter provider readiness") + } + case <-time.After(10 * time.Second): + t.Fatal("child readiness witness timed out") + } + if err := input.Close(); err != nil { + t.Fatal(err) + } + select { + case <-done: + if waitErr != nil { + t.Fatalf("cancelled component exit: %v\n%s", waitErr, stderr.String()) + } + case <-time.After(5 * time.Second): + t.Fatal("cancelled component exceeded the 5s stop budget") + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 57112b02b1..be99edfcbf 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -617,6 +617,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-FE-NVME-READY-001` | A read or write on a successfully recovered chunk volume awaiting attachment waits for attachment readiness, before storage admission, for at most 3 s or until an earlier caller deadline, on the local monotonic clock. | M1 Opened / Recovering → Serving | `core/frontend/durable/storage_adapter.go` `admitAfterAttachUnqueued`, `awaitAttachAdmission`, `readyCheck` | `TestWALStoreChunk_PendingReadWaitIsBounded`; `TestWALStoreChunk_PendingReadHonoursEarlierDeadline`; `TestWALStoreChunk_TakeoverWriteWaitsForAttach`; `TestReadReadinessWaitDoesNotHoldAdmissionAndCloseWakesIt` (`core/frontend/durable/read_ready_wait_test.go`); also in `core/frontend/durable/takeover_read_ready_test.go` | — | ACTIVE | | `INV-FE-NVME-READY-STATUS-001` | An NVMe read or write whose attachment-readiness wait times out or is refused completes with Namespace Not Ready (SC 0x82), DNR=0, without reading or mutating storage. | M1 Opened / Recovering → Serving | `core/frontend/durable/storage_adapter.go` `attachReadyTimeout`; `core/frontend/nvme/io.go` `mapBackendError` | `TestWALStoreChunk_TakeoverReadBeforeAttachIsRetryable`; `TestSessionReadNotReadyIsRetryable` (`core/frontend/nvme/read_ready_retry_test.go`); `TestWALStoreChunk_PendingAttachBeyondHostRetryBudget` (`core/frontend/durable/takeover_read_ready_test.go`) | — | ACTIVE | | `INV-FE-NVME-READY-ANA-001` | An I/O that ends during the attachment-readiness wait because the backend closed or its lineage went stale keeps its ANA error, and a physical I/O fault keeps Internal Error. | M1 Opened / Recovering → Serving | `core/frontend/durable/storage_adapter.go` `attachReadyTimeout`; `core/frontend/nvme/io.go` `mapBackendError` | `TestSessionReadNotReadyIsRetryable` (`core/frontend/nvme/read_ready_retry_test.go`); `TestReadReadinessWaitDoesNotHoldAdmissionAndCloseWakesIt` (`core/frontend/durable/read_ready_wait_test.go`) | — | ACTIVE | +| `INV-FE-NVME-CANCEL-001` | Closing an NVMe target cancels connection readiness waits before joining workers. Attach-pending reads and writes honour caller cancellation without accessing storage. | M1 Opened / Recovering; frontend shutdown | `core/frontend/nvme/target.go` `handleConn`; `session.go` `serve`; `core/frontend/durable/storage_adapter.go` `awaitAttachAdmission` | `TestTargetCloseCancelsPendingProviderReadiness`, `TestNVMeReadinessCancelProcess` (`core/frontend/nvme/target_cancel_test.go`); `TestAttachReadinessReadAndWriteHonourCallerCancellation` (`core/frontend/durable/read_ready_wait_test.go`) | NONE (frontend cancellation plumbing; no durable state transition) | ACTIVE | | `INV-FE-PRIMARY-READY-OPERATIONAL-001` | FrontendPrimaryReady is reported only while the local durable backend admits I/O, and the frontend target listens only after it first does; attach-pending, fenced or no durable status reports not ready with the reason. | M1 Opened / Recovering → Serving; M2 process exit | `core/host/volume/status_server.go` `statusProjection`; `core/frontend/durable/storage_adapter.go` `FirstServing`; `cmd/blockvolume/frontend_gate.go` `awaitFrontendStart` (the iSCSI, NVMe and ublk targets in `cmd/blockvolume/main.go` `runVolume` start after it); `cmd/blockvolume/process_exit.go` `waitWorkspaceStop` | `TestStatusServer_ReadyOnlyWhileBackendOperational`, `TestStatusServer_NotReadyAlwaysHasAReason` (`core/host/volume/status_server_test.go`); `TestFrontendGateWaitsForTheStorageClaim`, `TestFrontendGateStopsWithoutStartingTheFrontends` (`cmd/blockvolume/frontend_gate_test.go`); `TestDurableProvider_NonChunkVolumeServesRightAfterOpen` (`core/frontend/durable/first_serving_test.go`) | — | ACTIVE | | `INV-FE-FENCE-EXIT-001` | A workspace chunk primary whose backend fences after its target listens ends the process within detection plus the 5 s cleanup bound: a lease expiry at the guard's own deadline, a HEAD fence within 50 ms. | M1 Serving → Closed; M2 process exit | `core/frontend/durable/provider_startup.go` `watchChunkFence` (HEAD fence: not operational with the evidence within 50 ms; I/O refused from the fence); `cmd/blockvolume/process_exit.go` `watchChunkRuntimeFence` (78 `head_fenced`) and `waitWorkspaceStop` (lease fence: 75 `lease_expired`); `superviseProcess` (the 5 s cleanup bound from the decision) | `TestWALStoreChunk_RuntimeHeadFenceLatchesNotOperational` (`core/frontend/durable/runtime_fence_test.go`); `TestRuntimeHeadFenceChoosesHeadFencedExit` (`cmd/blockvolume/runtime_fence_exit_test.go`); real-binary case C (lease expiry after listening: exit 75) | — | ACTIVE | | `INV-WS-SERVE-LEASE-HELD-001` | A workspace primary claims HEAD, listens, reports ready and admits I/O only while its lease guard permits now; without a granted lease it holds at the gate and exits 75 when the startup wait runs out (`INV-WS-MASTER-WAIT-001`). | M1 Recovering → Serving; M2 process exit | `core/host/volume/workspace_lease.go` `WorkspaceLeaseGuard.Held` / `permits` (the one deciding function: the guarded projection gates the chunk claim, the per-I/O admit and); `core/frontend/durable/storage_adapter.go` `AdmitsIO` (the one "may serve" function, the I/O gate: backend admits AND guarded projection names this lineage; shared readiness rule); `core/host/volume/status_server.go` `statusProjection` (`FrontendPrimaryReady` from `AdmitsIO`; `NotReadyReason=lease_not_held` first); `cmd/blockvolume/frontend_gate.go` `frontendStartSignal` / `awaitFrontendStart` (a workspace primary's frontends start once `AdmitsIO` passes; non-chunk and supporting replicas start after open as before); `cmd/blockvolume/process_exit.go` (exit 75 `assignment_timeout`); `cmd/sw-block/shell_check.go` `FrontendPrimaryReady` | `TestStatusServer_WorkspacePrimaryNotReadyWithoutHeldLease`, `TestWorkspaceLeaseGrantIsLoggedOnceAfterRefusedRenewals`, `TestWorkspaceLeaseFirstRevokingReplyIsNotLoggedAsAGrant` (`core/host/volume/workspace_lease_held_test.go`); `TestStorageBackend_AdmitsIOIsTheIOGate` (`core/frontend/durable/admits_io_test.go`); `TestFrontendStartSignal_WorkspacePrimaryWaitsForAdmitsIO`, `TestFrontendStartSignal_OtherVolumesStartAfterOpenAsBefore`, `TestFirstAdmittedStopEndsTheWorker` (`cmd/blockvolume/frontend_start_signal_test.go`); real-binary cases B-late (restart before the forced-move barrier, re-granted inside the wait: no claim, listen or ready before the re-grant), B75 (no grant inside the wait: no claim, listen or ready, exit 75; a restart after the barrier serves) and B0 (restart inside the lease serves at once) | — | ACTIVE |