From 1b9dbbaea3e8bbe565c447aa14bc615336065a44 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 20:15:19 -0800 Subject: [PATCH 1/9] feat: negotiate NVMe command retry delays for transient readiness --- ...ure_retry_delay_kernel_integration_test.go | 108 +++++++++++++ .../core/frontend/nvme/admin_features.go | 27 ++++ .../core/frontend/nvme/controller.go | 14 ++ seaweed-block/core/frontend/nvme/identify.go | 2 + .../frontend/nvme/read_ready_retry_test.go | 150 ++++++++++++++++-- .../core/frontend/nvme/retry_delay.go | 12 ++ seaweed-block/core/frontend/nvme/session.go | 6 +- seaweed-block/docs/design/invariants.md | 2 + seaweed-block/docs/volume-lifecycle.md | 11 ++ 9 files changed, 318 insertions(+), 14 deletions(-) create mode 100644 seaweed-block/cmd/blockvolume/procedure_retry_delay_kernel_integration_test.go create mode 100644 seaweed-block/core/frontend/nvme/retry_delay.go diff --git a/seaweed-block/cmd/blockvolume/procedure_retry_delay_kernel_integration_test.go b/seaweed-block/cmd/blockvolume/procedure_retry_delay_kernel_integration_test.go new file mode 100644 index 0000000000..61de82a4d3 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/procedure_retry_delay_kernel_integration_test.go @@ -0,0 +1,108 @@ +//go:build linux && subprocess && chunkstore_integration + +package main_test + +import ( + "bytes" + "context" + "fmt" + "net" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" +) + +// This opt-in procedure uses the kernel's block I/O retry path, not passthrough +// commands or the userspace test initiator. The lab's retained build overlay +// holds the holder's first write Busy for 2 s before any storage I/O. +func TestProcedureKernelReadinessRetryDelay(t *testing.T) { + if os.Getenv("SWBLOCK_NVME_RETRY_KERNEL") != "1" { + t.Skip("requires a disposable root Linux host and the retained 2s Busy overlay") + } + budget, err := os.ReadFile("/sys/module/nvme_core/parameters/max_retries") + if err != nil || strings.TrimSpace(string(budget)) != "5" { + t.Fatalf("kernel max_retries=%q err=%v; require default5", budget, err) + } + uuid, err := os.ReadFile("/proc/sys/kernel/random/uuid") + if err != nil { + t.Fatal(err) + } + token := strings.TrimSpace(string(uuid)) + nqn := "nqn.2026-12.io.seaweedfs:retry-" + strings.ReplaceAll(token, "-", "") + root := t.TempDir() + receipt := filepath.Join(root, "busy-started") + t.Setenv("SWBLOCK_TEST_BUSY_RECEIPT", receipt) + env := startHandoffEnvWith(t, 1, nil) + env.volExtra = []string{"--nvme-subsysnqn", nqn, "--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"} + holder := env.start(t, "kernel-retry-holder", "s1") + env.adopt(t, holder, "s1") + host, port, err := net.SplitHostPort(env.hosts["s1"].nvme) + if err != nil { + t.Fatal(err) + } + cleanup := func() { + controllers, _ := filepath.Glob("/sys/class/nvme/nvme*") + for _, controller := range controllers { + got, _ := os.ReadFile(filepath.Join(controller, "subsysnqn")) + if strings.TrimSpace(string(got)) == nqn { + if err := os.WriteFile(filepath.Join(controller, "delete_controller"), []byte("1"), 0200); err != nil { + t.Errorf("disconnect own controller: %v", err) + } + } + } + } + t.Cleanup(cleanup) + fabric, err := os.OpenFile("/dev/nvme-fabrics", os.O_RDWR, 0) + if err != nil { + t.Fatal(err) + } + _, err = fabric.WriteString(fmt.Sprintf("transport=tcp,traddr=%s,trsvcid=%s,nqn=%s,hostnqn=nqn.2026-12.io.seaweedfs:host-%s,hostid=%s,nr_io_queues=1", host, port, nqn, token, token)) + closeErr := fabric.Close() + if err != nil || closeErr != nil { + t.Fatalf("kernel connect: write=%v close=%v", err, closeErr) + } + var device string + for end := time.Now().Add(20 * time.Second); time.Now().Before(end); time.Sleep(50 * time.Millisecond) { + blocks, _ := filepath.Glob("/sys/block/nvme*n*") + for _, block := range blocks { + got, _ := os.ReadFile(filepath.Join(block, "device", "subsysnqn")) + if strings.TrimSpace(string(got)) == nqn { + device = "/dev/" + filepath.Base(block) + break + } + } + if device != "" { + break + } + } + if device == "" { + t.Fatalf("no own namespace for %s", nqn) + } + payload := bytes.Repeat([]byte{0x6d}, 4096) + source := filepath.Join(root, "payload") + if err := os.WriteFile(source, payload, 0600); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + started := time.Now() + out, err := exec.CommandContext(ctx, "dd", "if="+source, "of="+device, "bs=4096", "count=1", "oflag=direct", "conv=fdatasync", "status=none").CombinedOutput() + elapsed := time.Since(started) + t.Logf("kernel default retries=5 device=%s write_elapsed=%s err=%v output=%s", device, elapsed, err, out) + if err != nil { + t.Fatalf("kernel write failed inside 2s Busy window: %v %s", err, out) + } + if elapsed < 1900*time.Millisecond { + t.Fatalf("2s hold was not exercised: elapsed=%s", elapsed) + } + if _, err := os.Stat(receipt); err != nil { + t.Fatalf("missing controlled Busy witness: %v", err) + } + got, err := exec.CommandContext(ctx, "dd", "if="+device, "bs=4096", "count=1", "iflag=direct", "status=none").Output() + if err != nil || !bytes.Equal(got, payload) { + t.Fatalf("kernel readback err=%v bytes=%d equal=%t", err, len(got), bytes.Equal(got, payload)) + } +} diff --git a/seaweed-block/core/frontend/nvme/admin_features.go b/seaweed-block/core/frontend/nvme/admin_features.go index 02b8e4c008..ed9a32b281 100644 --- a/seaweed-block/core/frontend/nvme/admin_features.go +++ b/seaweed-block/core/frontend/nvme/admin_features.go @@ -8,6 +8,7 @@ import "time" // - Set Features (opcode 0x09) // FID 0x07 Number of Queues — grants NSQR/NCQR // FID 0x0F Keep Alive Timer — store only (no timer) +// FID 0x16 Host Behavior Support -- negotiated ACRE only // - Get Features (opcode 0x0A) // FID 0x07 / 0x0F — round-trip what was set // - Keep Alive (opcode 0x18) — unconditional Success @@ -29,6 +30,7 @@ import "time" const ( featNumberOfQueues uint8 = 0x07 featKeepAliveTimer uint8 = 0x0F + featHostBehavior uint8 = 0x16 ) // handleSetFeatures services admin opcode 0x09. @@ -45,6 +47,24 @@ func (s *Session) handleSetFeatures(req *Request) error { } fid := uint8(cmd.D10 & 0xFF) switch fid { + case featHostBehavior: + valid := len(req.payload) == 512 && cmd.D10&(1<<31) == 0 && cmd.D11 == 0 + if valid { + valid = req.payload[0] <= 1 + for _, b := range req.payload[1:] { + if b != 0 { + valid = false + break + } + } + } + if !valid { + req.resp.Status = MakeStatusField(SCTGeneric, SCInvalidField, true) + } else { + s.ctrl.setACRE(req.payload[0] == 1) + } + s.enqueueResponse(&response{resp: req.resp}) + return nil case featNumberOfQueues: // CDW11 low 16 = NSQR, high 16 = NCQR, both zero-based. // Cap each at 7 (T2 defensive cap). @@ -90,6 +110,13 @@ func (s *Session) handleGetFeatures(req *Request) error { return nil } switch fid { + case featHostBehavior: + data := make([]byte, 512) + if sel == 0 && s.ctrl.getACRE() { + data[0] = 1 + } + s.enqueueResponse(&response{resp: req.resp, c2hData: data}) + return nil case featNumberOfQueues: req.resp.DW0 = s.ctrl.getNumQueues() s.enqueueResponse(&response{resp: req.resp}) diff --git a/seaweed-block/core/frontend/nvme/controller.go b/seaweed-block/core/frontend/nvme/controller.go index 9fb13bbf5b..eb3b2be657 100644 --- a/seaweed-block/core/frontend/nvme/controller.go +++ b/seaweed-block/core/frontend/nvme/controller.go @@ -67,6 +67,7 @@ type adminController struct { // Set Features state (11b A11/A12). Values the host asked // for; Get Features returns the same values back. numQueues uint32 // DW0 response for Feature 0x07; low 16 = NSQR, high 16 = NCQR + acre bool // negotiated Advanced Command Retry Enable (volatile) kato uint32 // Keep Alive Timeout, milliseconds // Single-slot pending AER (QA finding testing-#2, AERL=0 @@ -186,6 +187,7 @@ func (c *adminController) setCC(newCC uint32) uint32 { c.csts |= 0x01 // set RDY } else { c.csts &^= 0x01 // clear RDY + c.acre = false } _ = prevEN // kept for future state-transition logging return c.csts @@ -265,3 +267,15 @@ func (c *adminController) clearPendingAER() { c.pendingAERHasCID = false c.mu.Unlock() } + +func (c *adminController) setACRE(enabled bool) { + c.mu.Lock() + c.acre = enabled + c.mu.Unlock() +} + +func (c *adminController) getACRE() bool { + c.mu.Lock() + defer c.mu.Unlock() + return c.acre +} diff --git a/seaweed-block/core/frontend/nvme/identify.go b/seaweed-block/core/frontend/nvme/identify.go index 357dc32f74..f81e13d7c2 100644 --- a/seaweed-block/core/frontend/nvme/identify.go +++ b/seaweed-block/core/frontend/nvme/identify.go @@ -77,6 +77,8 @@ func (s *Session) handleAdminIdentify(req *Request) error { // §6 stop rule #4 ("advertised ≡ implemented"). func (s *Session) buildIdentifyController() []byte { buf := make([]byte, identifySize) + binary.LittleEndian.PutUint16(buf[128:130], 1) // CRDT1, 100 ms units + binary.LittleEndian.PutUint16(buf[130:132], 10) // CRDT2, readiness retry delay: 1 s subNQN := s.ctrlSubNQN() volumeID := s.ctrlVolumeID() 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 0b89d1dfad..8e65719bd8 100644 --- a/seaweed-block/core/frontend/nvme/read_ready_retry_test.go +++ b/seaweed-block/core/frontend/nvme/read_ready_retry_test.go @@ -2,6 +2,7 @@ package nvme import ( "context" + "encoding/binary" "errors" "fmt" "testing" @@ -46,20 +47,147 @@ func TestSessionReadNotReadyIsRetryable(t *testing.T) { } } -func TestReadinessRetryDelayIsNotAdvertised(t *testing.T) { +func TestReadinessRetryDelayNegotiation(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]) + id := s.buildIdentifyController() + if binary.LittleEndian.Uint16(id[128:130]) != 1 || binary.LittleEndian.Uint16(id[130:132]) != 10 || binary.LittleEndian.Uint16(id[132:134]) != 0 { + t.Fatalf("CRDT bytes=%v", id[128:134]) + } + for _, enable := range []byte{1, 0} { + req := &Request{payload: make([]byte, 512)} + req.capsule.D10 = 0x16 + req.payload[0] = enable + if err := s.handleSetFeatures(req); err != nil { + t.Fatal(err) + } + if got := (<-s.respCh).resp.Status; got != 0 { + t.Fatalf("ACRE=%d status=%#x", enable, got) + } + get := &Request{} + get.capsule.D10 = 0x16 + if err := s.handleGetFeatures(get); err != nil { + t.Fatal(err) + } + answer := <-s.respCh + if answer.resp.Status != 0 || len(answer.c2hData) != 512 || answer.c2hData[0] != enable { + t.Fatalf("ACRE Get=%+v", answer) } } - req := &Request{} - req.capsule.D10 = 0x16 // Host Behavior Support, including ACRE. - if err := s.handleSetFeatures(req); err != nil { - t.Fatal(err) +} + +type retryDelayBackend struct { + frontend.Backend + err error +} + +func (b *retryDelayBackend) Read(context.Context, int64, []byte) (int, error) { return 0, b.err } +func (b *retryDelayBackend) Write(context.Context, int64, []byte) (int, error) { return 0, b.err } +func (b *retryDelayBackend) Sync(context.Context) error { return b.err } + +func TestSessionRetryDelayOnEveryRetryableIO(t *testing.T) { + for _, opcode := range []uint8{ioRead, ioWrite, ioFlush} { + for _, enable := range []bool{false, true} { + for _, cause := range []error{frontend.ErrNotReady, frontend.ErrBackendBusy, frontend.ErrStalePrimary, frontend.ErrBackendClosed, errors.New("disk fault")} { + t.Run(fmt.Sprintf("opcode=%d/acre=%t/%v", opcode, enable, cause), func(t *testing.T) { + b := &retryDelayBackend{Backend: testback.NewRecordingBackend(frontend.Identity{VolumeID: "v1"}), err: cause} + s := &Session{handler: NewIOHandler(HandlerConfig{Backend: b}), ctrl: &adminController{}, respCh: make(chan *response, 1), done: make(chan struct{})} + if enable { + req := &Request{payload: make([]byte, 512)} + req.payload[0] = 1 + req.capsule.D10 = 0x16 + s.handleSetFeatures(req) + if got := (<-s.respCh).resp.Status; got != 0 { + t.Fatalf("ACRE enable=%#x", got) + } + } + req := &Request{payload: make([]byte, 4096)} + req.capsule.OpCode = opcode + req.capsule.NSID = 1 + s.dispatchIO(context.Background(), req) + status := (<-s.respCh).resp.Status + crd := (status >> 12) & 3 + transient := cause == frontend.ErrNotReady || cause == frontend.ErrBackendBusy + want := uint16(0) + if enable && transient { + want = 2 + } + if crd != want { + t.Fatalf("status=%#x CRD=%d want%d", status, crd, want) + } + if transient && (status&0x8000 != 0 || status&0xffe != 0x0104) { + t.Fatalf("retryable status changed=%#x", status) + } + }) + } + } } - if got := (<-s.respCh).resp.Status; got != MakeStatusField(SCTGeneric, SCInvalidField, true) { - t.Fatalf("unsupported Host Behavior status=%#x", got) +} + +func TestHostBehaviorRejectsUnsupportedPayloadWithoutChangingACRE(t *testing.T) { + s := &Session{ctrl: &adminController{}, respCh: make(chan *response, 1), done: make(chan struct{})} + for _, tc := range []struct { + name string + size int + offset int + value byte + d10, d11 uint32 + }{ + {"empty", 0, 0, 0, 0, 0}, {"short", 511, 0, 0, 0, 0}, {"long", 513, 0, 0, 0, 0}, + {"bad-acre", 512, 0, 2, 0, 0}, {"etdas", 512, 1, 1, 0, 0}, {"lbafee", 512, 2, 1, 0, 0}, {"reserved", 512, 511, 1, 0, 0}, + {"save", 512, 0, 1, 1 << 31, 0}, {"cdw11", 512, 0, 1, 0, 1}, + } { + t.Run(tc.name, func(t *testing.T) { + enable := &Request{payload: make([]byte, 512)} + enable.payload[0] = 1 + enable.capsule.D10 = 0x16 + s.handleSetFeatures(enable) + if (<-s.respCh).resp.Status != 0 { + t.Fatal("enable failed") + } + req := &Request{payload: make([]byte, tc.size)} + req.capsule.D10 = 0x16 | tc.d10 + req.capsule.D11 = tc.d11 + if tc.size > tc.offset { + req.payload[tc.offset] = tc.value + } + s.handleSetFeatures(req) + if got := (<-s.respCh).resp.Status; got != MakeStatusField(SCTGeneric, SCInvalidField, true) { + t.Fatalf("invalid payload accepted: %#x", got) + } + get := &Request{} + get.capsule.D10 = 0x16 + s.handleGetFeatures(get) + if got := (<-s.respCh).c2hData; len(got) != 512 || got[0] != 1 { + t.Fatalf("refusal changed ACRE=%v", got) + } + }) + } +} + +func TestRetryDelayControllerIsolationAndReset(t *testing.T) { + admin := &Session{ctrl: newAdminController(1, "test", "host-a", "v1"), respCh: make(chan *response, 1), done: make(chan struct{})} + io := &Session{ctrl: admin.ctrl} + other := &Session{ctrl: newAdminController(2, "test", "host-b", "v1")} + res := IOResult{SCT: SCTGeneric, SC: SCNamespaceNotReady, retryable: true} + req := &Request{payload: make([]byte, 512)} + req.payload[0] = 1 + req.capsule.D10 = 0x16 + admin.handleSetFeatures(req) + if (<-admin.respCh).resp.Status != 0 { + t.Fatal("enable failed") + } + if io.completionStatus(res) != (res.completionStatus()|2<<12) || other.completionStatus(res) != res.completionStatus() { + t.Fatal("negotiation not controller-scoped") + } + get := &Request{} + get.capsule.D10 = 0x16 | 1<<8 + admin.handleGetFeatures(get) + if got := (<-admin.respCh).c2hData; len(got) != 512 || got[0] != 0 { + t.Fatal("default ACRE not zero") + } + admin.ctrl.setCC(1) + admin.ctrl.setCC(0) + if io.completionStatus(res) != res.completionStatus() { + t.Fatal("controller reset retained ACRE") } } diff --git a/seaweed-block/core/frontend/nvme/retry_delay.go b/seaweed-block/core/frontend/nvme/retry_delay.go new file mode 100644 index 0000000000..8f2e19be4e --- /dev/null +++ b/seaweed-block/core/frontend/nvme/retry_delay.go @@ -0,0 +1,12 @@ +package nvme + +// completionStatus adds negotiated retry delay without changing the error class +// or DNR. Every transient namespace-not-ready result uses the readiness delay; +// selecting the shorter class would require a proved sub-500 ms bound. +func (s *Session) completionStatus(r IOResult) uint16 { + status := r.completionStatus() + if r.retryable && r.SCT == SCTGeneric && r.SC == SCNamespaceNotReady && s.ctrl != nil && s.ctrl.getACRE() { + status |= 2 << 12 + } + return status +} diff --git a/seaweed-block/core/frontend/nvme/session.go b/seaweed-block/core/frontend/nvme/session.go index 823f126e62..e470ac91f5 100644 --- a/seaweed-block/core/frontend/nvme/session.go +++ b/seaweed-block/core/frontend/nvme/session.go @@ -482,7 +482,7 @@ func (s *Session) dispatchIO(ctx context.Context, req *Request) { if s.logger != nil { s.logger.Printf("nvme: Flush failed qid=%d nsid=%d sct=%#x sc=%#x reason=%s", s.qid, req.capsule.NSID, res.SCT, res.SC, res.Reason) } - req.resp.Status = res.completionStatus() + req.resp.Status = s.completionStatus(res) } s.enqueueResponse(&response{resp: req.resp}) default: @@ -593,7 +593,7 @@ func (s *Session) handleRead(ctx context.Context, req *Request) { NLB: req.capsule.LbaLength(), }) if res.AsError() != nil { - req.resp.Status = res.completionStatus() + req.resp.Status = s.completionStatus(res) s.enqueueResponse(&response{resp: req.resp}) return } @@ -620,7 +620,7 @@ func (s *Session) handleWrite(ctx context.Context, req *Request) { }) s.recordWriteHandler(time.Since(handlerStart)) if res.AsError() != nil { - req.resp.Status = res.completionStatus() + req.resp.Status = s.completionStatus(res) } s.enqueueResponse(&response{resp: req.resp, writeCompletion: true, queuedAt: time.Now()}) } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 57112b02b1..40a6ea6e05 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -617,6 +617,8 @@ 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-NVME-RETRY-DELAY-001` | A negotiated ACRE controller returns retryable Namespace Not Ready with CRD=2 (CRDT2=1 s), DNR clear; permanent and successful completions do not gain retry delay. | M1 I/O completion encoding | `Session.completionStatus`; read/write/flush session handlers; `buildIdentifyController` | `TestReadinessRetryDelayNegotiation`, `TestSessionRetryDelayOnEveryRetryableIO` | NONE (wire encoding; no authority transition) | ACTIVE | +| `INV-NVME-HOST-BEHAVIOR-001` | ACRE accepts only a supported 512-byte Host Behavior payload, is scoped to its controller and clears on controller reset; an invalid update preserves its prior value. | M1 controller capability negotiation | `handleSetFeatures`, `handleGetFeatures`, `adminController.setCC` | `TestHostBehaviorRejectsUnsupportedPayloadWithoutChangingACRE`, `TestRetryDelayControllerIsolationAndReset` | NONE (volatile capability; no authority 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 | diff --git a/seaweed-block/docs/volume-lifecycle.md b/seaweed-block/docs/volume-lifecycle.md index 316deaf89e..5eee3761ed 100644 --- a/seaweed-block/docs/volume-lifecycle.md +++ b/seaweed-block/docs/volume-lifecycle.md @@ -556,6 +556,17 @@ follow from that order: answer is `snapshot_deleting ... is being deleted; wait for the delete to finish, then reuse the name`, not the earlier success. +## NVMe transient retry delay + +Linux hosts that enable Advanced Command Retry Enable (ACRE) receive a one-second +retry delay on retryable Namespace Not Ready completions. The target advertises +CRDT1=100 ms and CRDT2=1 s, and selects CRD=2 for all retryable SC 0x82 responses. +The default Linux budget remains five retries; this is bounded backoff, not an +unlimited wait. A host that does not negotiate ACRE keeps its existing behavior. +A Busy condition that persists beyond the host's retry budget can still become +an I/O error and needs diagnosis; readiness observation does not reserve future +admission. Permanent and lineage errors are not converted to retryable errors. + ## Symptoms | You see | It means | Do | From f76609cb4f242e06f8f1d5932f6230be2715893c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 20:33:06 -0800 Subject: [PATCH 2/9] test: hold non-negotiating NVMe write through attach readiness --- .../durable/attach_nvme_no_acre_test.go | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 seaweed-block/core/frontend/durable/attach_nvme_no_acre_test.go diff --git a/seaweed-block/core/frontend/durable/attach_nvme_no_acre_test.go b/seaweed-block/core/frontend/durable/attach_nvme_no_acre_test.go new file mode 100644 index 0000000000..a74683dc4f --- /dev/null +++ b/seaweed-block/core/frontend/durable/attach_nvme_no_acre_test.go @@ -0,0 +1,53 @@ +package durable_test + +import ( + "bytes" + "context" + "testing" + "testing/synctest" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/frontend/nvme" +) + +// A host without ACRE needs no retry when attachment becomes ready inside the +// existing allowance: its original command remains held before storage I/O. +func TestNVMeWithoutACREHoldsWriteThroughAttachReadiness(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + _, b, _, publishReady := pendingTakeoverReadWithRelease(t, -1) + waiting := make(chan struct{}, 1) + durable.SetTestBeforeAttachWait(b, func() { + select { + case waiting <- struct{}{}: + default: + } + }) + handler := nvme.NewIOHandler(nvme.HandlerConfig{Backend: b, BlockSize: 4096}) + payload := block(0x76) + done := make(chan nvme.IOResult, 1) + go func() { + done <- handler.Handle(context.Background(), nvme.IOCommand{ + Opcode: 0x01, NSID: 1, SLBA: 33, NLB: 1, Data: payload, + }) + }() + <-waiting + synctest.Wait() + time.Sleep(2 * time.Second) + synctest.Wait() + select { + case result := <-done: + t.Fatalf("command completed before readiness: %+v", result) + default: + } + publishReady() + synctest.Wait() + if result := <-done; result.AsError() != nil { + t.Fatalf("held command failed instead of completing: %+v", result) + } + got := make([]byte, len(payload)) + if n, err := b.Read(context.Background(), 33*4096, got); err != nil || n != len(got) || !bytes.Equal(got, payload) { + t.Fatalf("held write readback n=%d err=%v exact=%t", n, err, bytes.Equal(got, payload)) + } + }) +} From 3fdc17e3e7cc53ff8939e1f81c00ac57ddc71834 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 20:29:41 -0800 Subject: [PATCH 3/9] ci: retain timed test events and whole-job load on failure Co-Authored-By: Claude Opus 5.5 --- seaweed-block/.github/scripts/ci-evidence.md | 39 ++++ seaweed-block/.github/scripts/ci-load-test.py | 101 ++++++++++ seaweed-block/.github/scripts/ci-load.py | 172 ++++++++++++++++++ .../.github/scripts/go-test-output.py | 9 + .../.github/scripts/record-go-test-test.sh | 26 +++ .../.github/scripts/record-go-test.sh | 16 ++ seaweed-block/.github/workflows/test.yml | 60 ++++-- 7 files changed, 407 insertions(+), 16 deletions(-) create mode 100644 seaweed-block/.github/scripts/ci-evidence.md create mode 100644 seaweed-block/.github/scripts/ci-load-test.py create mode 100644 seaweed-block/.github/scripts/ci-load.py create mode 100644 seaweed-block/.github/scripts/go-test-output.py create mode 100644 seaweed-block/.github/scripts/record-go-test-test.sh create mode 100644 seaweed-block/.github/scripts/record-go-test.sh diff --git a/seaweed-block/.github/scripts/ci-evidence.md b/seaweed-block/.github/scripts/ci-evidence.md new file mode 100644 index 0000000000..36a1b0336b --- /dev/null +++ b/seaweed-block/.github/scripts/ci-evidence.md @@ -0,0 +1,39 @@ +# Failed-job evidence + +Both test suites keep one `ci---` artifact on failure for +14 days. `go-test.json` contains Go's timestamped events and per-test `Elapsed` +values; process shards also keep their original JSON, logs and exit receipts. +`go-test.stderr` keeps build/tool errors outside Go's JSON event stream. The +console still shows the original test output. Test arguments, scope, timeouts, +exit-code handling and the required-tests gate are unchanged. + +`load.tsv` begins immediately after checkout and samples once per second until +the final collection step. It covers setup, builds and tests; the checkout +itself and the artifact upload are outside the sampling interval. The sampler +has the job's maximum lifetime if cancellation prevents its stop step. The +stop receipt includes the process start time, so a recycled PID is not killed. + +Columns: + +- `ts_utc`: UTC timestamp with milliseconds. Scheduling gaps remain visible; + delayed sampling does not invent backfilled one-second rows. +- `load1`: machine load average. +- `steal_pct`, `iowait_pct`: interval percentages from `/proc/stat` (the first + row has no baseline and is null). Guest counters are not counted twice. +- `psi_cpu`, `psi_io`, `psi_mem`: JSON objects containing the kernel's `some` + and, when available, `full` pressure averages and cumulative microseconds. +- `disk_await_ms`: JSON map by device, calculated as the interval's read/write + milliseconds divided by completed reads/writes from `/proc/diskstats`. + Devices are kept separate, including partitions and device-mapper layers; + do not sum them. No completed IO, reset counters or a new device yields null. + Discard and flush-only operations are not included in this read/write mean. +- `cgroup_cpu_max`: JSON map of `cpu.max` for the sampler's current cgroup and + every visible ancestor. The sampler inherits the job's cgroup. Parent quotas + matter even when the leaf says `max`. Cgroup v1/unavailable data is null. +- `errors`: read/parse errors; missing or inaccessible counters are null, + never fabricated zero load. Consult `load.sampler.log` for sampler errors. + +No package installation, sudo, or `iostat` executable is required. `/proc` +CPU/PSI/disk observations are machine-wide; these are correlation evidence, +not proof that the job itself caused contention. Sampling is diagnostic and +does not revoke, retry or change a test's result. diff --git a/seaweed-block/.github/scripts/ci-load-test.py b/seaweed-block/.github/scripts/ci-load-test.py new file mode 100644 index 0000000000..d7fe06c350 --- /dev/null +++ b/seaweed-block/.github/scripts/ci-load-test.py @@ -0,0 +1,101 @@ +"""Fixed Linux counter fixtures; no host load or privileged runner needed.""" +import importlib.util +import json +import pathlib +import subprocess +import sys +import tempfile +import time +import unittest + +spec = importlib.util.spec_from_file_location('ci_load', pathlib.Path(__file__).with_name('ci-load.py')) +load = importlib.util.module_from_spec(spec) +spec.loader.exec_module(load) + + +class LoadTest(unittest.TestCase): + @unittest.skipUnless(sys.platform == 'linux', 'real /proc lifecycle is Linux-only') + def test_cli_samples_and_stops_its_own_process(self): + with tempfile.TemporaryDirectory() as name: + output = pathlib.Path(name)/'load.tsv' + command = [sys.executable, '-I', str(pathlib.Path(__file__).with_name('ci-load.py'))] + try: + subprocess.run(command+['start', str(output), '--duration', '30'], check=True, timeout=10) + deadline = time.monotonic()+10 + while time.monotonic() < deadline: + if output.exists() and len(output.read_text().splitlines()) >= 3: + break + time.sleep(0.05) + finally: + subprocess.run(command+['stop', str(output)], check=True, timeout=5) + lines = output.read_text().splitlines() + self.assertGreaterEqual(len(lines), 3) + self.assertTrue(lines[0].startswith('ts_utc\tload1\tsteal_pct')) + for line in lines[1:]: + fields = line.split('\t') + self.assertEqual(len(fields), 10) + self.assertTrue(fields[0].endswith('+00:00')) + for field in fields[1:]: + json.loads(field) + before = output.read_bytes() + time.sleep(0.1) + self.assertEqual(output.read_bytes(), before) + + def test_cpu_and_disk_interval_not_since_boot(self): + # CPU: 100 ticks, 10 iowait, 5 stolen. guest ticks are already in user. + before = {'cpu': [100, 0, 20, 800, 20, 0, 0, 10, 3, 0], + 'disks': {'nvme0n1': [10, 30]}} + after = {'cpu': [130, 0, 25, 850, 30, 0, 0, 15, 7, 0], + 'disks': {'nvme0n1': [14, 50], 'new': [1000, 9000]}} + cpu, disks = load.interval(before, after) + self.assertEqual(cpu, {'steal_pct': 5.0, 'iowait_pct': 10.0}) + self.assertEqual(disks, {'nvme0n1': 5.0, 'new': None}) + + def test_reset_or_no_io_is_unknown_not_zero_latency(self): + before = {'cpu': [10]*8, 'disks': {'sda': [10, 100], 'sdb': [20, 200]}} + after = {'cpu': [1]*8, 'disks': {'sda': [10, 100], 'sdb': [1, 3]}} + cpu, disks = load.interval(before, after) + self.assertEqual(cpu, {'steal_pct': None, 'iowait_pct': None}) + self.assertEqual(disks, {'sda': None, 'sdb': None}) + + def test_proc_fields_and_cgroup_ancestor_quota(self): + with tempfile.TemporaryDirectory() as name: + root = pathlib.Path(name) + (root/'pressure').mkdir() + (root/'self').mkdir() + mount = root/'cg' + (mount/'runner/job').mkdir(parents=True) + (mount/'cpu.max').write_text('max 100000\n') + (mount/'runner/cpu.max').write_text('200000 100000\n') + (mount/'runner/job/cpu.max').write_text('max 100000\n') + (root/'self/cgroup').write_text('0::/slice/runner/job\n') + (root/'self/mountinfo').write_text(f'1 0 0:1 /slice {mount.as_posix()} rw - cgroup2 cgroup rw\n') + (root/'loadavg').write_text('3.25 2.00 1.00 1/1 1\n') + (root/'stat').write_text('cpu 100 0 20 800 20 0 0 10 3 0\n') + (root/'diskstats').write_text('259 0 nvme0n1 2 0 0 6 3 0 0 9 0 0 0\n') + for kind in ('cpu', 'io', 'memory'): + (root/'pressure'/kind).write_text('some avg10=1.25 avg60=0.50 avg300=0.20 total=12345\n') + snapshot = load.read_snapshot(root) + self.assertEqual(snapshot['load1'], 3.25) + self.assertEqual(snapshot['disks'], {'nvme0n1': [5, 15]}) + self.assertEqual(snapshot['psi']['cpu']['some']['total'], 12345) + self.assertEqual(snapshot['cpu_max'][str(mount/'runner/cpu.max')], '200000 100000') + self.assertEqual(snapshot['errors'], []) + (mount/'cpu.max').unlink() + snapshot = load.read_snapshot(root) + self.assertEqual(snapshot['cpu_max'][str(mount/'runner/cpu.max')], '200000 100000') + self.assertIsNone(snapshot['cpu_max'][str(mount/'cpu.max')]) + self.assertTrue(snapshot['errors']) + + def test_missing_inputs_explicitly_reported(self): + with tempfile.TemporaryDirectory() as name: + snapshot = load.read_snapshot(pathlib.Path(name)) + self.assertIsNone(snapshot['load1']) + self.assertIsNone(snapshot['cpu']) + self.assertTrue(snapshot['errors']) + self.assertIsNone(snapshot['psi']['cpu']) + self.assertIsNone(snapshot['cpu_max']) + + +if __name__ == '__main__': + unittest.main() diff --git a/seaweed-block/.github/scripts/ci-load.py b/seaweed-block/.github/scripts/ci-load.py new file mode 100644 index 0000000000..54a4f5543f --- /dev/null +++ b/seaweed-block/.github/scripts/ci-load.py @@ -0,0 +1,172 @@ +"""One-second Linux job-load evidence. Missing counters are null, never zero. + +Disk await is delta(read_ms + write_ms) / delta(completed reads + writes), +per device from diskstats (the r_await/w_await weighted mean, not a sum across +stacked devices). PSI retains the kernel's avg10/60/300 and total microseconds. +cpu.max includes every visible ancestor, since a parent may impose the quota. +The sampler is diagnostic only; it has a job-sized lifetime even if stop is lost. +""" +import argparse +import datetime +import json +import os +import pathlib +import re +import signal +import subprocess +import sys +import threading +import time + + +def read_snapshot(proc=pathlib.Path('/proc')): + errors = [] + + def read(path, parse): + try: + return parse(path.read_text()) + except (OSError, ValueError, IndexError, StopIteration) as error: + errors.append(str(path)+': '+str(error)) + return None + + def pressure(text): + return {parts[0]: {k: (int(v) if k == 'total' else float(v)) + for k, v in (item.split('=') for item in parts[1:])} + for parts in (line.split() for line in text.splitlines()) if parts} + + def diskstats(text): + result = {} + for line in text.splitlines(): + fields = line.split() + # fields after the device name: reads, merges, sectors, ms, + # writes, merges, sectors, ms (present on all supported kernels). + result[fields[2]] = [int(fields[3])+int(fields[7]), int(fields[6])+int(fields[10])] + return result + + def quotas(_): + group = next(line.split('::', 1)[1] for line in (proc/'self/cgroup').read_text().splitlines() + if line.startswith('0::')) + for line in (proc/'self/mountinfo').read_text().splitlines(): + fields, filesystem = line.split(' - ', 1) + if filesystem.split()[0] != 'cgroup2': + continue + # mountinfo escapes whitespace and backslash with octal codes. + unescape = lambda value: re.sub(r'\\([0-7]{3})', lambda m: chr(int(m[1], 8)), value) + fields = fields.split() + base, mount = unescape(fields[3]), pathlib.Path(unescape(fields[4])) + if base != '/' and (group == base or group.startswith(base+'/')): + relative = group[len(base):].lstrip('/') + else: + # cgroup namespace: membership is relative to its visible root. + relative = group.lstrip('/') + current = mount / relative + current.relative_to(mount) + result = {} + while True: + path = current/'cpu.max' + # The real hierarchy root need not expose cpu.max. Preserve + # readable leaf/parent quotas even if another level is absent. + result[str(path)] = read(path, str.strip) + if current == mount: + return result + current = current.parent + raise ValueError('no visible cgroup v2 mount (v1 or unavailable)') + + return dict(load1=read(proc/'loadavg', lambda text: float(text.split()[0])), + cpu=read(proc/'stat', lambda text: [int(v) for v in next( + line for line in text.splitlines() if line.startswith('cpu ')).split()[1:]]), + disks=read(proc/'diskstats', diskstats), + psi={kind: read(proc/'pressure'/filename, pressure) for kind, filename in + [('cpu', 'cpu'), ('io', 'io'), ('mem', 'memory')]}, + cpu_max=read(proc/'self/cgroup', quotas), errors=errors) + + +def interval(before, after): + cpu = dict(steal_pct=None, iowait_pct=None) + old, new = before['cpu'], after['cpu'] + if old is not None and new is not None and len(old) >= 8 and len(new) >= 8: + deltas = [new[i]-old[i] for i in range(8)] # guest already included in user/nice + total = sum(deltas) + if min(deltas) >= 0 and total > 0: + cpu = dict(steal_pct=100*deltas[7]/total, iowait_pct=100*deltas[4]/total) + disks = None + if after['disks'] is not None: + disks = {} + for name, values in after['disks'].items(): + previous = (before['disks'] or {}).get(name) + disks[name] = None + if previous and values[0] > previous[0] and values[1] >= previous[1]: + disks[name] = (values[1]-previous[1])/(values[0]-previous[0]) + return cpu, disks + + +def sample(output, duration): + output.parent.mkdir(parents=True, exist_ok=True) + previous = dict(cpu=None, disks=None) + end, due = time.monotonic()+duration, time.monotonic() + stopped = threading.Event() + signal.signal(signal.SIGTERM, lambda *_: stopped.set()) + with output.open('w', buffering=1) as stream: + stream.write('ts_utc\tload1\tsteal_pct\tiowait_pct\tpsi_cpu\tpsi_io\tpsi_mem\tdisk_await_ms\tcgroup_cpu_max\terrors\n') + while not stopped.is_set() and time.monotonic() < end: + timestamp = datetime.datetime.now(datetime.timezone.utc).isoformat(timespec='milliseconds') + current = read_snapshot() + cpu, disks = interval(previous, current) + fields = [timestamp, current['load1'], cpu['steal_pct'], cpu['iowait_pct'], + current['psi']['cpu'], current['psi']['io'], current['psi']['mem'], + disks, current['cpu_max'], current['errors']] + stream.write('\t'.join(json.dumps(v, separators=(',', ':')) if not isinstance(v, str) else v + for v in fields)+'\n') + previous = current + due += 1 + stopped.wait(max(0, min(due, end)-time.monotonic())) + # Do not emit a burst of fictitious one-second samples after a stall. + due = max(due, time.monotonic()) + + +def identity(pid): + # comm may contain spaces or parentheses; starttime is field 22. + return pathlib.Path(f'/proc/{pid}/stat').read_text().rsplit(')', 1)[1].split()[19] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('action', choices=['start', 'sample', 'stop']) + parser.add_argument('output', type=pathlib.Path) + parser.add_argument('--duration', type=int, default=5400) + args = parser.parse_args() + receipt = args.output.with_suffix('.pid.json') + if args.action == 'sample': + sample(args.output, args.duration) + elif args.action == 'start': + args.output.parent.mkdir(parents=True, exist_ok=True) + with args.output.with_suffix('.sampler.log').open('w') as log: + child = subprocess.Popen([sys.executable, '-I', str(pathlib.Path(__file__).resolve()), + 'sample', str(args.output), '--duration', str(args.duration)], + stdin=subprocess.DEVNULL, stdout=log, stderr=log, start_new_session=True) + receipt.write_text(json.dumps(dict(pid=child.pid, start=identity(child.pid)))) + elif receipt.exists(): + owner = json.loads(receipt.read_text()) + handle = None + try: + # A pidfd makes the identity-check/signal pair safe even if the + # process exits and its numeric PID is recycled between the two. + handle = os.pidfd_open(owner['pid']) + if identity(owner['pid']) == owner['start']: + signal.pidfd_send_signal(handle, signal.SIGTERM) + # Flush the last row before the uploader reads the file. Never + # signal a reused PID and never wait indefinitely for evidence. + until = time.monotonic()+2 + while time.monotonic() < until and identity(owner['pid']) == owner['start']: + time.sleep(0.05) + except ProcessLookupError: + pass + except FileNotFoundError: + pass + finally: + if handle is not None: + os.close(handle) + + +if __name__ == '__main__': + main() diff --git a/seaweed-block/.github/scripts/go-test-output.py b/seaweed-block/.github/scripts/go-test-output.py new file mode 100644 index 0000000000..888af12ab0 --- /dev/null +++ b/seaweed-block/.github/scripts/go-test-output.py @@ -0,0 +1,9 @@ +"""Render go test -json Output events without changing the test verdict.""" +import json +import sys + +for line in sys.stdin: + event = json.loads(line) + if 'Output' in event: + sys.stdout.write(event['Output']) + sys.stdout.flush() diff --git a/seaweed-block/.github/scripts/record-go-test-test.sh b/seaweed-block/.github/scripts/record-go-test-test.sh new file mode 100644 index 0000000000..26d0955d27 --- /dev/null +++ b/seaweed-block/.github/scripts/record-go-test-test.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash +set -euo pipefail +here=$(cd "$(dirname "$0")" && pwd) +root=$(mktemp -d) +trap 'rm -rf "$root"' EXIT +mkdir -p "$root/bin" +cat >"$root/bin/go" <<'EOF' +#!/usr/bin/env bash +test "$1" = test && test "$2" = -json || exit 99 +printf '%s\n' '{"Time":"2026-12-02T00:00:01Z","Action":"run","Test":"TestX"}' +printf '%s\n' '{"Time":"2026-12-02T00:00:02Z","Action":"output","Test":"TestX","Output":"fixture output\n"}' +printf '%s\n' '{"Time":"2026-12-02T00:00:02Z","Action":"fail","Test":"TestX","Elapsed":1}' +echo 'fixture stderr' >&2 +exit "${FAKE_GO_EXIT:-0}" +EOF +chmod +x "$root/bin/go" +export PATH="$root/bin:$PATH" +code=0 +FAKE_GO_EXIT=7 bash "$here/record-go-test.sh" "$root/go-test.json" -run TestX >"$root/console" 2>"$root/stderr" || code=$? +test "$code" = 7 +grep -q 'fixture output' "$root/console" +grep -q 'fixture stderr' "$root/go-test.stderr" +"${PYTHON:-python3}" -c 'import json,sys; events=[json.loads(s) for s in open(sys.argv[1])]; assert len(events)==3; assert events[-1]["Elapsed"]==1; assert events[-1]["Time"]=="2026-12-02T00:00:02Z"' "$root/go-test.json" +FAKE_GO_EXIT=0 bash "$here/record-go-test.sh" "$root/go-test.json" -run TestX >"$root/console" 2>"$root/stderr" +test "$(wc -l <"$root/go-test.json")" = 6 +echo 'record-go-test: output, timestamp, elapsed, append and exit-status controls PASS' diff --git a/seaweed-block/.github/scripts/record-go-test.sh b/seaweed-block/.github/scripts/record-go-test.sh new file mode 100644 index 0000000000..f91c05b64c --- /dev/null +++ b/seaweed-block/.github/scripts/record-go-test.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +# Keep timestamped Go events, while preserving the existing human output and +# nonzero pipeline status. One caller at a time appends to a job's event file. +set -euo pipefail +out=$1 +shift +mkdir -p "$(dirname "$out")" +exec 3> >(tee -a "${out%.json}.stderr" >&2) +stderr_pid=$! +status=0 +go test -json "$@" 2>&3 | + tee -a "$out" | + "${PYTHON:-python3}" -u "$(dirname "$0")/go-test-output.py" || status=$? +exec 3>&- +wait "$stderr_pid" || true +exit "$status" diff --git a/seaweed-block/.github/workflows/test.yml b/seaweed-block/.github/workflows/test.yml index 6da3c87084..e18f7752bb 100644 --- a/seaweed-block/.github/workflows/test.yml +++ b/seaweed-block/.github/workflows/test.yml @@ -46,6 +46,7 @@ jobs: # Pure-Go build: no package in the default build needs cgo, and the # hosted runner should not depend on a C toolchain being present. CGO_ENABLED: "0" + CI_EVIDENCE_DIR: ${{ runner.temp }}/ci-${{ matrix.suite }}-${{ github.run_id }}-${{ github.run_attempt }} steps: - name: Checkout uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 @@ -55,6 +56,21 @@ jobs: # step can see which packages the PR touches. fetch-depth: 2 + - name: Start whole-job load evidence + # Begins after checkout, before toolchain setup/build/tests. No host + # installation or privileged reads. A job-sized lifetime also bounds + # the sampler if cancellation prevents the stop step. + continue-on-error: true + run: | + mkdir -p "$CI_EVIDENCE_DIR" + : >"$CI_EVIDENCE_DIR/go-test.json" + python3 -I .github/scripts/ci-load.py start "$CI_EVIDENCE_DIR/load.tsv" --duration ${{ matrix.suite == 'unit' && 2400 || 5400 }} + + - name: Self-test evidence capture + run: | + python3 -B .github/scripts/ci-load-test.py + bash .github/scripts/record-go-test-test.sh + - name: Docs-only pull request id: scope if: matrix.suite == 'process' && github.event_name == 'pull_request' @@ -115,8 +131,8 @@ jobs: bash .github/scripts/lab-tag-check-test.sh for tags in swblock_lab_bigvol swblock_v11_format swblock_lab_bigvol,swblock_v11_format; do go vet -tags "$tags" ./core/geometry/ ./core/frontend/durable/ ./internal/buildinfo/ ./core/storage/ - go test -count=1 -tags "$tags" -run 'Lab|Headroom|Revision' ./core/geometry/ ./core/frontend/durable/ ./internal/buildinfo/ - go test -count=1 -tags "$tags" -run 'TestV11FormatFollowsItsOwnTagAlone' ./core/storage/ + bash .github/scripts/record-go-test.sh "$CI_EVIDENCE_DIR/go-test.json" -count=1 -tags "$tags" -run 'Lab|Headroom|Revision' ./core/geometry/ ./core/frontend/durable/ ./internal/buildinfo/ + bash .github/scripts/record-go-test.sh "$CI_EVIDENCE_DIR/go-test.json" -count=1 -tags "$tags" -run 'TestV11FormatFollowsItsOwnTagAlone' ./core/storage/ done - name: Test default configuration @@ -143,7 +159,7 @@ jobs: fi # 20m per package: core/storage alone took 602 s on tp04 on main # (2026-11-22), past the old 10m, so any PR touching it failed. - go test -p=1 -short -count=1 -timeout 20m $pkgs + bash .github/scripts/record-go-test.sh "$CI_EVIDENCE_DIR/go-test.json" -p=1 -short -count=1 -timeout 20m $pkgs - name: Format v3 tagged tests if: matrix.suite == 'unit' @@ -155,7 +171,7 @@ jobs: run: | set -euo pipefail skip='^(TestDurableProviderV3_AttachesCompletedChunkBASE|TestDurableProviderV3_CompletedBASEDoesNotRestoreOlderHEAD|TestDurableProviderV3_DefersBASERetirementUntilLocalPresence|TestDurableProviderV3_FreshMarkerCrashKeepsCompletedBASE|TestDurableProviderV3_FreshMarkerCaptureCrashKeepsCompletedBASE)$' - go test -p=1 -count=1 -timeout 20m -tags swblock_format_v3_test -skip "$skip" \ + bash .github/scripts/record-go-test.sh "$CI_EVIDENCE_DIR/go-test.json" -p=1 -count=1 -timeout 20m -tags swblock_format_v3_test -skip "$skip" \ ./core/frontend/durable/ ./core/recovery/ ./core/replication/ ./core/transport/ - name: Self-test of the required-tests gate @@ -223,7 +239,7 @@ jobs: for spec in "./core/frontend/chunkstore/ ^TestIntegration" "./core/frontend/durable/ ^TestQD1LayoutSync"; do pkg=${spec%% *}; filter=${spec#* } log="$RUNNER_TEMP/integration-$(basename "$pkg").log" - go test -count=1 -v -timeout 20m -tags chunkstore_integration -run "$filter" "$pkg" 2>&1 | tee "$log" + bash .github/scripts/record-go-test.sh "$CI_EVIDENCE_DIR/go-test.json" -count=1 -v -timeout 20m -tags chunkstore_integration -run "$filter" "$pkg" 2>&1 | tee "$log" grep -q '^--- PASS: ' "$log" || { echo "no test of $pkg matched $filter"; exit 1; } done @@ -257,7 +273,7 @@ jobs: TEST_TIMEOUT: 15m # A failed test copies each daemon's whole log here (keepFullLog); # the step below keeps them as the run's artifact. - SWBLOCK_TEST_LOG_DIR: ${{ runner.temp }}/process-level-logs + SWBLOCK_TEST_LOG_DIR: ${{ env.CI_EVIDENCE_DIR }}/daemon-logs run: | set -euo pipefail # SHARDS parallel shards, balanced by their last measured times @@ -294,17 +310,29 @@ jobs: python3 -I .github/scripts/required-tests-check.py --status "$RUNNER_TEMP/process-level.status" \ "$names" "$RUNNER_TEMP"/process-level-*.json - - name: Keep the process-level logs and shard results - # A failure's evidence outlives the runner's temp directory: each - # failed test's full daemon logs and every shard's raw JSON and log. - if: failure() && matrix.suite == 'process' + - name: Stop load evidence and collect raw process events + if: always() + continue-on-error: true + env: + SUITE: ${{ matrix.suite }} + run: | + python3 -I .github/scripts/ci-load.py stop "$CI_EVIDENCE_DIR/load.tsv" || true + if [ "$SUITE" = process ]; then + mkdir -p "$CI_EVIDENCE_DIR/shards" + shopt -s nullglob + for file in "$RUNNER_TEMP"/process-level-*.json "$RUNNER_TEMP"/process-level-*.log "$RUNNER_TEMP"/process-level*.status; do + cp "$file" "$CI_EVIDENCE_DIR/shards/" + done + for file in "$CI_EVIDENCE_DIR"/shards/*.json; do cat "$file" >>"$CI_EVIDENCE_DIR/go-test.json"; done + fi + + - name: Keep failed-job tests, load, daemon logs and shard results + # Both suites retain timed events and whole-job load. Process evidence + # also retains the original shard receipts and full daemon logs. + if: failure() uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: - name: process-level-${{ github.run_id }}-${{ github.run_attempt }} - path: | - ${{ runner.temp }}/process-level-logs - ${{ runner.temp }}/process-level-*.json - ${{ runner.temp }}/process-level-*.log - ${{ runner.temp }}/process-level-*.status + name: ci-${{ matrix.suite }}-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ env.CI_EVIDENCE_DIR }} retention-days: 14 if-no-files-found: warn From 458f64dda9eb4a02282dc99c010f05c080c3ade2 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 20:35:43 -0800 Subject: [PATCH 4/9] ci: resolve evidence directory only after runner allocation --- seaweed-block/.github/workflows/test.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/seaweed-block/.github/workflows/test.yml b/seaweed-block/.github/workflows/test.yml index e18f7752bb..5e1591c52a 100644 --- a/seaweed-block/.github/workflows/test.yml +++ b/seaweed-block/.github/workflows/test.yml @@ -46,7 +46,6 @@ jobs: # Pure-Go build: no package in the default build needs cgo, and the # hosted runner should not depend on a C toolchain being present. CGO_ENABLED: "0" - CI_EVIDENCE_DIR: ${{ runner.temp }}/ci-${{ matrix.suite }}-${{ github.run_id }}-${{ github.run_attempt }} steps: - name: Checkout uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 @@ -61,7 +60,10 @@ jobs: # installation or privileged reads. A job-sized lifetime also bounds # the sampler if cancellation prevents the stop step. continue-on-error: true + env: + CI_EVIDENCE_DIR: ${{ runner.temp }}/ci-${{ matrix.suite }}-${{ github.run_id }}-${{ github.run_attempt }} run: | + echo "CI_EVIDENCE_DIR=$CI_EVIDENCE_DIR" >>"$GITHUB_ENV" mkdir -p "$CI_EVIDENCE_DIR" : >"$CI_EVIDENCE_DIR/go-test.json" python3 -I .github/scripts/ci-load.py start "$CI_EVIDENCE_DIR/load.tsv" --duration ${{ matrix.suite == 'unit' && 2400 || 5400 }} @@ -316,6 +318,7 @@ jobs: env: SUITE: ${{ matrix.suite }} run: | + if [ -z "${CI_EVIDENCE_DIR:-}" ]; then exit 0; fi python3 -I .github/scripts/ci-load.py stop "$CI_EVIDENCE_DIR/load.tsv" || true if [ "$SUITE" = process ]; then mkdir -p "$CI_EVIDENCE_DIR/shards" From 73c99f5a05c7e19a68057f393f3d6cc22ba473d1 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 20:48:22 -0800 Subject: [PATCH 5/9] test: prove owned kernel controller teardown after retry procedure --- ...ure_retry_delay_kernel_integration_test.go | 50 +++++-- .../retry_controller_cleanup_test.go | 130 ++++++++++++++++++ .../frontend/nvme/read_ready_retry_test.go | 95 +++++++------ 3 files changed, 221 insertions(+), 54 deletions(-) create mode 100644 seaweed-block/cmd/blockvolume/retry_controller_cleanup_test.go diff --git a/seaweed-block/cmd/blockvolume/procedure_retry_delay_kernel_integration_test.go b/seaweed-block/cmd/blockvolume/procedure_retry_delay_kernel_integration_test.go index 61de82a4d3..4a9900e396 100644 --- a/seaweed-block/cmd/blockvolume/procedure_retry_delay_kernel_integration_test.go +++ b/seaweed-block/cmd/blockvolume/procedure_retry_delay_kernel_integration_test.go @@ -6,6 +6,7 @@ import ( "bytes" "context" "fmt" + "io" "net" "os" "os/exec" @@ -43,27 +44,46 @@ func TestProcedureKernelReadinessRetryDelay(t *testing.T) { if err != nil { t.Fatal(err) } - cleanup := func() { - controllers, _ := filepath.Glob("/sys/class/nvme/nvme*") - for _, controller := range controllers { - got, _ := os.ReadFile(filepath.Join(controller, "subsysnqn")) - if strings.TrimSpace(string(got)) == nqn { - if err := os.WriteFile(filepath.Join(controller, "delete_controller"), []byte("1"), 0200); err != nil { - t.Errorf("disconnect own controller: %v", err) - } - } - } - } - t.Cleanup(cleanup) fabric, err := os.OpenFile("/dev/nvme-fabrics", os.O_RDWR, 0) if err != nil { t.Fatal(err) } + var controller string + connected := false + // Keep the fabrics fd (and its kernel controller reference) until teardown. + t.Cleanup(func() { + defer func() { + if err := fabric.Close(); err != nil { + t.Errorf("close fabrics handle: %v", err) + } + }() + if controller == "" { + if connected { + t.Error("connected controller identity unresolved; cleanup not proven") + } + return + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if err := disconnectRetryController(ctx, controller, nqn); err != nil { + t.Errorf("owned controller teardown unresolved: %v", err) + } + }) _, err = fabric.WriteString(fmt.Sprintf("transport=tcp,traddr=%s,trsvcid=%s,nqn=%s,hostnqn=nqn.2026-12.io.seaweedfs:host-%s,hostid=%s,nr_io_queues=1", host, port, nqn, token, token)) - closeErr := fabric.Close() - if err != nil || closeErr != nil { - t.Fatalf("kernel connect: write=%v close=%v", err, closeErr) + if err != nil { + t.Fatalf("kernel connect: %v", err) } + connected = true + answer, err := io.ReadAll(io.LimitReader(fabric, 4096)) + if err != nil { + t.Fatalf("read acquired controller identity: %v", err) + } + instance, err := retryControllerInstance(string(answer)) + if err != nil { + t.Fatal(err) + } + controller = filepath.Join("/sys/class/nvme", fmt.Sprintf("nvme%d", instance)) + t.Logf("acquired own controller %s answer=%q", controller, answer) var device string for end := time.Now().Add(20 * time.Second); time.Now().Before(end); time.Sleep(50 * time.Millisecond) { blocks, _ := filepath.Glob("/sys/block/nvme*n*") diff --git a/seaweed-block/cmd/blockvolume/retry_controller_cleanup_test.go b/seaweed-block/cmd/blockvolume/retry_controller_cleanup_test.go new file mode 100644 index 0000000000..12f765957f --- /dev/null +++ b/seaweed-block/cmd/blockvolume/retry_controller_cleanup_test.go @@ -0,0 +1,130 @@ +package main_test + +import ( + "context" + "fmt" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +func retryControllerInstance(answer string) (int, error) { + var instance, cntlid int + if n, err := fmt.Sscanf(strings.TrimSpace(answer), "instance=%d,cntlid=%d", &instance, &cntlid); err != nil || n != 2 || instance < 0 || cntlid < 0 { + return 0, fmt.Errorf("invalid acquired controller identity %q", answer) + } + return instance, nil +} + +// path is the acquired fabrics instance, never a discovered/global controller. +// The caller retains the fabrics handle until this bounded check completes. +func disconnectRetryController(ctx context.Context, path, nqn string) error { + original, err := os.Stat(path) + if os.IsNotExist(err) { + return nil + } + if err != nil { + return fmt.Errorf("stat acquired controller: %w", err) + } + identity, err := os.ReadFile(filepath.Join(path, "subsysnqn")) + if err != nil { + return fmt.Errorf("read owned identity: %w", err) + } + if strings.TrimSpace(string(identity)) != nqn { + return fmt.Errorf("acquired controller identity changed: %q", identity) + } + if err := os.WriteFile(filepath.Join(path, "delete_controller"), []byte("1"), 0200); err != nil { + return fmt.Errorf("request owned deletion: %w", err) + } + for { + current, err := os.Stat(path) + if os.IsNotExist(err) { + return nil + } + if err != nil { + return fmt.Errorf("verify owned deletion: %w", err) + } + if !os.SameFile(original, current) { + return fmt.Errorf("controller path replaced while awaiting deletion") + } + select { + case <-ctx.Done(): + return fmt.Errorf("owned controller still present: %w", ctx.Err()) + case <-time.After(10 * time.Millisecond): + } + } +} + +func TestRetryControllerCleanupRefusesUnknownIdentity(t *testing.T) { + path := t.TempDir() + marker := filepath.Join(path, "delete_controller") + if err := os.WriteFile(marker, []byte("untouched"), 0600); err != nil { + t.Fatal(err) + } + for _, identity := range []string{"", "another-controller"} { + if identity != "" { + if err := os.WriteFile(filepath.Join(path, "subsysnqn"), []byte(identity), 0600); err != nil { + t.Fatal(err) + } + } + if err := disconnectRetryController(context.Background(), path, "own"); err == nil { + t.Fatal("unknown identity deletion accepted") + } + if got, err := os.ReadFile(marker); err != nil || string(got) != "untouched" { + t.Fatalf("unproved controller changed: %q %v", got, err) + } + } +} + +func TestRetryControllerCleanupAwaitsOwnedRemoval(t *testing.T) { + for _, remove := range []bool{false, true} { + t.Run(fmt.Sprint(remove), func(t *testing.T) { + path := filepath.Join(t.TempDir(), "controller") + if err := os.Mkdir(path, 0700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(path, "subsysnqn"), []byte("own"), 0600); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + joined := make(chan struct{}) + if remove { + go func() { + defer close(joined) + for { + if _, err := os.Stat(filepath.Join(path, "delete_controller")); err == nil { + break + } + select { + case <-ctx.Done(): + return + case <-time.After(time.Millisecond): + } + } + _ = os.RemoveAll(path) + }() + } else { + close(joined) + } + err := disconnectRetryController(ctx, path, "own") + <-joined + if (err == nil) != remove { + t.Fatalf("remove=%t cleanup=%v", remove, err) + } + }) + } +} + +func TestRetryControllerAcquiredIdentity(t *testing.T) { + if got, err := retryControllerInstance("instance=12,cntlid=3\n"); err != nil || got != 12 { + t.Fatalf("identity %d %v", got, err) + } + for _, bad := range []string{"", "instance=-1,cntlid=-1", "instance=3", "garbage"} { + if _, err := retryControllerInstance(bad); err == nil { + t.Fatalf("accepted %q", bad) + } + } +} 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 8e65719bd8..5994d3d176 100644 --- a/seaweed-block/core/frontend/nvme/read_ready_retry_test.go +++ b/seaweed-block/core/frontend/nvme/read_ready_retry_test.go @@ -80,14 +80,24 @@ type retryDelayBackend struct { err error } -func (b *retryDelayBackend) Read(context.Context, int64, []byte) (int, error) { return 0, b.err } -func (b *retryDelayBackend) Write(context.Context, int64, []byte) (int, error) { return 0, b.err } -func (b *retryDelayBackend) Sync(context.Context) error { return b.err } +func (b *retryDelayBackend) Read(ctx context.Context, offset int64, data []byte) (int, error) { + if b.err == nil { + return b.Backend.Read(ctx, offset, data) + } + return 0, b.err +} +func (b *retryDelayBackend) Write(ctx context.Context, offset int64, data []byte) (int, error) { + if b.err == nil { + return b.Backend.Write(ctx, offset, data) + } + return 0, b.err +} +func (b *retryDelayBackend) Sync(context.Context) error { return b.err } func TestSessionRetryDelayOnEveryRetryableIO(t *testing.T) { for _, opcode := range []uint8{ioRead, ioWrite, ioFlush} { for _, enable := range []bool{false, true} { - for _, cause := range []error{frontend.ErrNotReady, frontend.ErrBackendBusy, frontend.ErrStalePrimary, frontend.ErrBackendClosed, errors.New("disk fault")} { + for _, cause := range []error{nil, frontend.ErrNotReady, frontend.ErrBackendBusy, frontend.ErrStalePrimary, frontend.ErrBackendClosed, errors.New("disk fault")} { t.Run(fmt.Sprintf("opcode=%d/acre=%t/%v", opcode, enable, cause), func(t *testing.T) { b := &retryDelayBackend{Backend: testback.NewRecordingBackend(frontend.Identity{VolumeID: "v1"}), err: cause} s := &Session{handler: NewIOHandler(HandlerConfig{Backend: b}), ctrl: &adminController{}, respCh: make(chan *response, 1), done: make(chan struct{})} @@ -105,6 +115,9 @@ func TestSessionRetryDelayOnEveryRetryableIO(t *testing.T) { req.capsule.NSID = 1 s.dispatchIO(context.Background(), req) status := (<-s.respCh).resp.Status + if cause == nil && status != 0 { + t.Fatalf("successful IO has status=%#x", status) + } crd := (status >> 12) & 3 transient := cause == frontend.ErrNotReady || cause == frontend.ErrBackendBusy want := uint16(0) @@ -124,41 +137,45 @@ func TestSessionRetryDelayOnEveryRetryableIO(t *testing.T) { } func TestHostBehaviorRejectsUnsupportedPayloadWithoutChangingACRE(t *testing.T) { - s := &Session{ctrl: &adminController{}, respCh: make(chan *response, 1), done: make(chan struct{})} - for _, tc := range []struct { - name string - size int - offset int - value byte - d10, d11 uint32 - }{ - {"empty", 0, 0, 0, 0, 0}, {"short", 511, 0, 0, 0, 0}, {"long", 513, 0, 0, 0, 0}, - {"bad-acre", 512, 0, 2, 0, 0}, {"etdas", 512, 1, 1, 0, 0}, {"lbafee", 512, 2, 1, 0, 0}, {"reserved", 512, 511, 1, 0, 0}, - {"save", 512, 0, 1, 1 << 31, 0}, {"cdw11", 512, 0, 1, 0, 1}, - } { - t.Run(tc.name, func(t *testing.T) { - enable := &Request{payload: make([]byte, 512)} - enable.payload[0] = 1 - enable.capsule.D10 = 0x16 - s.handleSetFeatures(enable) - if (<-s.respCh).resp.Status != 0 { - t.Fatal("enable failed") - } - req := &Request{payload: make([]byte, tc.size)} - req.capsule.D10 = 0x16 | tc.d10 - req.capsule.D11 = tc.d11 - if tc.size > tc.offset { - req.payload[tc.offset] = tc.value - } - s.handleSetFeatures(req) - if got := (<-s.respCh).resp.Status; got != MakeStatusField(SCTGeneric, SCInvalidField, true) { - t.Fatalf("invalid payload accepted: %#x", got) - } - get := &Request{} - get.capsule.D10 = 0x16 - s.handleGetFeatures(get) - if got := (<-s.respCh).c2hData; len(got) != 512 || got[0] != 1 { - t.Fatalf("refusal changed ACRE=%v", got) + for _, initial := range []byte{0, 1} { + t.Run(fmt.Sprintf("initial=%d", initial), func(t *testing.T) { + s := &Session{ctrl: &adminController{}, respCh: make(chan *response, 1), done: make(chan struct{})} + for _, tc := range []struct { + name string + size int + offset int + value byte + d10, d11 uint32 + }{ + {"empty", 0, 0, 0, 0, 0}, {"short", 511, 0, 0, 0, 0}, {"long", 513, 0, 0, 0, 0}, + {"bad-acre", 512, 0, 2, 0, 0}, {"etdas", 512, 1, 1, 0, 0}, {"lbafee", 512, 2, 1, 0, 0}, {"reserved", 512, 511, 1, 0, 0}, + {"save", 512, 0, 1, 1 << 31, 0}, {"cdw11", 512, 0, 1, 0, 1}, + } { + t.Run(tc.name, func(t *testing.T) { + enable := &Request{payload: make([]byte, 512)} + enable.payload[0] = initial + enable.capsule.D10 = 0x16 + s.handleSetFeatures(enable) + if (<-s.respCh).resp.Status != 0 { + t.Fatal("enable failed") + } + req := &Request{payload: make([]byte, tc.size)} + req.capsule.D10 = 0x16 | tc.d10 + req.capsule.D11 = tc.d11 + if tc.size > tc.offset { + req.payload[tc.offset] = tc.value + } + s.handleSetFeatures(req) + if got := (<-s.respCh).resp.Status; got != MakeStatusField(SCTGeneric, SCInvalidField, true) { + t.Fatalf("invalid payload accepted: %#x", got) + } + get := &Request{} + get.capsule.D10 = 0x16 + s.handleGetFeatures(get) + if got := (<-s.respCh).c2hData; len(got) != 512 || got[0] != initial { + t.Fatalf("refusal changed ACRE=%v", got) + } + }) } }) } From 92658eccdb8f838f32bdc4b1a0e169b2e34cf34e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 20:46:10 -0800 Subject: [PATCH 6/9] ci: keep recorder errors separate from the Go test verdict --- seaweed-block/.github/scripts/ci-evidence.md | 4 +- .../.github/scripts/go-test-output.py | 59 +++++++++++++++++-- .../.github/scripts/record-go-test-test.sh | 20 +++++++ .../.github/scripts/record-go-test.sh | 14 +++-- 4 files changed, 86 insertions(+), 11 deletions(-) diff --git a/seaweed-block/.github/scripts/ci-evidence.md b/seaweed-block/.github/scripts/ci-evidence.md index 36a1b0336b..ab9f09edd9 100644 --- a/seaweed-block/.github/scripts/ci-evidence.md +++ b/seaweed-block/.github/scripts/ci-evidence.md @@ -4,7 +4,9 @@ Both test suites keep one `ci---` artifact on failure for 14 days. `go-test.json` contains Go's timestamped events and per-test `Elapsed` values; process shards also keep their original JSON, logs and exit receipts. `go-test.stderr` keeps build/tool errors outside Go's JSON event stream. The -console still shows the original test output. Test arguments, scope, timeouts, +console still shows the original test output. Recording/rendering errors are +best effort: they report the missing evidence and keep draining Go, whose own +exit code alone decides the wrapper's result. Test arguments, scope, timeouts, exit-code handling and the required-tests gate are unchanged. `load.tsv` begins immediately after checkout and samples once per second until diff --git a/seaweed-block/.github/scripts/go-test-output.py b/seaweed-block/.github/scripts/go-test-output.py index 888af12ab0..264e316b14 100644 --- a/seaweed-block/.github/scripts/go-test-output.py +++ b/seaweed-block/.github/scripts/go-test-output.py @@ -1,9 +1,58 @@ -"""Render go test -json Output events without changing the test verdict.""" +"""Drain a Go stream even when recording/rendering fails; never judge tests.""" import json +import os import sys +sys.stdin.reconfigure(encoding='utf-8', errors='replace') + + +def warn(error): + try: + print('test evidence unavailable: '+str(error), file=sys.stderr) + except OSError: + pass + + +archive = None +try: + archive = open(sys.argv[1], 'a', encoding='utf-8', buffering=1) +except OSError as error: + warn(error) +raw = len(sys.argv) > 2 and sys.argv[2] == '--raw' +console = True for line in sys.stdin: - event = json.loads(line) - if 'Output' in event: - sys.stdout.write(event['Output']) - sys.stdout.flush() + if archive is not None: + try: + archive.write(line) + except OSError as error: + warn(error) + try: + archive.close() + except OSError: + pass + archive = None + output = line + if not raw: + try: + output = json.loads(line).get('Output', '') + except (ValueError, AttributeError) as error: + # Keep and display unexpected text, but keep draining the producer. + warn(error) + if console: + try: + sys.stdout.write(output) + sys.stdout.flush() + except OSError: + console = False + # Avoid an interpreter-exit BrokenPipe flush; the stream still + # drains Go to EOF so a dead console cannot send SIGPIPE upstream. + try: + with open(os.devnull, 'w') as sink: + os.dup2(sink.fileno(), sys.stdout.fileno()) + except OSError: + pass +if archive is not None: + try: + archive.close() + except OSError as error: + warn(error) diff --git a/seaweed-block/.github/scripts/record-go-test-test.sh b/seaweed-block/.github/scripts/record-go-test-test.sh index 26d0955d27..43fd831f0e 100644 --- a/seaweed-block/.github/scripts/record-go-test-test.sh +++ b/seaweed-block/.github/scripts/record-go-test-test.sh @@ -6,10 +6,14 @@ trap 'rm -rf "$root"' EXIT mkdir -p "$root/bin" cat >"$root/bin/go" <<'EOF' #!/usr/bin/env bash +set -e test "$1" = test && test "$2" = -json || exit 99 printf '%s\n' '{"Time":"2026-12-02T00:00:01Z","Action":"run","Test":"TestX"}' printf '%s\n' '{"Time":"2026-12-02T00:00:02Z","Action":"output","Test":"TestX","Output":"fixture output\n"}' printf '%s\n' '{"Time":"2026-12-02T00:00:02Z","Action":"fail","Test":"TestX","Elapsed":1}' +if [ "${FAKE_GO_LARGE:-0}" = 1 ]; then + for ((i=0; i<10000; i++)); do printf '%s\n' '{"Action":"output","Output":"draining after recorder failure\n"}'; done +fi echo 'fixture stderr' >&2 exit "${FAKE_GO_EXIT:-0}" EOF @@ -23,4 +27,20 @@ grep -q 'fixture stderr' "$root/go-test.stderr" "${PYTHON:-python3}" -c 'import json,sys; events=[json.loads(s) for s in open(sys.argv[1])]; assert len(events)==3; assert events[-1]["Elapsed"]==1; assert events[-1]["Time"]=="2026-12-02T00:00:02Z"' "$root/go-test.json" FAKE_GO_EXIT=0 bash "$here/record-go-test.sh" "$root/go-test.json" -run TestX >"$root/console" 2>"$root/stderr" test "$(wc -l <"$root/go-test.json")" = 6 +# The evidence destination cannot be opened (a file where its parent belongs). +# The original Go success/failure must still be the command's answer. +echo occupied >"$root/not-a-directory" +code=0 +FAKE_GO_EXIT=0 bash "$here/record-go-test.sh" "$root/not-a-directory/go-test.json" >"$root/console" 2>"$root/stderr" || code=$? +test "$code" = 0 +grep -q 'fixture output' "$root/console" +code=0 +FAKE_GO_EXIT=7 bash "$here/record-go-test.sh" "$root/not-a-directory/go-test.json" >"$root/console" 2>"$root/stderr" || code=$? +test "$code" = 7 +if [ "$(uname -s)" = Linux ] && [ -c /dev/full ]; then + ln -s /dev/full "$root/full.json" + FAKE_GO_LARGE=1 FAKE_GO_EXIT=0 bash "$here/record-go-test.sh" "$root/full.json" >"$root/console" 2>"$root/stderr" + grep -q 'draining after recorder failure' "$root/console" + grep -q 'test evidence unavailable' "$root/stderr" +fi echo 'record-go-test: output, timestamp, elapsed, append and exit-status controls PASS' diff --git a/seaweed-block/.github/scripts/record-go-test.sh b/seaweed-block/.github/scripts/record-go-test.sh index f91c05b64c..caebc315d1 100644 --- a/seaweed-block/.github/scripts/record-go-test.sh +++ b/seaweed-block/.github/scripts/record-go-test.sh @@ -4,13 +4,17 @@ set -euo pipefail out=$1 shift -mkdir -p "$(dirname "$out")" -exec 3> >(tee -a "${out%.json}.stderr" >&2) +mkdir -p "$(dirname "$out")" || true +capture="$(dirname "$0")/go-test-output.py" +exec 3> >("${PYTHON:-python3}" -u "$capture" "${out%.json}.stderr" --raw >&2) stderr_pid=$! -status=0 +# Only Go judges the test. The readers keep draining after evidence IO errors, +# so a disk-full recorder cannot turn Go's PASS into a pipeline/SIGPIPE failure. +set +e go test -json "$@" 2>&3 | - tee -a "$out" | - "${PYTHON:-python3}" -u "$(dirname "$0")/go-test-output.py" || status=$? + "${PYTHON:-python3}" -u "$capture" "$out" +status=${PIPESTATUS[0]} +set -e exec 3>&- wait "$stderr_pid" || true exit "$status" From f459e5c20865474bcec861264ce458394e22845a Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 20:53:22 -0800 Subject: [PATCH 7/9] test: require an existing kernel namespace block device --- ...ocedure_retry_delay_kernel_integration_test.go | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/procedure_retry_delay_kernel_integration_test.go b/seaweed-block/cmd/blockvolume/procedure_retry_delay_kernel_integration_test.go index 4a9900e396..bf9fda3f1c 100644 --- a/seaweed-block/cmd/blockvolume/procedure_retry_delay_kernel_integration_test.go +++ b/seaweed-block/cmd/blockvolume/procedure_retry_delay_kernel_integration_test.go @@ -90,7 +90,18 @@ func TestProcedureKernelReadinessRetryDelay(t *testing.T) { for _, block := range blocks { got, _ := os.ReadFile(filepath.Join(block, "device", "subsysnqn")) if strings.TrimSpace(string(got)) == nqn { - device = "/dev/" + filepath.Base(block) + candidate := "/dev/" + filepath.Base(block) + info, statErr := os.Stat(candidate) + if os.IsNotExist(statErr) { + continue + } // hidden multipath component + if statErr != nil { + t.Fatalf("stat own namespace %s: %v", candidate, statErr) + } + if info.Mode()&os.ModeDevice == 0 || info.Mode()&os.ModeCharDevice != 0 { + t.Fatalf("own namespace %s is not a block device: %s", candidate, info.Mode()) + } + device = candidate break } } @@ -109,7 +120,7 @@ func TestProcedureKernelReadinessRetryDelay(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) defer cancel() started := time.Now() - out, err := exec.CommandContext(ctx, "dd", "if="+source, "of="+device, "bs=4096", "count=1", "oflag=direct", "conv=fdatasync", "status=none").CombinedOutput() + out, err := exec.CommandContext(ctx, "dd", "if="+source, "of="+device, "bs=4096", "count=1", "oflag=direct", "conv=nocreat,fdatasync", "status=none").CombinedOutput() elapsed := time.Since(started) t.Logf("kernel default retries=5 device=%s write_elapsed=%s err=%v output=%s", device, elapsed, err, out) if err != nil { From 69cd5c08bb675a8d3433bb83581edfe295b33352 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 23:50:48 -0800 Subject: [PATCH 8/9] ci: a dead recorder hands its stream to cat; a sampler that will not stop is recorded If the Go event recorder itself dies or cannot start, the rest of its stream (stdout, and the stderr side) now drains through cat, so go test never writes into a closed pipe and its own exit status stays the answer. Twins with a recorder that exits after 100 bytes and a large stream: exit 0 stays 0, exit 7 stays 7. Stopping the load sampler now waits on its pidfd (readable on exit) for 2 s; a sampler still alive leaves load.incomplete beside its rows and a stderr note instead of returning as if it had flushed. The stop test checks the process is gone (no file-stability guess) and a SIGTERM- ignoring stand-in yields the note within 5 s. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/.github/scripts/ci-load-test.py | 31 +++++++++++++++++-- seaweed-block/.github/scripts/ci-load.py | 10 ++++-- .../.github/scripts/record-go-test-test.sh | 17 +++++++++- .../.github/scripts/record-go-test.sh | 6 ++-- 4 files changed, 55 insertions(+), 9 deletions(-) diff --git a/seaweed-block/.github/scripts/ci-load-test.py b/seaweed-block/.github/scripts/ci-load-test.py index d7fe06c350..b09cd6903f 100644 --- a/seaweed-block/.github/scripts/ci-load-test.py +++ b/seaweed-block/.github/scripts/ci-load-test.py @@ -37,9 +37,34 @@ class LoadTest(unittest.TestCase): self.assertTrue(fields[0].endswith('+00:00')) for field in fields[1:]: json.loads(field) - before = output.read_bytes() - time.sleep(0.1) - self.assertEqual(output.read_bytes(), before) + # The sampler exited: its pid is gone, and no incomplete note. + pid = json.loads(output.with_suffix('.pid.json').read_text())['pid'] + self.assertFalse(pathlib.Path(f'/proc/{pid}').exists() and + pathlib.Path(f'/proc/{pid}/stat').read_text().split(')')[1].split()[0] != 'Z') + self.assertFalse(output.with_suffix('.incomplete').exists()) + + @unittest.skipUnless(sys.platform == 'linux', 'real /proc lifecycle is Linux-only') + def test_stop_records_a_sampler_that_does_not_exit(self): + with tempfile.TemporaryDirectory() as name: + output = pathlib.Path(name)/'load.tsv' + ready = pathlib.Path(name)/'ready' + stubborn = subprocess.Popen([sys.executable, '-c', + 'import pathlib,signal,sys,time; signal.signal(signal.SIGTERM, signal.SIG_IGN); ' + 'pathlib.Path(sys.argv[1]).touch(); time.sleep(30)', str(ready)]) + try: + while not ready.exists(): + time.sleep(0.01) + output.with_suffix('.pid.json').write_text(json.dumps(dict(pid=stubborn.pid, start=load.identity(stubborn.pid)))) + began = time.monotonic() + done = subprocess.run([sys.executable, '-I', str(pathlib.Path(__file__).with_name('ci-load.py')), 'stop', str(output)], + capture_output=True, text=True, timeout=10) + self.assertEqual(done.returncode, 0) + self.assertLess(time.monotonic()-began, 5) + self.assertIn('did not exit', output.with_suffix('.incomplete').read_text()) + self.assertIn('load evidence incomplete', done.stderr) + finally: + stubborn.kill() + stubborn.wait() def test_cpu_and_disk_interval_not_since_boot(self): # CPU: 100 ticks, 10 iowait, 5 stolen. guest ticks are already in user. diff --git a/seaweed-block/.github/scripts/ci-load.py b/seaweed-block/.github/scripts/ci-load.py index 54a4f5543f..c0fcd56407 100644 --- a/seaweed-block/.github/scripts/ci-load.py +++ b/seaweed-block/.github/scripts/ci-load.py @@ -12,6 +12,7 @@ import json import os import pathlib import re +import select import signal import subprocess import sys @@ -156,9 +157,12 @@ def main(): signal.pidfd_send_signal(handle, signal.SIGTERM) # Flush the last row before the uploader reads the file. Never # signal a reused PID and never wait indefinitely for evidence. - until = time.monotonic()+2 - while time.monotonic() < until and identity(owner['pid']) == owner['start']: - time.sleep(0.05) + # The pidfd turns readable when the sampler exits; one still + # alive after 2 s leaves load.incomplete beside its rows. + if not select.select([handle], [], [], 2)[0]: + note = args.output.with_suffix('.incomplete') + note.write_text('the sampler did not exit within 2 s of SIGTERM; its last rows may be missing\n') + print('load evidence incomplete: '+str(note), file=sys.stderr) except ProcessLookupError: pass except FileNotFoundError: diff --git a/seaweed-block/.github/scripts/record-go-test-test.sh b/seaweed-block/.github/scripts/record-go-test-test.sh index 43fd831f0e..b98de88e99 100644 --- a/seaweed-block/.github/scripts/record-go-test-test.sh +++ b/seaweed-block/.github/scripts/record-go-test-test.sh @@ -43,4 +43,19 @@ if [ "$(uname -s)" = Linux ] && [ -c /dev/full ]; then grep -q 'draining after recorder failure' "$root/console" grep -q 'test evidence unavailable' "$root/stderr" fi -echo 'record-go-test: output, timestamp, elapsed, append and exit-status controls PASS' +# The recorder itself dies after its first bytes (a crash, an OOM kill): the +# rest of a large stream still drains and Go's own status is the answer. +cat >"$root/bin/dead-recorder" <<'EOF2' +#!/usr/bin/env bash +head -c 100 >/dev/null +exit 3 +EOF2 +chmod +x "$root/bin/dead-recorder" +for want in 0 7; do + code=0 + PYTHON="$root/bin/dead-recorder" FAKE_GO_LARGE=1 FAKE_GO_EXIT=$want bash "$here/record-go-test.sh" "$root/dead.json" >"$root/console" 2>"$root/stderr" || code=$? + test "$code" = "$want" + grep -q 'draining after recorder failure' "$root/console" + grep -q 'the recorder exited' "$root/stderr" +done +echo 'record-go-test: output, timestamp, elapsed, append, dead-recorder and exit-status controls PASS' diff --git a/seaweed-block/.github/scripts/record-go-test.sh b/seaweed-block/.github/scripts/record-go-test.sh index caebc315d1..d227a8bb14 100644 --- a/seaweed-block/.github/scripts/record-go-test.sh +++ b/seaweed-block/.github/scripts/record-go-test.sh @@ -6,13 +6,15 @@ out=$1 shift mkdir -p "$(dirname "$out")" || true capture="$(dirname "$0")/go-test-output.py" -exec 3> >("${PYTHON:-python3}" -u "$capture" "${out%.json}.stderr" --raw >&2) +# A recorder that dies (or cannot start) hands the rest of its stream to cat, +# so Go never writes into a closed pipe. +exec 3> >({ "${PYTHON:-python3}" -u "$capture" "${out%.json}.stderr" --raw || cat; } >&2) stderr_pid=$! # Only Go judges the test. The readers keep draining after evidence IO errors, # so a disk-full recorder cannot turn Go's PASS into a pipeline/SIGPIPE failure. set +e go test -json "$@" 2>&3 | - "${PYTHON:-python3}" -u "$capture" "$out" + { "${PYTHON:-python3}" -u "$capture" "$out" || { echo "test evidence unavailable: the recorder exited" >&2; cat; }; } status=${PIPESTATUS[0]} set -e exec 3>&- From 7cb62f3b71b351510030df916ec417ceaf08f48b Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 2 Dec 2026 00:42:45 -0800 Subject: [PATCH 9/9] ci: the stderr fallback and a missing recorder have their own controls The dead-recorder twins wrote a large stdout but one short stderr line, so removing only the stderr fallback still passed. A fake Go that writes 10,000 stderr lines now runs with a recorder that dies after 100 bytes, and with no recorder at all (no such interpreter); each keeps Go's own exit 0 and 7, and dropping the stderr fallback turns the suite red. The sampler stop test's wait for its stand-in is bounded (10 s) and fails at once if the stand-in exits before it is ready. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/.github/scripts/ci-load-test.py | 3 +++ .../.github/scripts/record-go-test-test.sh | 14 ++++++++++++++ 2 files changed, 17 insertions(+) diff --git a/seaweed-block/.github/scripts/ci-load-test.py b/seaweed-block/.github/scripts/ci-load-test.py index b09cd6903f..90ff55d3af 100644 --- a/seaweed-block/.github/scripts/ci-load-test.py +++ b/seaweed-block/.github/scripts/ci-load-test.py @@ -52,7 +52,10 @@ class LoadTest(unittest.TestCase): 'import pathlib,signal,sys,time; signal.signal(signal.SIGTERM, signal.SIG_IGN); ' 'pathlib.Path(sys.argv[1]).touch(); time.sleep(30)', str(ready)]) try: + deadline = time.monotonic()+10 while not ready.exists(): + self.assertIsNone(stubborn.poll(), 'the stand-in exited before it was ready') + self.assertLess(time.monotonic(), deadline, 'the stand-in never became ready') time.sleep(0.01) output.with_suffix('.pid.json').write_text(json.dumps(dict(pid=stubborn.pid, start=load.identity(stubborn.pid)))) began = time.monotonic() diff --git a/seaweed-block/.github/scripts/record-go-test-test.sh b/seaweed-block/.github/scripts/record-go-test-test.sh index b98de88e99..54bd092d34 100644 --- a/seaweed-block/.github/scripts/record-go-test-test.sh +++ b/seaweed-block/.github/scripts/record-go-test-test.sh @@ -15,6 +15,9 @@ if [ "${FAKE_GO_LARGE:-0}" = 1 ]; then for ((i=0; i<10000; i++)); do printf '%s\n' '{"Action":"output","Output":"draining after recorder failure\n"}'; done fi echo 'fixture stderr' >&2 +if [ "${FAKE_GO_LARGE_STDERR:-0}" = 1 ]; then + for ((i=0; i<10000; i++)); do echo 'stderr draining after recorder failure' >&2; done +fi exit "${FAKE_GO_EXIT:-0}" EOF chmod +x "$root/bin/go" @@ -57,5 +60,16 @@ for want in 0 7; do test "$code" = "$want" grep -q 'draining after recorder failure' "$root/console" grep -q 'the recorder exited' "$root/stderr" + # The stderr reader dies with a large stderr still to come. + code=0 + PYTHON="$root/bin/dead-recorder" FAKE_GO_LARGE_STDERR=1 FAKE_GO_EXIT=$want bash "$here/record-go-test.sh" "$root/dead.json" >"$root/console" 2>"$root/stderr" || code=$? + test "$code" = "$want" + grep -q 'stderr draining after recorder failure' "$root/stderr" + # The recorder cannot start at all (no such interpreter). + code=0 + PYTHON="$root/bin/no-such-python" FAKE_GO_LARGE=1 FAKE_GO_LARGE_STDERR=1 FAKE_GO_EXIT=$want bash "$here/record-go-test.sh" "$root/dead.json" >"$root/console" 2>"$root/stderr" || code=$? + test "$code" = "$want" + grep -q 'draining after recorder failure' "$root/console" + grep -q 'stderr draining after recorder failure' "$root/stderr" done echo 'record-go-test: output, timestamp, elapsed, append, dead-recorder and exit-status controls PASS'