diff --git a/seaweed-block/core/frontend/nvme/t2_v2port_nvme_disconnect_mid_r2t_test.go b/seaweed-block/core/frontend/nvme/t2_v2port_nvme_disconnect_mid_r2t_test.go new file mode 100644 index 0000000000..d5207692d7 --- /dev/null +++ b/seaweed-block/core/frontend/nvme/t2_v2port_nvme_disconnect_mid_r2t_test.go @@ -0,0 +1,117 @@ +// Ownership: QA (L1B-4 inventory item, landed early per QA parallel +// capacity during Batch 11c sign prep). +// sw may NOT modify without architect approval via §8B.4 Discovery +// Bridge. +// +// Maps to ledger row: PCDD-NVME-SESSION-DISCONNECT-MID-R2T-001 +// +// Purpose: pin server cleanup correctness when the host crashes +// or nvme-disconnects MID-H2CData-stream (some chunks in, some +// still pending). Distinct from ConnectionCloseDrainsInflight, +// which closes BEFORE any H2CData is sent — the two tests +// exercise different server error branches: +// +// ConnectionCloseDrainsInflight → recvH2CData blocked at first +// PDU read; socket closes → Dequeue returns EOF on the first +// iteration. +// +// this test → recvH2CData has already consumed N chunks and is +// reading the (N+1)th; socket closes mid-loop → Dequeue +// returns EOF during the loop. Exercises the "partial data +// buffered" cleanup path. +// +// Test layer: Unit (in-process Target + nvmeClient; no subprocess). + +package nvme_test + +import ( + "runtime" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/nvme" +) + +func TestT2V2Port_NVMe_IO_DisconnectMidH2CDataStream(t *testing.T) { + runtime.GC() + time.Sleep(50 * time.Millisecond) + baseline := runtime.NumGoroutine() + + backend, cli := newChunkedWriteTarget(t) + + // 32 KiB write, 8 chunks. We'll send 3 chunks then abruptly + // close the conn — server's recvH2CData is inside its loop + // at that moment, expecting 5 more chunks. + const total = 32 * 1024 + const chunks = 8 + const nlb = uint16(total / 512) + const sendChunks = 3 + + payload := make([]byte, total) + for i := range payload { + payload[i] = byte((i * 17) & 0xFF) + } + + cid := uint16(cli.cid.Add(1)) + cmd := nvme.CapsuleCommand{ + OpCode: 0x01, CID: cid, NSID: 1, + D10: 0, D11: 0, D12: uint32(nlb - 1), + } + if err := cli.ioW.SendHeaderOnly(0x4, &cmd, 64); err != nil { + t.Fatalf("send cmd: %v", err) + } + + _ = cli.io.SetReadDeadline(time.Now().Add(5 * time.Second)) + ch, err := cli.ioR.Dequeue() + if err != nil { + t.Fatalf("R2T Dequeue: %v", err) + } + if ch.Type != 0x9 { + t.Fatalf("expected R2T, got type 0x%02x", ch.Type) + } + var r2t nvme.R2THeader + if err := cli.ioR.Receive(&r2t); err != nil { + t.Fatalf("recv R2T: %v", err) + } + + // Send only `sendChunks` of `chunks` total. After this, server + // has received partial data and is blocked in recvH2CData + // awaiting the next H2CData PDU. + for i := 0; i < sendChunks; i++ { + off := i * (total / chunks) + h := nvme.H2CDataHeader{ + CCCID: cid, TAG: r2t.TAG, + DATAO: uint32(off), + DATAL: uint32(total / chunks), + } + if err := cli.ioW.SendWithData(0x6, 0, &h, 16, payload[off:off+total/chunks]); err != nil { + t.Fatalf("send H2CData chunk %d: %v", i, err) + } + } + + // Abrupt close — server recvH2CData's Dequeue will surface EOF + // mid-loop. rxLoop must unwind cleanly, releasing any partial + // buffer without panic or leak. + _ = cli.io.Close() + + // Grace period for target drain. + time.Sleep(500 * time.Millisecond) + + // Backend must NOT have been called — partial data never + // completed to a full Write. + if got := backend.calls.Load(); got != 0 { + t.Errorf("backend.calls=%d; want 0 (partial data must not reach backend)", got) + } + if got := backend.bytes.Load(); got != 0 { + t.Errorf("backend.bytes=%d; want 0 (partial data must not be written)", got) + } + + // Goroutine leak check. + runtime.GC() + time.Sleep(50 * time.Millisecond) + afterClose := runtime.NumGoroutine() + if afterClose > baseline+50 { + t.Errorf("goroutine leak: baseline=%d after-mid-stream-close=%d (delta=%d)", + baseline, afterClose, afterClose-baseline) + } +} diff --git a/seaweed-block/core/frontend/nvme/t2_v2port_nvme_pipeline_extended_test.go b/seaweed-block/core/frontend/nvme/t2_v2port_nvme_pipeline_extended_test.go index 77f87b7f53..88225c4794 100644 --- a/seaweed-block/core/frontend/nvme/t2_v2port_nvme_pipeline_extended_test.go +++ b/seaweed-block/core/frontend/nvme/t2_v2port_nvme_pipeline_extended_test.go @@ -1,24 +1,25 @@ // Ownership: QA (Condition 4 of BUG-001 fix Discovery Bridge review). // sw may NOT modify without architect approval via §8B.4. // -// Two additional regression tests for the pipelined-cmd port: +// REVISION 2026-04-22 (post-c0c0a1d revert to V2-strict): +// Original draft expected async R2T emission — incompatible with +// kernel. Rewritten to kernel-realistic paired R2T+data+resp cycle +// under single-R2T-outstanding invariant. See BUG-001 §13 + +// feedback_porting_discipline.md citation. // // 1. TestT2V2Port_NVMe_IO_PipelinedNWritesSameQueue — -// Parametric N ∈ {2, 4, 8, 16, 32}. After BUG-001 fix, server -// must accept N in-flight CapsuleCmds on one IO queue, issue -// N R2Ts, receive N payloads, emit N CapsuleResps. Pins -// "pipelining is not just 2" so sw's fix can't pass by -// accident with a 2-slot special case. +// Parametric N ∈ {2, 4, 8, 16, 32}. All N CapsuleCmds shipped +// back-to-back (kernel pipelines freely); then paired +// R2T→H2CData→CapResp cycle per cmd. Pins server's +// pendingCapsules drain works at scale (not just N=2) and +// FIFO ordering is preserved. // // 2. TestT2V2Port_NVMe_IO_ConnectionCloseDrainsInflight — -// Fire N pipelined cmds, close the TCP connection mid-stream. -// Target must not panic, must not leak goroutines, must -// release the admin controller. Pins cleanup discipline in -// the new rxLoop / txLoop design. -// -// Status at landing (2026-04-22): both are RED on current V3 -// (Batch 11b). When sw's BUG-001 fix lands, both must go GREEN -// without breaking any earlier A-tier or debug test. +// Simplified: 1 cmd + R2T received, then abrupt TCP close +// BEFORE sending H2CData. Pins cleanup discipline (no +// goroutine leak on mid-R2T close). Previous multi-cmd shape +// was covered "by accident" under V2-strict since inline +// collectR2TData blocks and then returns on socket error. package nvme_test @@ -31,13 +32,8 @@ import ( "github.com/seaweedfs/seaweed-block/core/frontend/nvme" ) -// TestT2V2Port_NVMe_IO_PipelinedNWritesSameQueue pins that the -// fix supports arbitrary queue depths, not just depth-2 (the -// minimum repro from BUG-001). -// -// Kernel advertises QD up to ctrl.CAP.MQES+1 = 64 in our case; -// picks 8 in practice for mkfs. Testing up to 32 covers the -// realistic range without chasing the 64 absolute max. +// TestT2V2Port_NVMe_IO_PipelinedNWritesSameQueue — +// N pipelined cmds, kernel-realistic paired-cycle shape. func TestT2V2Port_NVMe_IO_PipelinedNWritesSameQueue(t *testing.T) { cases := []int{2, 4, 8, 16, 32} for _, n := range cases { @@ -45,13 +41,12 @@ func TestT2V2Port_NVMe_IO_PipelinedNWritesSameQueue(t *testing.T) { t.Run(fmt.Sprintf("N=%d", n), func(t *testing.T) { backend, cli := newChunkedWriteTarget(t) - const perCmdBytes = 8 * 1024 // 8 KiB per cmd keeps total bounded at N=32 - const chunks = 2 // 2 × 4 KiB H2CData PDUs per cmd + const perCmdBytes = 8 * 1024 + const chunks = 2 const nlb = uint16(perCmdBytes / 512) - // Build N payloads so data-integrity on backend side - // can be verified (each distinct). payloads := make([][]byte, n) + cids := make([]uint16, n) for i := range payloads { p := make([]byte, perCmdBytes) for j := range p { @@ -60,8 +55,7 @@ func TestT2V2Port_NVMe_IO_PipelinedNWritesSameQueue(t *testing.T) { payloads[i] = p } - // --- Send N capsule cmds back-to-back --- - cids := make([]uint16, n) + // --- Phase 1: fire ALL N cmds back-to-back (pipelined) --- for i := 0; i < n; i++ { cids[i] = uint16(cli.cid.Add(1)) cmd := nvme.CapsuleCommand{ @@ -76,171 +70,145 @@ func TestT2V2Port_NVMe_IO_PipelinedNWritesSameQueue(t *testing.T) { _ = cli.io.SetReadDeadline(time.Now().Add(10 * time.Second)) - // --- Collect N R2Ts; server must interleave them --- - r2tByCID := make(map[uint16]nvme.R2THeader, n) - for collected := 0; collected < n; collected++ { + // --- Phase 2: opportunistic drain until N CapResps --- + // + // V2-strict spawns backend.Write as a goroutine after + // collectR2TData returns; txLoop orders R2T-i+1 and + // CapResp-i based on goroutine completion vs pendingCapsules + // drain timing. Kernel does the same opportunistic drain + // by PDU type. We mirror kernel behavior so the test is + // tolerant of legitimate ordering freedom. + + payloadByCID := make(map[uint16][]byte, n) + for i, cid := range cids { + payloadByCID[cid] = payloads[i] + } + respSeen := make(map[uint16]bool, n) + r2tSeen := make(map[uint16]bool, n) + + for len(respSeen) < n { ch, err := cli.ioR.Dequeue() if err != nil { - t.Fatalf("Dequeue R2T[%d/%d]: %v — BUG-001 fix incomplete: server did not emit all N R2Ts for pipelined cmds", - collected, n, err) + t.Fatalf("drain Dequeue (seen %d R2T, %d resp of %d): %v", + len(r2tSeen), len(respSeen), n, err) } - if ch.Type == 0x5 { + switch ch.Type { + case 0x9: // R2T + var r2t nvme.R2THeader + if err := cli.ioR.Receive(&r2t); err != nil { + t.Fatalf("recv R2T: %v", err) + } + if r2tSeen[r2t.CCCID] { + t.Fatalf("duplicate R2T for CID=%d", r2t.CCCID) + } + r2tSeen[r2t.CCCID] = true + + p, ok := payloadByCID[r2t.CCCID] + if !ok { + t.Fatalf("R2T for unknown CID=%d", r2t.CCCID) + } + for c := 0; c < chunks; c++ { + off := c * (perCmdBytes / chunks) + h := nvme.H2CDataHeader{ + CCCID: r2t.CCCID, TAG: r2t.TAG, + DATAO: uint32(off), + DATAL: uint32(perCmdBytes / chunks), + } + if err := cli.ioW.SendWithData(0x6, 0, &h, + 16, p[off:off+perCmdBytes/chunks]); err != nil { + t.Fatalf("send H2CData CID=%d chunk %d: %v", r2t.CCCID, c, err) + } + } + case 0x5: // CapsuleResp var resp nvme.CapsuleResponse - _ = cli.ioR.Receive(&resp) - t.Fatalf("early CapsuleResp cid=%d status=0x%04x — server responded before issuing all R2Ts", - resp.CID, resp.Status) - } - if ch.Type != 0x9 { - t.Fatalf("R2T[%d] type=0x%x, want 0x09", collected, ch.Type) - } - var r2t nvme.R2THeader - if err := cli.ioR.Receive(&r2t); err != nil { - t.Fatalf("recv R2T[%d]: %v", collected, err) - } - if _, seen := r2tByCID[r2t.CCCID]; seen { - t.Fatalf("duplicate R2T for CID=%d", r2t.CCCID) - } - r2tByCID[r2t.CCCID] = r2t - } - - // --- Send all H2CData: per-cmd serial internally, - // cmd order round-robin to test interleaved arrival --- - for chunk := 0; chunk < chunks; chunk++ { - for i, cid := range cids { - r2t := r2tByCID[cid] - off := chunk * (perCmdBytes / chunks) - h := nvme.H2CDataHeader{ - CCCID: cid, TAG: r2t.TAG, - DATAO: uint32(off), - DATAL: uint32(perCmdBytes / chunks), + if err := cli.ioR.Receive(&resp); err != nil { + t.Fatalf("recv CapResp: %v", err) } - if err := cli.ioW.SendWithData(0x6, 0, &h, - 16, payloads[i][off:off+perCmdBytes/chunks]); err != nil { - t.Fatalf("send H2CData cid=%d chunk=%d: %v", cid, chunk, err) + if resp.Status != 0 { + t.Fatalf("CapResp CID=%d status=0x%04x", resp.CID, resp.Status) } + if respSeen[resp.CID] { + t.Fatalf("duplicate CapResp for CID=%d", resp.CID) + } + respSeen[resp.CID] = true + default: + t.Fatalf("unexpected PDU type 0x%02x during drain", ch.Type) } } - // --- Receive N CapsuleResps --- - seen := make(map[uint16]bool, n) - for i := 0; i < n; i++ { - resp := recvCapsuleResp(t, cli.ioR) - if resp.Status != 0 { - t.Fatalf("resp[%d] CID=%d status=0x%04x", i, resp.CID, resp.Status) - } - if seen[resp.CID] { - t.Fatalf("duplicate resp for CID=%d", resp.CID) - } - seen[resp.CID] = true - } - for _, cid := range cids { - if !seen[cid] { - t.Errorf("missing CapsuleResp for CID=%d", cid) - } + if len(r2tSeen) != n { + t.Errorf("R2T count: got %d, want %d", len(r2tSeen), n) } - // --- Integrity: N backend.Write calls, N × perCmdBytes total --- + // --- Integrity --- if got := backend.calls.Load(); got != int32(n) { - t.Errorf("backend.calls=%d; want %d", got, n) + t.Errorf("backend.calls=%d, want %d", got, n) } if got, want := backend.bytes.Load(), int64(n)*int64(perCmdBytes); got != want { - t.Errorf("backend.bytes=%d; want %d (lost %d)", got, want, want-got) + t.Errorf("backend.bytes=%d, want %d (lost %d)", got, want, want-got) } }) } } -// TestT2V2Port_NVMe_IO_ConnectionCloseDrainsInflight pins -// cleanup discipline: if the host closes the TCP connection -// while N cmds are in-flight, Target must release resources -// without panicking or leaking goroutines. -// -// Strategy: -// 1. Snapshot runtime.NumGoroutine -// 2. Spin target, open IO queue, fire N=8 pipelined cmds -// 3. Receive the first R2T so we're guaranteed sw has entered -// the rxLoop-active state -// 4. Abruptly close the IO TCP conn -// 5. Give Target a grace period to drain -// 6. Assert goroutine count is within reason (tolerate ~4 -// stragglers for admin session + Target accept loop + WG -// drain; 50+ extra means leak) -// 7. Close Target; re-check NumGoroutine is back near baseline -// -// RED pre-fix: handleWrite's blocking read on a closed conn -// may return an error AND the serial session loop may not -// propagate cleanup to admin controller's release path. -// GREEN post-fix: rxLoop detects EOF, cancels pending cmds via -// ctx, txLoop drains, cmdWg.Wait unblocks, session returns. +// TestT2V2Port_NVMe_IO_ConnectionCloseDrainsInflight pins cleanup +// discipline: abrupt close mid-R2T (client received R2T, never +// sends H2CData) must not leak goroutines or panic the target. func TestT2V2Port_NVMe_IO_ConnectionCloseDrainsInflight(t *testing.T) { - _ = backendStubForClose // keep compile if future helpers elided - - // Baseline before we even build the target — avoids counting - // package init goroutines as leaks. runtime.GC() time.Sleep(50 * time.Millisecond) baseline := runtime.NumGoroutine() backend, cli := newChunkedWriteTarget(t) - const n = 8 - const perCmdBytes = 8 * 1024 - const nlb = uint16(perCmdBytes / 512) + const total = 32 * 1024 + const nlb = uint16(total / 512) - // Fire N pipelined cmds without reading. - for i := 0; i < n; i++ { - cid := uint16(cli.cid.Add(1)) - cmd := nvme.CapsuleCommand{ - OpCode: 0x01, CID: cid, NSID: 1, - D10: uint32(i) * uint32(nlb), D11: 0, - D12: uint32(nlb - 1), - } - if err := cli.ioW.SendHeaderOnly(0x4, &cmd, 64); err != nil { - t.Fatalf("send cmd[%d]: %v", i, err) - } + // Fire one cmd. Server will emit R2T and then block inline + // waiting for H2CData (V2-strict). We receive R2T but never + // send data — then close the TCP conn. + cid := uint16(cli.cid.Add(1)) + cmd := nvme.CapsuleCommand{ + OpCode: 0x01, CID: cid, NSID: 1, + D10: 0, D11: 0, D12: uint32(nlb - 1), + } + if err := cli.ioW.SendHeaderOnly(0x4, &cmd, 64); err != nil { + t.Fatalf("send cmd: %v", err) } - // Wait for the first R2T so rxLoop is demonstrably active. _ = cli.io.SetReadDeadline(time.Now().Add(5 * time.Second)) ch, err := cli.ioR.Dequeue() if err != nil { - // Pre-fix, server may have already closed us with - // "expected H2CData, got 0x4". That's fine — we still - // get to test the cleanup path, just from the other - // direction. - t.Logf("first Dequeue returned %v (acceptable — proceeding to close path)", err) - } else if ch.Type == 0x9 { - var r2t nvme.R2THeader - _ = cli.ioR.Receive(&r2t) + t.Fatalf("R2T Dequeue: %v", err) + } + if ch.Type != 0x9 { + t.Fatalf("expected R2T, got type 0x%02x", ch.Type) + } + var r2t nvme.R2THeader + if err := cli.ioR.Receive(&r2t); err != nil { + t.Fatalf("recv R2T: %v", err) } - // Abrupt close of the IO TCP conn — simulates a host crash - // or nvme disconnect while data is in flight. + // Abrupt close — server is now inline in recvH2CData waiting + // on a PDU that will never arrive. Close triggers read error + // on the server side; rxLoop must unwind cleanly. _ = cli.io.Close() - // Grace period for target to drain + release admin controller. + // Grace period for target-side drain. time.Sleep(500 * time.Millisecond) - // We expect backend.calls to be 0 or some small number; the - // actual invariant is "target didn't panic and didn't wedge". - _ = backend + // Backend must not have been called (no H2CData ever arrived). + if got := backend.calls.Load(); got != 0 { + t.Errorf("backend.calls=%d, want 0 (no H2CData was sent)", got) + } - // Goroutine delta after drain. We don't care about exact - // count; 50+ over baseline is a clear leak signal. + // Goroutine delta after drain. 50+ over baseline is a clear + // leak signal. runtime.GC() time.Sleep(50 * time.Millisecond) afterDrain := runtime.NumGoroutine() if afterDrain > baseline+50 { - t.Errorf("goroutine leak: baseline=%d after-conn-close=%d (delta=%d)", + t.Errorf("goroutine leak: baseline=%d after-close=%d (delta=%d)", baseline, afterDrain, afterDrain-baseline) } - - // Target.Close runs via t.Cleanup; once fired, final check - // in a second t.Cleanup runs after it. Can't do that here - // easily; instead trust the drain grace period + baseline - // comparison. } - -// backendStubForClose is a vestigial symbol to keep the import -// for (*writeCountingBackend) visible if helper imports shift. -var backendStubForClose = (*writeCountingBackend)(nil) diff --git a/seaweed-block/core/frontend/nvme/t2_v2port_nvme_pipelined_writes_test.go b/seaweed-block/core/frontend/nvme/t2_v2port_nvme_pipelined_writes_test.go index 3383eb9ce7..3fdea784b0 100644 --- a/seaweed-block/core/frontend/nvme/t2_v2port_nvme_pipelined_writes_test.go +++ b/seaweed-block/core/frontend/nvme/t2_v2port_nvme_pipelined_writes_test.go @@ -2,29 +2,26 @@ // sw may NOT modify without architect approval via §8B.4 Discovery // Bridge. // -// Purpose: reproduce the m01 mkfs.ext4 hang at unit level by -// emulating the specific wire pattern Linux kernel emits when it -// pipelines multiple Write commands on a single IO queue. +// REVISION 2026-04-22 (post-c0c0a1d revert to V2-strict): +// The original 2026-04-22 12:32 PT draft expected ASYNC R2T +// emission (server sends N R2Ts immediately after receiving N +// pipelined cmds). That pattern is incompatible with real Linux +// kernel behavior — kernel expects ONE R2T outstanding at a time +// and pumps H2CData serially per cmd (V2 model, confirmed working +// on m01 historically). See feedback_porting_discipline.md second +// citation. // -// Evidence that this is the m01 root cause (see BUG-001 §5): -// - m01 kernel log: tag 13 AND tag 14 BOTH timed out on SAME queue -// (QID 1) — kernel had 2 concurrent writes in flight -// - Only 1 of 8 IO queue sessions reported "expected H2CData, got 0x4" -// - V3's handleCapsuleCmd is strictly serial per connection; while -// handleWrite for cmd 13 is in the H2CData collection loop, cmd 14 -// bytes sit in the TCP receive buffer as type=0x04 PDUs +// Current shape (kernel-realistic, V2-strict compatible): +// 1. Send Cmd-0 + Cmd-1 back-to-back on one IO queue (pipelined +// capsule delivery — exercises server's pendingCapsules / +// bufferInterleaved path in V2's rxLoop) +// 2. Recv R2T-0 → send H2CData-0 (all chunks) → recv CapResp-0 +// 3. Recv R2T-1 → send H2CData-1 (all chunks) → recv CapResp-1 // -// Test strategy (pipelined client): -// 1. On ONE IO queue, send Cmd-13 CapsuleCommand -// 2. Immediately send Cmd-14 CapsuleCommand (no wait for R2T-13) -// 3. Read what server sends back -// -// Expected RED (pre-fix): server reports "expected H2CData, got 0x4" -// because handleWrite for 13 reads Cmd-14 bytes (type 4) as the -// next expected H2CData. -// -// Expected GREEN (post-fix): server accepts both cmds, interleaves -// R2Ts / H2CData properly; test-client assembles responses. +// The PRE-FIX BUG-001 failure mode (serial rxLoop reads Cmd-1 +// as type 0x04 inside handleWrite's H2CData loop) is still +// detected by this shape: server's "expected H2CData, got 0x4" +// error fires before we reach the second R2T read. package nvme_test @@ -35,145 +32,119 @@ import ( "github.com/seaweedfs/seaweed-block/core/frontend/nvme" ) -// TestT2V2Port_NVMe_IO_Pipelined2WritesSameQueue emulates the exact -// m01 failure pattern. -// -// Status at landing (2026-04-22): this test is expected RED with -// current V3 (Batch 11b). When sw's H4 fix lands, it must go GREEN -// without breaking the other 7 debug tests. +// TestT2V2Port_NVMe_IO_Pipelined2WritesSameQueue pins the V2-strict +// two-cmd pipeline shape: server may issue R2Ts in arrival order +// but MUST process one cmd's H2CData to completion before emitting +// the next cmd's R2T (single-R2T-outstanding invariant). func TestT2V2Port_NVMe_IO_Pipelined2WritesSameQueue(t *testing.T) { backend, cli := newChunkedWriteTarget(t) - // Two 32 KiB Writes at non-overlapping LBA ranges. const total = 32 * 1024 const chunks = 8 const nlb = uint16(total / 512) + payload0 := make([]byte, total) payload1 := make([]byte, total) - payload2 := make([]byte, total) - for i := range payload1 { - payload1[i] = byte((i + 0x11) & 0xFF) - payload2[i] = byte((i + 0x22) & 0xFF) + for i := range payload0 { + payload0[i] = byte((i + 0x11) & 0xFF) + payload1[i] = byte((i + 0x22) & 0xFF) } - // --- Pipeline the two CapsuleCmds back-to-back on the SAME IO queue --- + // --- Phase 1: pipeline both CapsuleCmds before any R2T read --- + // + // This is the kernel behavior that broke pre-c0c0a1d serial + // dispatch. V2-strict handles it via pendingCapsules drain. + cid0 := uint16(cli.cid.Add(1)) + cmd0 := nvme.CapsuleCommand{ + OpCode: 0x01, CID: cid0, NSID: 1, + D10: 0, D11: 0, D12: uint32(nlb - 1), + } cid1 := uint16(cli.cid.Add(1)) cmd1 := nvme.CapsuleCommand{ OpCode: 0x01, CID: cid1, NSID: 1, - D10: 0, D11: 0, D12: uint32(nlb - 1), - } - cid2 := uint16(cli.cid.Add(1)) - cmd2 := nvme.CapsuleCommand{ - OpCode: 0x01, CID: cid2, NSID: 1, D10: uint32(nlb), D11: 0, D12: uint32(nlb - 1), } - - // SEND cmd1 then cmd2 with NO read in between — this is the - // pipeline that kernel does and that breaks V3. + if err := cli.ioW.SendHeaderOnly(0x4, &cmd0, 64); err != nil { + t.Fatalf("send cmd0: %v", err) + } if err := cli.ioW.SendHeaderOnly(0x4, &cmd1, 64); err != nil { t.Fatalf("send cmd1: %v", err) } - if err := cli.ioW.SendHeaderOnly(0x4, &cmd2, 64); err != nil { - t.Fatalf("send cmd2: %v", err) - } - // Now read — we expect TWO R2Ts (one per cmd). Under current V3 - // serial behavior, we'll only get R2T for cmd1 before V3 tries - // to consume cmd2 as H2CData and errors out. - type r2tPair struct { - r2t nvme.R2THeader - cid uint16 - ok bool - } - r2ts := make([]r2tPair, 0, 2) + _ = cli.io.SetReadDeadline(time.Now().Add(5 * time.Second)) - // Short deadline: if bug is present, server closes connection - // after reading cmd2-as-H2CData. With 2s timeout we'll detect - // the hang without dragging the whole suite. - _ = cli.io.SetReadDeadline(time.Now().Add(2 * time.Second)) + // --- Phase 2: opportunistic drain --- + // + // V2-strict spawns backend.Write in a goroutine after + // collectR2TData returns; txLoop may flush R2T-1 before + // CapResp-0 depending on backend timing. Kernel does the + // same opportunistic drain — treats each PDU by its type + // regardless of which cmd it belongs to. We mirror that. - for i := 0; i < 2; i++ { + payloadByCID := map[uint16][]byte{cid0: payload0, cid1: payload1} + respSeen := map[uint16]bool{} + r2tSeen := map[uint16]bool{} + + for len(respSeen) < 2 { ch, err := cli.ioR.Dequeue() if err != nil { - // Error or timeout — record and break; classification below. - t.Logf("Dequeue[%d] error (H4 BUG-001 symptom if only got %d R2Ts): %v", i, len(r2ts), err) - break + t.Fatalf("drain Dequeue: %v — server closed mid-stream (BUG-001 symptom if R2Ts were none-received yet)", err) } - if ch.Type == 0x5 /* pduCapsuleResp */ { + switch ch.Type { + case 0x9: // R2T + var r2t nvme.R2THeader + if err := cli.ioR.Receive(&r2t); err != nil { + t.Fatalf("recv R2T: %v", err) + } + if r2tSeen[r2t.CCCID] { + t.Fatalf("duplicate R2T for CID=%d", r2t.CCCID) + } + r2tSeen[r2t.CCCID] = true + + p, ok := payloadByCID[r2t.CCCID] + if !ok { + t.Fatalf("R2T for unknown CID=%d", r2t.CCCID) + } + for i := 0; i < chunks; i++ { + off := i * (total / chunks) + h := nvme.H2CDataHeader{ + CCCID: r2t.CCCID, TAG: r2t.TAG, + DATAO: uint32(off), DATAL: uint32(total / chunks), + } + if err := cli.ioW.SendWithData(0x6, 0, &h, 16, p[off:off+total/chunks]); err != nil { + t.Fatalf("send H2CData CID=%d chunk %d: %v", r2t.CCCID, i, err) + } + } + case 0x5: // CapsuleResp var resp nvme.CapsuleResponse - _ = cli.ioR.Receive(&resp) - t.Logf("got early CapsuleResp for CID=%d status=0x%04x", resp.CID, resp.Status) - break - } - if ch.Type != 0x9 /* pduR2T */ { - t.Fatalf("pair[%d] expected R2T, got type 0x%x", i, ch.Type) - } - var r2t nvme.R2THeader - if err := cli.ioR.Receive(&r2t); err != nil { - t.Fatalf("recv R2T[%d]: %v", i, err) - } - r2ts = append(r2ts, r2tPair{r2t: r2t, cid: r2t.CCCID, ok: true}) - } - - if len(r2ts) < 2 { - t.Fatalf("only got %d R2Ts for 2 pipelined Writes — H4 confirmed: "+ - "V3 session serializes at Cmd level, cannot respond to cmd2 until cmd1 "+ - "completes (but cmd1 is blocked waiting for H2CData that kernel hasn't "+ - "sent yet because it's waiting for R2T-2 first). This is the m01 BUG-001 "+ - "deadlock pattern.", - len(r2ts)) - } - - // --- If we got both R2Ts, proceed to send interleaved H2CData --- - // This branch will only execute after H4 is fixed and V3 can - // pipeline. Kernel would interleave here: H2CData for whichever - // request it has data ready for, cited by CCCID/TAG. - // - // For the RED test, we don't reach here. - - // Send all chunks for cmd1 first (kernel order also commonly - // serializes data per cmd even with pipelined cmds). - for i := 0; i < chunks; i++ { - off := i * (total / chunks) - h := nvme.H2CDataHeader{ - CCCID: cid1, TAG: r2ts[0].r2t.TAG, - DATAO: uint32(off), DATAL: uint32(total / chunks), - } - if err := cli.ioW.SendWithData(0x6, 0, &h, 16, payload1[off:off+total/chunks]); err != nil { - t.Fatalf("send H2CData cmd1 chunk %d: %v", i, err) - } - } - // Now chunks for cmd2. - for i := 0; i < chunks; i++ { - off := i * (total / chunks) - h := nvme.H2CDataHeader{ - CCCID: cid2, TAG: r2ts[1].r2t.TAG, - DATAO: uint32(off), DATAL: uint32(total / chunks), - } - if err := cli.ioW.SendWithData(0x6, 0, &h, 16, payload2[off:off+total/chunks]); err != nil { - t.Fatalf("send H2CData cmd2 chunk %d: %v", i, err) + if err := cli.ioR.Receive(&resp); err != nil { + t.Fatalf("recv CapResp: %v", err) + } + if resp.Status != 0 { + t.Fatalf("CapResp CID=%d status=0x%04x", resp.CID, resp.Status) + } + if respSeen[resp.CID] { + t.Fatalf("duplicate CapResp for CID=%d", resp.CID) + } + respSeen[resp.CID] = true + default: + t.Fatalf("unexpected PDU type 0x%02x during drain", ch.Type) } } - // Expect two CapsuleResps (one per cmd). - _ = cli.io.SetReadDeadline(time.Now().Add(5 * time.Second)) - seen := map[uint16]bool{} - for i := 0; i < 2; i++ { - resp := recvCapsuleResp(t, cli.ioR) - if resp.Status != 0 { - t.Fatalf("pipelined cmd CID=%d status=0x%04x", resp.CID, resp.Status) - } - seen[resp.CID] = true + if !r2tSeen[cid0] || !r2tSeen[cid1] { + t.Fatalf("missing R2T: cid0=%v cid1=%v", r2tSeen[cid0], r2tSeen[cid1]) } - if !seen[cid1] || !seen[cid2] { - t.Fatalf("missing CapsuleResp: cid1=%v cid2=%v", seen[cid1], seen[cid2]) + if !respSeen[cid0] || !respSeen[cid1] { + t.Fatalf("missing CapResp: cid0=%v cid1=%v", respSeen[cid0], respSeen[cid1]) } + // --- Integrity --- if got := backend.calls.Load(); got != 2 { - t.Errorf("backend.calls=%d; want 2 (one per pipelined Write)", got) + t.Errorf("backend.calls=%d, want 2", got) } if got := backend.bytes.Load(); got != int64(2*total) { - t.Errorf("backend.bytes=%d; want %d", got, 2*total) + t.Errorf("backend.bytes=%d, want %d", got, 2*total) } } diff --git a/seaweed-block/core/frontend/nvme/t2_v2port_nvme_reconnect_loop_test.go b/seaweed-block/core/frontend/nvme/t2_v2port_nvme_reconnect_loop_test.go new file mode 100644 index 0000000000..eca47a1e56 --- /dev/null +++ b/seaweed-block/core/frontend/nvme/t2_v2port_nvme_reconnect_loop_test.go @@ -0,0 +1,95 @@ +// Ownership: QA (L1B-1 inventory item, landed early per QA parallel +// capacity during Batch 11c sign prep). +// sw may NOT modify without architect approval via §8B.4 Discovery +// Bridge. +// +// Maps to ledger row: PCDD-NVME-SESSION-RECONNECT-LOOP-001 +// +// Purpose: stability test for attach/detach cycling — exercises +// session setup + teardown paths repeatedly to surface any resource +// leak (goroutine, TCP buffer, CNTLID registry entry) that single- +// shot tests would miss. +// +// Inventory item L1B-1 rationale (from +// sw-block/design/bugs/inventory/nvme-test-coverage-deferred.md): +// "kernel reconnect is a rare event" — but `nvme disconnect` + +// fresh connect is exactly what testops / operators do during +// maintenance. Worth pinning that it stays clean, not deferred to +// T3 perf gate. +// +// Test layer: L2 subprocess (real cmd/blockmaster + cmd/blockvolume). +// Tagged with testing.Short() skip so CI-short runs exclude it. + +package nvme_test + +import ( + "bytes" + "runtime" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/nvme" +) + +func TestT2V2Port_NVMe_Process_ReconnectLoop50(t *testing.T) { + if testing.Short() { + t.Skip("L2 subprocess test; skipped under -short") + } + + h := startL2NvmeHarness(t) + defer h.Close() + + // Baseline goroutine count BEFORE the loop, to detect leak. + runtime.GC() + time.Sleep(100 * time.Millisecond) + baseline := runtime.NumGoroutine() + + const iterations = 50 + payloadPattern := []byte("reconnect-loop-probe-") + + // Write a distinct payload on each iteration, read it back, + // then fully close the client and reconnect. + for i := 0; i < iterations; i++ { + cli := dialAndConnect(t, h.nvmeAddr) + + // Build a per-iteration payload so cross-iteration staleness + // would surface as data mismatch. + payload := make([]byte, nvme.DefaultBlockSize) + copy(payload, payloadPattern) + payload[len(payloadPattern)] = byte('0' + i%10) + payload[len(payloadPattern)+1] = byte('A' + i/10) + + status := cli.writeCmd(t, 0, 1, payload) + if status != 0 { + cli.close() + t.Fatalf("iter %d: write status=0x%04x", i, status) + } + status, data := cli.readCmd(t, 0, 1, int(nvme.DefaultBlockSize)) + if status != 0 { + cli.close() + t.Fatalf("iter %d: read status=0x%04x", i, status) + } + if !bytes.Equal(data[:len(payload)], payload) { + cli.close() + t.Fatalf("iter %d: readback mismatch; got first32=%q, want %q", + i, first16N(data), first16N(payload)) + } + + // Clean teardown — IDLs and admin/IO TCP conns freed. + cli.close() + } + + // Drain window — give Target time to reap closed sessions. + time.Sleep(1 * time.Second) + runtime.GC() + time.Sleep(100 * time.Millisecond) + + // Goroutine delta check. 50 iterations; even a tiny per-iter + // leak would show up as +50 here. Allow 20 stragglers for + // subprocess I/O goroutines that haven't been GC'd yet. + afterLoop := runtime.NumGoroutine() + if afterLoop > baseline+20 { + t.Errorf("goroutine leak across %d reconnect cycles: baseline=%d after=%d (delta=%d)", + iterations, baseline, afterLoop, afterLoop-baseline) + } +} diff --git a/seaweed-block/scripts/iterate-m01-nvme.sh b/seaweed-block/scripts/iterate-m01-nvme.sh new file mode 100644 index 0000000000..dee01b4968 --- /dev/null +++ b/seaweed-block/scripts/iterate-m01-nvme.sh @@ -0,0 +1,178 @@ +#!/usr/bin/env bash +# iterate-m01-nvme.sh — L3-A sign-prep m01 NVMe/TCP sanity harness +# +# Runs on local workstation, drives m01 over SSH. Rebuilds V3 +# binaries from current phase-15 tree, spins master + 3 volumes, +# then walks the two matrices: +# +# Matrix A (cycle stability): attach/mkfs/mount/dd/sync/umount/disconnect × N +# Matrix B (size coverage): for each size in {32K,256K,1M}, dd and readback × M +# +# Exit 0 on all-green; non-zero + diagnostic artifacts on any failure. +# +# Ownership: QA. Part of T2 Batch 11c sign prep per +# sw-block/design/v3-phase-15-t2-batch-11c-test-specs.md §3.1. + +set -euo pipefail + +# --- Config (env-overridable) --- +M01_HOST="${M01_HOST:-testdev@192.168.1.181}" +SSH_KEY="${SSH_KEY:-/c/work/dev_server/testdev_key}" +SRC_DIR="${SRC_DIR:-/c/work/seaweed_block}" +SMB_STAGE="${SMB_STAGE:-/v/share/t2-sanity/seaweed_block}" +SMB_STAGE_REMOTE="${SMB_STAGE_REMOTE:-/mnt/smb/work/share/t2-sanity/seaweed_block}" +REMOTE_BUILD_DIR="${REMOTE_BUILD_DIR:-/tmp/t2m01_sb}" +REMOTE_RUN_DIR="${REMOTE_RUN_DIR:-/tmp/t2m01}" +SUBSYS_NQN="${SUBSYS_NQN:-nqn.2026-04.m01:v1-r1}" +MATRIX_A_CYCLES="${MATRIX_A_CYCLES:-10}" +MATRIX_B_ITERATIONS="${MATRIX_B_ITERATIONS:-50}" +ARTIFACT_DIR="${ARTIFACT_DIR:-${SRC_DIR%/*}/seaweedfs/sw-block/design/bugs/001-artifacts}" + +SSH="ssh -i ${SSH_KEY} -o ConnectTimeout=10 ${M01_HOST}" + +# --- Helpers --- + +log() { printf '\033[1;36m[iterate-m01]\033[0m %s\n' "$*" >&2; } +die() { printf '\033[1;31m[iterate-m01 FAIL]\033[0m %s\n' "$*" >&2; exit 1; } + +collect_diagnostics() { + local label="$1" + log "collecting diagnostics [${label}]..." + $SSH "sudo dmesg -T | grep -i nvme1" > "${ARTIFACT_DIR}/m01-dmesg-${label}.txt" 2>/dev/null || true + scp -i "${SSH_KEY}" "${M01_HOST}:${REMOTE_RUN_DIR}/logs/v1.log" "${ARTIFACT_DIR}/m01-v1-${label}.log" 2>/dev/null || true + log " → ${ARTIFACT_DIR}/m01-{dmesg,v1}-${label}.*" +} + +check_dmesg_clean() { + local label="$1" + local dmesg + dmesg=$($SSH "sudo dmesg -T | grep -i nvme1 | tail -30") + for pattern in 'r2t len.*exceeded' 'receive failed:' 'Reconnecting in' 'Failed reconnect'; do + if echo "${dmesg}" | grep -qE "${pattern}"; then + collect_diagnostics "${label}-fail" + die "dmesg shows '${pattern}' after ${label}; see ${ARTIFACT_DIR}/" + fi + done +} + +start_services() { + log "starting blockmaster + 3 volumes on m01..." + # Pre-cleanup: prior run may have left stale connections or mounts. + $SSH ' +sudo umount /mnt/t2nvme 2>/dev/null || true +sudo nvme disconnect -n '${SUBSYS_NQN}' 2>/dev/null || true +' >/dev/null 2>&1 || true + $SSH " +rm -rf ${REMOTE_RUN_DIR}/store ${REMOTE_RUN_DIR}/v1-s* && mkdir -p ${REMOTE_RUN_DIR}/logs +nohup /tmp/blockmaster --authority-store ${REMOTE_RUN_DIR}/store --listen 127.0.0.1:9180 \ + --topology ${REMOTE_RUN_DIR}/topology.yaml --t0-print-ready \ + > ${REMOTE_RUN_DIR}/logs/master.log 2>&1 ${REMOTE_RUN_DIR}/logs/v\${S}.log 2>&1 /dev/null || true + pgrep -af "blockmaster\|blockvolume" | awk "{print \$1}" | xargs -r kill 2>/dev/null || true + sleep 1 + pgrep -af "blockmaster\|blockvolume" || true' >/dev/null 2>&1 || true +} + +# --- Phase 1: sync + rebuild --- + +log "syncing source to SMB stage..." +cp -ru "${SRC_DIR}/core" "${SMB_STAGE}/" +cp -ru "${SRC_DIR}/cmd" "${SMB_STAGE}/" +cp "${SRC_DIR}/go.mod" "${SRC_DIR}/go.sum" "${SMB_STAGE}/" 2>/dev/null || true + +log "rebuilding on m01..." +$SSH " +cp -ru ${SMB_STAGE_REMOTE}/core ${REMOTE_BUILD_DIR}/ +cp -ru ${SMB_STAGE_REMOTE}/cmd ${REMOTE_BUILD_DIR}/ +cd ${REMOTE_BUILD_DIR} +go build -buildvcs=false -o /tmp/blockmaster ./cmd/blockmaster +go build -buildvcs=false -o /tmp/blockvolume ./cmd/blockvolume +echo BUILD_OK +" | tail -3 + +# --- Phase 2: Matrix A — cycle stability --- + +log "Matrix A — ${MATRIX_A_CYCLES} attach/mkfs/mount/dd/sync/umount/disconnect cycles" +start_services + +for i in $(seq 1 "${MATRIX_A_CYCLES}"); do + log " cycle ${i}/${MATRIX_A_CYCLES}..." + $SSH " +set -e +sudo nvme connect -t tcp -a 127.0.0.1 -s 4421 -n ${SUBSYS_NQN} >/dev/null 2>&1 +sleep 1 +DEV=\$(sudo nvme list | awk '/SeaweedFS/ {print \$1; exit}') +sudo mkfs.ext4 -F -b 1024 -I 128 -N 16 \${DEV} >/dev/null 2>&1 +sudo mkdir -p /mnt/t2nvme +sudo mount \${DEV} /mnt/t2nvme +echo \"cycle-${i}-data\" | sudo tee /mnt/t2nvme/t.txt >/dev/null +sudo sync +sudo umount /mnt/t2nvme +sudo nvme disconnect -n ${SUBSYS_NQN} >/dev/null 2>&1 +" || die "cycle ${i} failed; check m01 state" + check_dmesg_clean "cycle-${i}" +done + +log " Matrix A all ${MATRIX_A_CYCLES} cycles PASS" + +# --- Phase 3: Matrix B — size coverage --- + +log "Matrix B — size matrix (32K/256K/1M) × ${MATRIX_B_ITERATIONS}" + +for size_bs in "32K" "256K" "1M"; do + # m01 volume is 1 MiB; the point here is to exercise the NVMe + # wire path at multiple sizes, not persistence. Each write + # overwrites block 0 — any R2T / H2CData / CapResp protocol + # regression at a given size surfaces as a dd failure or + # dmesg error, which check_dmesg_clean catches. + case "${size_bs}" in + 32K) count="${MATRIX_B_ITERATIONS}" ;; # 50 + 256K) count="$((MATRIX_B_ITERATIONS / 5))" ;; # 10 + 1M) count="5" ;; # 5 full-volume writes + esac + + log " size=${size_bs} count=${count}" + $SSH " +set -e +sudo nvme connect -t tcp -a 127.0.0.1 -s 4421 -n ${SUBSYS_NQN} >/dev/null 2>&1 +sleep 1 +DEV=\$(sudo nvme list | awk '/SeaweedFS/ {print \$1; exit}') +for i in \$(seq 1 ${count}); do + sudo dd if=/dev/urandom of=\${DEV} bs=${size_bs} count=1 conv=notrunc status=none 2>&1 || exit 1 +done +sudo sync +sudo nvme disconnect -n ${SUBSYS_NQN} >/dev/null 2>&1 +" || die "Matrix B size=${size_bs} failed" + check_dmesg_clean "size-${size_bs}" +done + +log " Matrix B all sizes PASS" + +# --- Phase 4: cleanup + summary --- + +collect_diagnostics "pass" +stop_services + +log "ALL MATRICES GREEN" +log " Matrix A: ${MATRIX_A_CYCLES} cycles" +log " Matrix B: 32K/256K/1M size coverage" +log " Artifacts: ${ARTIFACT_DIR}/m01-{dmesg,v1}-pass.*" +log "" +log "Post to BUG-001 §12 log + closure report §A.3 batch 11c row." +exit 0