From 9fb03057f36d2c5b771ab12ad4ee658cf0cecd06 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 1 Aug 2026 03:44:12 -0700 Subject: [PATCH] test: add phase174 NVMe fixed-work attribution --- .../frontend/nvme/phase174_fixed_work_test.go | 504 ++++++++++++++++++ .../phase174-d2-nvme-tcp-fixed-work-qa.md | 79 +++ .../run-phase174-nvme-tcp-fixed-work-gate.sh | 261 +++++++++ 3 files changed, 844 insertions(+) create mode 100644 seaweed-block/core/frontend/nvme/phase174_fixed_work_test.go create mode 100644 seaweed-block/internal/docs/qa-assignments/phase174-d2-nvme-tcp-fixed-work-qa.md create mode 100644 seaweed-block/scripts/run-phase174-nvme-tcp-fixed-work-gate.sh diff --git a/seaweed-block/core/frontend/nvme/phase174_fixed_work_test.go b/seaweed-block/core/frontend/nvme/phase174_fixed_work_test.go new file mode 100644 index 0000000000..d350e6e19e --- /dev/null +++ b/seaweed-block/core/frontend/nvme/phase174_fixed_work_test.go @@ -0,0 +1,504 @@ +//go:build swblock_testtools + +package nvme_test + +import ( + "bytes" + "encoding/binary" + "encoding/json" + "fmt" + "io" + "log" + "os" + "path/filepath" + "sort" + "strconv" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/frontend/nvme" + "github.com/seaweedfs/seaweed-block/core/frontend/testback" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +const ( + phase174NVMeStoreDirEnv = "SW_BLOCK_PHASE174_NVME_STORE_DIR" + phase174NVMeWritersEnv = "SW_BLOCK_PHASE174_NVME_WRITERS" + phase174NVMeRunEnv = "SW_BLOCK_PHASE174_NVME_RUN" + phase174NVMeSetEnv = "SW_BLOCK_PHASE174_NVME_SET" + + phase174NVMeBlockSize = 4096 + phase174NVMENumBlocks = 65536 + phase174NVMeRegionBlocks = phase174NVMENumBlocks / 2 + phase174NVMeAPIOperations = 16384 + phase174NVMeWarmupOperations = 1024 + phase174NVMERuns = 5 + phase174NVMESectorsPerBlock uint16 = uint16(phase174NVMeBlockSize / int(nvme.DefaultBlockSize)) +) + +type phase174NVMeView struct { + projection frontend.Projection +} + +func (v *phase174NVMeView) Projection() frontend.Projection { + return v.projection +} + +type phase174NVMeFixedWorkResult struct { + Contract string `json:"contract"` + Layer string `json:"layer"` + Scope string `json:"scope"` + AckProfile string `json:"ack_profile"` + Set int `json:"set"` + Run int `json:"run"` + Writers int `json:"writers"` + APIOperations int `json:"api_operations"` + LogicalBytes uint64 `json:"logical_bytes"` + ForegroundNanos int64 `json:"foreground_ns"` + MiBPerSecond float64 `json:"mib_per_second"` + P50Nanos int64 `json:"p50_ns"` + P95Nanos int64 `json:"p95_ns"` + P99Nanos int64 `json:"p99_ns"` + ClientWriteLatencyNanos uint64 `json:"client_write_latency_ns"` + NVMeRoundTripNonBackendNanos uint64 `json:"nvme_round_trip_nonbackend_ns"` + FinalFlushNanos int64 `json:"final_flush_ns"` + NVMeWriteCommands uint64 `json:"nvme_write_commands"` + NVMeR2TWriteCommands uint64 `json:"nvme_r2t_write_commands"` + NVMeR2TWriteBytes uint64 `json:"nvme_r2t_write_bytes"` + NVMeH2CDataPDUs uint64 `json:"nvme_h2c_data_pdus"` + NVMeH2CDataBytes uint64 `json:"nvme_h2c_data_bytes"` + TargetWriteOps uint64 `json:"target_write_ops"` + TargetWriteBytes uint64 `json:"target_write_bytes"` + TargetWriteNanos uint64 `json:"target_write_ns"` + AdapterRequestOps uint64 `json:"adapter_request_ops"` + AdapterRequestBytes uint64 `json:"adapter_request_bytes"` + AdapterWriteOps uint64 `json:"adapter_write_ops"` + AdapterWriteBytes uint64 `json:"adapter_write_bytes"` + AdapterWriteNanos uint64 `json:"adapter_write_ns"` + AdapterStorageCalls uint64 `json:"adapter_storage_write_calls"` + AdapterStorageBlocks uint64 `json:"adapter_storage_write_blocks"` + PrimaryWALWrites uint64 `json:"primary_wal_write_ops"` + PrimaryWALCopyNanos uint64 `json:"primary_wal_copy_ns"` + PrimaryWALEncodeNanos uint64 `json:"primary_wal_encode_ns"` + PrimaryWALChecksumNanos uint64 `json:"primary_wal_checksum_ns"` + PrimaryWALAppendNanos uint64 `json:"primary_wal_append_ns"` + PrimaryWALAppendLockWaitNanos uint64 `json:"primary_wal_append_lock_wait_ns"` + PrimaryWriteCommitWaitNanos uint64 `json:"primary_write_commit_lock_wait_ns"` + PrimaryDirtyMapNanos uint64 `json:"primary_dirty_map_ns"` + PrimaryStableLSN uint64 `json:"primary_stable_lsn"` + PrimaryHeadLSN uint64 `json:"primary_head_lsn"` + FlusherPhaseReset bool `json:"flusher_phase_reset"` + CloseRecoverComplete bool `json:"close_recover_complete"` + CorrectnessSamples int `json:"correctness_samples"` + MountedShapeComparable bool `json:"mounted_shape_comparable"` + MountedThroughputRatioAllowed bool `json:"mounted_throughput_ratio_allowed"` +} + +func TestPhase174NVMeFixedWorkContract(t *testing.T) { + for _, writers := range []int{1, 4, 8} { + if err := phase174NVMeValidateWriters(writers); err != nil { + t.Fatal(err) + } + seen := make(map[uint32]struct{}, phase174NVMeAPIOperations) + for operation := 0; operation < phase174NVMeAPIOperations; operation++ { + lba := phase174NVMeOperationLBA(operation, 0) + if _, exists := seen[lba]; exists { + t.Fatalf("writers=%d duplicate measured LBA %d", writers, lba) + } + seen[lba] = struct{}{} + } + } + if err := phase174NVMeValidateWriters(3); err == nil { + t.Fatal("writers=3 accepted") + } + if phase174NVMESectorsPerBlock != 8 { + t.Fatalf("NVMe sectors per logical block=%d want 8", phase174NVMESectorsPerBlock) + } +} + +func TestPhase174NVMeFixedWorkPipeline(t *testing.T) { + storeDir := os.Getenv(phase174NVMeStoreDirEnv) + if storeDir == "" { + t.Skip("formal NVMe fixed-work run requires " + phase174NVMeStoreDirEnv) + } + writers := phase174NVMeEnvInt(t, phase174NVMeWritersEnv, 1, 8) + if err := phase174NVMeValidateWriters(writers); err != nil { + t.Fatal(err) + } + run := phase174NVMeEnvInt(t, phase174NVMeRunEnv, 0, phase174NVMERuns) + set := phase174NVMeEnvInt(t, phase174NVMeSetEnv, 1, 2) + oldLogWriter := log.Writer() + if os.Getenv("SW_BLOCK_BENCH_VERBOSE") == "" { + log.SetOutput(io.Discard) + defer log.SetOutput(oldLogWriter) + } + + groupDir := filepath.Join(storeDir, fmt.Sprintf("set%d-nvme-tcp-rf1-writers%d", set, writers)) + if err := os.MkdirAll(groupDir, 0o755); err != nil { + t.Fatal(err) + } + storePath := filepath.Join(groupDir, "primary.store") + if run == 0 { + if err := os.Remove(storePath); err != nil && !os.IsNotExist(err) { + t.Fatal(err) + } + } + result := phase174RunNVMeFixedWork(t, storePath, run == 0, set, run, writers) + if run == 0 { + return + } + encoded, err := json.Marshal(result) + if err != nil { + t.Fatal(err) + } + fmt.Printf("phase174_nvme_fixed_work_result=%s\n", encoded) +} + +func phase174RunNVMeFixedWork( + t *testing.T, + storePath string, + create bool, + set, run, writers int, +) phase174NVMeFixedWorkResult { + t.Helper() + store := phase174NVMeOpenStore(t, storePath, create) + id := frontend.Identity{VolumeID: "phase174", ReplicaID: "primary", Epoch: 1, EndpointVersion: 1} + view := &phase174NVMeView{projection: frontend.Projection{ + VolumeID: id.VolumeID, ReplicaID: id.ReplicaID, Epoch: id.Epoch, + EndpointVersion: id.EndpointVersion, Healthy: true, + }} + backend := durable.NewStorageBackend(store, view, id) + backend.SetOperational(true, "phase174 NVMe fixed-work") + target := nvme.NewTarget(nvme.TargetConfig{ + Listen: "127.0.0.1:0", + SubsysNQN: "nqn.2026-04.io.seaweedfs:phase174", + VolumeID: id.VolumeID, + Provider: testback.NewStaticProvider(backend), + Handler: nvme.HandlerConfig{ + BlockSize: nvme.DefaultBlockSize, + VolumeSize: uint64(phase174NVMENumBlocks * phase174NVMeBlockSize), + }, + }) + addr, err := target.Start() + if err != nil { + t.Fatal(err) + } + client := newMultiQueueClient(t, addr, "nqn.2026-04.io.seaweedfs:phase174", + "nqn.2026-04.io.seaweedfs:phase174-host", writers) + + warmup := phase174NVMePayloads(phase174NVMeWarmupOperations, set, run, 0x1740) + if _, _, err := phase174NVMeWrites(t, client, writers, phase174NVMeRegionBlocks, warmup, false); err != nil { + t.Fatalf("warmup writes: %v", err) + } + if err := phase174NVMeFlush(t, client); err != nil { + t.Fatalf("warmup flush: %v", err) + } + if err := store.ResetFlusherForMeasurement(); err != nil { + t.Fatalf("reset flusher: %v", err) + } + + targetBefore := target.Stats() + adapterBefore := backend.WriteProfile() + storageBefore := store.WriteInstrumentation() + payloads := phase174NVMePayloads(phase174NVMeAPIOperations, set, run, 0x1741) + foreground, latencies, err := phase174NVMeWrites(t, client, writers, 0, payloads, true) + if err != nil { + t.Fatalf("measured writes: %v", err) + } + targetAfter := target.Stats() + adapterAfter := backend.WriteProfile() + storageAfter := store.WriteInstrumentation() + flushStart := time.Now() + if err := phase174NVMeFlush(t, client); err != nil { + t.Fatalf("final flush: %v", err) + } + finalFlush := time.Since(flushStart) + + phase174CloseNVMeClient(client) + if err := target.Close(); err != nil { + t.Fatal(err) + } + if err := backend.Close(); err != nil { + t.Fatal(err) + } + if err := store.Close(); err != nil { + t.Fatal(err) + } + stable, head, samples := phase174NVMeRecoverAndVerify(t, storePath, payloads) + + logicalBytes := uint64(phase174NVMeAPIOperations * phase174NVMeBlockSize) + clientLatencyNanos := phase174NVMeSumLatencies(latencies) + targetWriteNanos := adapterAfter.TargetWriteDurationNanos - adapterBefore.TargetWriteDurationNanos + nonBackendNanos := uint64(0) + if clientLatencyNanos > targetWriteNanos { + nonBackendNanos = clientLatencyNanos - targetWriteNanos + } + result := phase174NVMeFixedWorkResult{ + Contract: "phase174-fixed-work-v1", Layer: "nvme_tcp_rf1", + Scope: "nvme_tcp_target_durable_adapter", AckProfile: "local_durable", + Set: set, Run: run, Writers: writers, APIOperations: phase174NVMeAPIOperations, + LogicalBytes: logicalBytes, ForegroundNanos: foreground.Nanoseconds(), + MiBPerSecond: (float64(logicalBytes) / (1024 * 1024)) / foreground.Seconds(), + P50Nanos: phase174NVMePercentile(latencies, 50), + P95Nanos: phase174NVMePercentile(latencies, 95), + P99Nanos: phase174NVMePercentile(latencies, 99), + ClientWriteLatencyNanos: clientLatencyNanos, + NVMeRoundTripNonBackendNanos: nonBackendNanos, + FinalFlushNanos: finalFlush.Nanoseconds(), + NVMeWriteCommands: targetAfter.WriteCommands - targetBefore.WriteCommands, + NVMeR2TWriteCommands: targetAfter.R2TWriteCommands - targetBefore.R2TWriteCommands, + NVMeR2TWriteBytes: targetAfter.R2TWriteBytes - targetBefore.R2TWriteBytes, + NVMeH2CDataPDUs: targetAfter.H2CDataPDUs - targetBefore.H2CDataPDUs, + NVMeH2CDataBytes: targetAfter.H2CDataBytes - targetBefore.H2CDataBytes, + TargetWriteOps: adapterAfter.TargetWriteOps - adapterBefore.TargetWriteOps, + TargetWriteBytes: adapterAfter.TargetWriteBytes - adapterBefore.TargetWriteBytes, + TargetWriteNanos: targetWriteNanos, + AdapterRequestOps: adapterAfter.BackendWriteRequestOps - adapterBefore.BackendWriteRequestOps, + AdapterRequestBytes: adapterAfter.BackendWriteRequestBytes - adapterBefore.BackendWriteRequestBytes, + AdapterWriteOps: adapterAfter.BackendWriteOps - adapterBefore.BackendWriteOps, + AdapterWriteBytes: adapterAfter.BackendWriteBytes - adapterBefore.BackendWriteBytes, + AdapterWriteNanos: adapterAfter.BackendWriteDurationNanos - adapterBefore.BackendWriteDurationNanos, + AdapterStorageCalls: adapterAfter.BackendStorageWriteCalls - adapterBefore.BackendStorageWriteCalls, + AdapterStorageBlocks: adapterAfter.BackendStorageWriteBlocks - adapterBefore.BackendStorageWriteBlocks, + PrimaryWALWrites: storageAfter.WALEncodeOps - storageBefore.WALEncodeOps, + PrimaryWALCopyNanos: storageAfter.WALCopyDurationNanos - storageBefore.WALCopyDurationNanos, + PrimaryWALEncodeNanos: storageAfter.WALEncodeDurationNanos - storageBefore.WALEncodeDurationNanos, + PrimaryWALChecksumNanos: storageAfter.WALChecksumDurationNanos - storageBefore.WALChecksumDurationNanos, + PrimaryWALAppendNanos: storageAfter.WALAppendDurationNanos - storageBefore.WALAppendDurationNanos, + PrimaryWALAppendLockWaitNanos: storageAfter.WALAppendLockWaitNanos - storageBefore.WALAppendLockWaitNanos, + PrimaryWriteCommitWaitNanos: storageAfter.WriteCommitLockWaitNanos - storageBefore.WriteCommitLockWaitNanos, + PrimaryDirtyMapNanos: storageAfter.DirtyMapUpdateDurationNanos - storageBefore.DirtyMapUpdateDurationNanos, + PrimaryStableLSN: stable, PrimaryHeadLSN: head, FlusherPhaseReset: true, + CloseRecoverComplete: true, CorrectnessSamples: samples, + MountedShapeComparable: false, MountedThroughputRatioAllowed: false, + } + phase174NVMeValidateResult(t, result) + return result +} + +func phase174NVMeWrites( + t *testing.T, + client *multiQueueClient, + writers int, + base uint32, + payloads [][]byte, + measureLatency bool, +) (time.Duration, []int64, error) { + t.Helper() + latencies := make([]int64, len(payloads)) + start := make(chan struct{}) + var wg sync.WaitGroup + var firstErr error + var errOnce sync.Once + wallStart := time.Now() + for worker := 0; worker < writers; worker++ { + worker := worker + wg.Add(1) + go func() { + defer wg.Done() + <-start + queue := client.queues[worker] + for operation := worker; operation < len(payloads); operation += writers { + opStart := time.Now() + storageLBA := phase174NVMeOperationLBA(operation, base) + status, err := client.chunkedWriteOnQueue(t, queue, + uint64(storageLBA)*uint64(phase174NVMESectorsPerBlock), phase174NVMESectorsPerBlock, + payloads[operation], 1) + if measureLatency { + latencies[operation] = time.Since(opStart).Nanoseconds() + } + if err == nil && status != 0 { + err = fmt.Errorf("operation %d status=0x%04x", operation, status) + } + if err != nil { + errOnce.Do(func() { firstErr = err }) + return + } + } + }() + } + close(start) + wg.Wait() + return time.Since(wallStart), latencies, firstErr +} + +func phase174NVMeFlush(t *testing.T, client *multiQueueClient) error { + t.Helper() + queue := client.queues[0] + cid := uint16(client.cidSeq.Add(1)) + cmd := nvme.CapsuleCommand{OpCode: 0x00, CID: cid, NSID: 1} + if err := queue.w.SendHeaderOnly(0x4, &cmd, 64); err != nil { + return err + } + resp := recvCapsuleResp(t, queue.r) + if resp.CID != cid { + return fmt.Errorf("flush response CID=%d want %d", resp.CID, cid) + } + if resp.Status != 0 { + return fmt.Errorf("flush status=0x%04x", resp.Status) + } + return nil +} + +func phase174CloseNVMeClient(client *multiQueueClient) { + for _, queue := range client.queues { + _ = queue.conn.Close() + } + _ = client.admin.Close() +} + +func phase174NVMeOpenStore(t *testing.T, path string, create bool) *storage.WALStore { + t.Helper() + var ( + store *storage.WALStore + err error + ) + if create { + store, err = storage.CreateWALStore(path, phase174NVMENumBlocks, phase174NVMeBlockSize) + } else { + store, err = storage.OpenWALStore(path) + if err == nil { + _, err = store.Recover() + } + } + if err != nil { + if store != nil { + _ = store.Close() + } + t.Fatal(err) + } + return store +} + +func phase174NVMeRecoverAndVerify(t *testing.T, path string, payloads [][]byte) (uint64, uint64, int) { + t.Helper() + store, err := storage.OpenWALStore(path) + if err != nil { + t.Fatal(err) + } + defer func() { + if err := store.Close(); err != nil { + t.Fatal(err) + } + }() + if _, err := store.Recover(); err != nil { + t.Fatal(err) + } + stable, _, head := store.Boundaries() + if stable != head { + t.Fatalf("recovered stable=%d head=%d", stable, head) + } + samples := 0 + for _, operation := range phase174NVMESampleOperations(len(payloads)) { + got, err := store.Read(phase174NVMeOperationLBA(operation, 0)) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, payloads[operation]) { + t.Fatalf("operation=%d recovered data mismatch", operation) + } + samples++ + } + return stable, head, samples +} + +func phase174NVMeValidateResult(t *testing.T, result phase174NVMeFixedWorkResult) { + t.Helper() + wantOps := uint64(phase174NVMeAPIOperations) + wantBytes := uint64(phase174NVMeAPIOperations * phase174NVMeBlockSize) + for name, got := range map[string]uint64{ + "nvme_write_commands": result.NVMeWriteCommands, + "nvme_r2t_write_commands": result.NVMeR2TWriteCommands, + "nvme_h2c_data_pdus": result.NVMeH2CDataPDUs, + "target_write_ops": result.TargetWriteOps, + "adapter_request_ops": result.AdapterRequestOps, + "adapter_write_ops": result.AdapterWriteOps, + "adapter_storage_write_calls": result.AdapterStorageCalls, + "adapter_storage_write_blocks": result.AdapterStorageBlocks, + "primary_wal_write_ops": result.PrimaryWALWrites, + } { + if got != wantOps { + t.Fatalf("%s=%d want %d", name, got, wantOps) + } + } + for name, got := range map[string]uint64{ + "nvme_r2t_write_bytes": result.NVMeR2TWriteBytes, + "nvme_h2c_data_bytes": result.NVMeH2CDataBytes, + "target_write_bytes": result.TargetWriteBytes, + "adapter_request_bytes": result.AdapterRequestBytes, + "adapter_write_bytes": result.AdapterWriteBytes, + } { + if got != wantBytes { + t.Fatalf("%s=%d want %d", name, got, wantBytes) + } + } + if result.PrimaryStableLSN != result.PrimaryHeadLSN || result.CorrectnessSamples < 5 { + t.Fatalf("recovery stable=%d head=%d samples=%d", + result.PrimaryStableLSN, result.PrimaryHeadLSN, result.CorrectnessSamples) + } +} + +func phase174NVMeValidateWriters(writers int) error { + switch writers { + case 1, 4, 8: + return nil + default: + return fmt.Errorf("phase174 NVMe: writers=%d want one of 1,4,8", writers) + } +} + +func phase174NVMeEnvInt(t *testing.T, name string, min, max int) int { + t.Helper() + value, err := strconv.Atoi(os.Getenv(name)) + if err != nil || value < min || value > max { + t.Fatalf("%s must be in [%d,%d]", name, min, max) + } + return value +} + +func phase174NVMeOperationLBA(operation int, base uint32) uint32 { + return base + uint32((operation*7919)%phase174NVMeRegionBlocks) +} + +func phase174NVMePayloads(operations, set, run int, marker uint64) [][]byte { + payloads := make([][]byte, operations) + for operation := range payloads { + payload := make([]byte, phase174NVMeBlockSize) + for offset := 0; offset < len(payload); offset += 8 { + value := marker<<48 | uint64(set)<<40 | uint64(run)<<32 | + uint64(operation+1)<<12 | uint64(offset/8) + binary.LittleEndian.PutUint64(payload[offset:offset+8], value) + } + payloads[operation] = payload + } + return payloads +} + +func phase174NVMESampleOperations(operations int) []int { + samples := []int{0, operations / 7, operations / 3, operations / 2, operations - 1} + sort.Ints(samples) + return samples +} + +func phase174NVMePercentile(samples []int64, percent int) int64 { + ordered := append([]int64(nil), samples...) + sort.Slice(ordered, func(i, j int) bool { return ordered[i] < ordered[j] }) + index := (len(ordered)*percent + 99) / 100 + if index > 0 { + index-- + } + return ordered[index] +} + +func phase174NVMeSumLatencies(samples []int64) uint64 { + var total uint64 + for _, sample := range samples { + if sample > 0 { + total += uint64(sample) + } + } + return total +} diff --git a/seaweed-block/internal/docs/qa-assignments/phase174-d2-nvme-tcp-fixed-work-qa.md b/seaweed-block/internal/docs/qa-assignments/phase174-d2-nvme-tcp-fixed-work-qa.md new file mode 100644 index 0000000000..6dedadb4fe --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase174-d2-nvme-tcp-fixed-work-qa.md @@ -0,0 +1,79 @@ +# Phase 174 D2 NVMe/TCP Fixed-Work QA + +## Purpose + +Measure the real NVMe/TCP target over the same logical-work contract used by +the Phase 174 engine and durable-adapter slices. This is an RF1 local-durable +attribution gate, not a mounted or RF3 performance claim. + +## Source + +Run the gate from the exact assigned commit. Do not use a dirty shared tree. +The test binary must be built with `swblock_testtools`; no shipped binary gains +test-only reset or benchmark behavior. + +## Environment + +- Linux host: m02. +- Store root: a dedicated NVMe filesystem, normally `/data/nvme/block`. +- CPU control: `GOMAXPROCS=4`, `taskset -c 0,2,4,6` unless the host topology + requires an explicitly documented replacement. +- Transport: real loopback NVMe/TCP admin and IO queues. Loopback removes the + external network from this attribution slice; it does not make the result a + mounted or 100 GbE claim. + +## Command + +```bash +SW_BLOCK_ARTIFACT_DIR=/tmp/ \ +SW_BLOCK_PHASE174_NVME_STORE_DIR=/data/nvme/block/-stores \ + bash scripts/run-phase174-nvme-tcp-fixed-work-gate.sh "$PWD" +``` + +## Required Checks + +1. The fixed work is exactly 16,384 API writes of 4 KiB, with 1, 4, and 8 + independent NVMe IO queues. +2. Each writer shape has two independently ordered sets of five measured + runs, after one precondition run per set and shape. +3. Every measured row reports exactly 16,384 NVMe Write commands, R2T writes, + H2C PDUs, target writes, adapter requests/writes, storage calls/blocks, and + WAL writes. +4. Every byte counter reports exactly 67,108,864 bytes. +5. The accumulated client request latency reconciles as target backend-call + time plus NVMe/TCP round-trip non-backend time. The latter includes test + initiator, loopback TCP, R2T/H2C receive, dispatch, and completion; do not + relabel it as a pure target CPU measurement. +6. Final NVMe Flush succeeds, close/reopen/recovery reaches `R == H`, and at + least five measured LBAs retain the expected bytes. +7. Capture merged CPU, block, and mutex profiles for five four-queue diagnostic + runs. +8. Record stability honestly. A range above `1.25x` is HOLD evidence, not a + reason to delete a slow run or select an architecture candidate. +9. All test stores and the test binary are removed after the gate. + +## Mounted Boundary + +The existing mounted fio/dd gates do not issue the same API/LBA/queue shape. +This gate must keep: + +```text +mounted_shape_comparable=false +mounted_throughput_ratio_allowed=false +``` + +Mounted evidence remains a separate product diagnostic until a kernel +initiator workload can prove the same logical operation contract. Do not +divide this gate's throughput by historical mounted numbers. + +## Verdict + +- PASS: all operation, byte, recovery, and cleanup checks reconcile. Stability + may be recorded as PASS or HOLD independently. +- FAIL: protocol/status error, counter mismatch, failed Flush/recovery/data + check, or store residue. +- BLOCKED: the dedicated filesystem, CPU controls, or required Linux tooling + is unavailable. + +No result from this gate selects or implements an architecture change by +itself. diff --git a/seaweed-block/scripts/run-phase174-nvme-tcp-fixed-work-gate.sh b/seaweed-block/scripts/run-phase174-nvme-tcp-fixed-work-gate.sh new file mode 100644 index 0000000000..097cf74032 --- /dev/null +++ b/seaweed-block/scripts/run-phase174-nvme-tcp-fixed-work-gate.sh @@ -0,0 +1,261 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT="${1:-$(pwd)}" +ARTIFACT_DIR="${SW_BLOCK_ARTIFACT_DIR:-${ROOT}/results/phase174-nvme-tcp-fixed-work-gate}" +STORE_DIR="${SW_BLOCK_PHASE174_NVME_STORE_DIR:-${ARTIFACT_DIR}/stores}" +SUMMARY="${ARTIFACT_DIR}/phase174-nvme-tcp-fixed-work-summary.txt" +RESULTS="${ARTIFACT_DIR}/phase174-nvme-tcp-fixed-work-results.jsonl" +TEST_BINARY="${ARTIFACT_DIR}/phase174-nvme.test" +RUNS=5 +MAX_RANGE="1.25" +CPUSET="${SW_BLOCK_PHASE174_CPUSET:-0,2,4,6}" +GOMAXPROCS_VALUE="${SW_BLOCK_PHASE174_GOMAXPROCS:-4}" +WRITERS_FORWARD=(1 4 8) +WRITERS_REVERSE=(8 4 1) + +mkdir -p "${ARTIFACT_DIR}/logs" "${ARTIFACT_DIR}/profiles" "${STORE_DIR}" +: >"${SUMMARY}" +: >"${RESULTS}" + +write_summary() { + echo "$*" | tee -a "${SUMMARY}" >/dev/null +} + +capture() { + local name="$1" + shift + "$@" >"${ARTIFACT_DIR}/${name}.txt" 2>&1 || true +} + +cleanup() { + find "${STORE_DIR}" -type f -name '*.store' -delete 2>/dev/null || true + find "${STORE_DIR}" -depth -type d -empty -delete 2>/dev/null || true + rm -f "${TEST_BINARY}" +} +trap cleanup EXIT + +for command in go python3 taskset findmnt; do + command -v "${command}" >/dev/null 2>&1 || { + echo "missing required command: ${command}" >&2 + exit 2 + } +done + +store_source="$(findmnt -n -o SOURCE -T "${STORE_DIR}")" +store_filesystem="$(findmnt -n -o FSTYPE -T "${STORE_DIR}")" +root_source="$(findmnt -n -o SOURCE -T /)" +if [[ -z "${store_source}" || "${store_source}" == "${root_source}" ]]; then + echo "phase174 NVMe store must use a dedicated filesystem: store=${store_source:-missing} root=${root_source}" >&2 + exit 1 +fi + +write_summary "phase174_nvme_tcp_fixed_work_status=running" +write_summary "contract=phase174-fixed-work-v1" +write_summary "layer=nvme_tcp_rf1" +write_summary "scope=nvme_tcp_target_durable_adapter" +write_summary "ack_profile=local_durable" +write_summary "transport=tcp" +write_summary "runs_per_set=${RUNS}" +write_summary "sets=2" +write_summary "writers=1,4,8" +write_summary "logical_block_bytes=4096" +write_summary "nvme_sector_bytes=512" +write_summary "api_operations_per_run=16384" +write_summary "max_min_limit=${MAX_RANGE}" +write_summary "store_source=${store_source}" +write_summary "store_filesystem=${store_filesystem}" +write_summary "dedicated_store_source=true" +write_summary "control_cpuset=${CPUSET}" +write_summary "control_gomaxprocs=${GOMAXPROCS_VALUE}" +write_summary "second_set_order=reversed" +write_summary "mounted_shape_comparable=false" +write_summary "mounted_throughput_ratio_allowed=false" + +capture kernel uname -a +capture go-version go version +capture cpu lscpu +capture filesystem findmnt -T "${STORE_DIR}" -o TARGET,SOURCE,FSTYPE,OPTIONS +capture free-space df -hT "${STORE_DIR}" +capture load uptime + +cd "${ROOT}" +go test -tags swblock_testtools ./core/frontend/nvme \ + -run '^TestPhase174NVMeFixedWorkContract$' -count=1 \ + >"${ARTIFACT_DIR}/contract-test.log" 2>&1 +go test -tags swblock_testtools -c -o "${TEST_BINARY}" ./core/frontend/nvme + +for set_id in 1 2; do + sync + sleep 5 + capture "set-${set_id}-start-load" uptime + if [[ "${set_id}" == "1" ]]; then + writers_values=("${WRITERS_FORWARD[@]}") + else + writers_values=("${WRITERS_REVERSE[@]}") + fi + for writers in "${writers_values[@]}"; do + precondition_log="${ARTIFACT_DIR}/logs/set${set_id}-writers${writers}-precondition.log" + SW_BLOCK_PHASE174_NVME_STORE_DIR="${STORE_DIR}" \ + SW_BLOCK_PHASE174_NVME_WRITERS="${writers}" \ + SW_BLOCK_PHASE174_NVME_SET="${set_id}" \ + SW_BLOCK_PHASE174_NVME_RUN=0 \ + GOMAXPROCS="${GOMAXPROCS_VALUE}" taskset -c "${CPUSET}" \ + "${TEST_BINARY}" -test.run '^TestPhase174NVMeFixedWorkPipeline$' -test.count=1 -test.timeout=10m \ + >"${precondition_log}" 2>&1 + for run in $(seq 1 "${RUNS}"); do + sync + sleep 0.25 + run_log="${ARTIFACT_DIR}/logs/set${set_id}-writers${writers}-run${run}.log" + SW_BLOCK_PHASE174_NVME_STORE_DIR="${STORE_DIR}" \ + SW_BLOCK_PHASE174_NVME_WRITERS="${writers}" \ + SW_BLOCK_PHASE174_NVME_SET="${set_id}" \ + SW_BLOCK_PHASE174_NVME_RUN="${run}" \ + GOMAXPROCS="${GOMAXPROCS_VALUE}" taskset -c "${CPUSET}" \ + "${TEST_BINARY}" -test.run '^TestPhase174NVMeFixedWorkPipeline$' -test.count=1 -test.timeout=10m \ + >"${run_log}" 2>&1 + sed -n 's/^phase174_nvme_fixed_work_result=//p' "${run_log}" >>"${RESULTS}" + done + done +done + +PROFILE_STORE="${STORE_DIR}/profiles" +mkdir -p "${PROFILE_STORE}" +SW_BLOCK_PHASE174_NVME_STORE_DIR="${PROFILE_STORE}" \ +SW_BLOCK_PHASE174_NVME_WRITERS=4 \ +SW_BLOCK_PHASE174_NVME_SET=1 \ +SW_BLOCK_PHASE174_NVME_RUN=0 \ +GOMAXPROCS="${GOMAXPROCS_VALUE}" taskset -c "${CPUSET}" \ + "${TEST_BINARY}" -test.run '^TestPhase174NVMeFixedWorkPipeline$' -test.count=1 -test.timeout=10m \ + >"${ARTIFACT_DIR}/profiles/precondition.log" 2>&1 + +cpu_profiles=() +block_profiles=() +mutex_profiles=() +for run in $(seq 1 "${RUNS}"); do + prefix="${ARTIFACT_DIR}/profiles/run${run}" + SW_BLOCK_PHASE174_NVME_STORE_DIR="${PROFILE_STORE}" \ + SW_BLOCK_PHASE174_NVME_WRITERS=4 \ + SW_BLOCK_PHASE174_NVME_SET=1 \ + SW_BLOCK_PHASE174_NVME_RUN="${run}" \ + GOMAXPROCS="${GOMAXPROCS_VALUE}" taskset -c "${CPUSET}" \ + "${TEST_BINARY}" -test.run '^TestPhase174NVMeFixedWorkPipeline$' -test.count=1 -test.timeout=10m \ + -test.cpuprofile="${prefix}-cpu.pprof" \ + -test.blockprofile="${prefix}-block.pprof" -test.blockprofilerate=1 \ + -test.mutexprofile="${prefix}-mutex.pprof" -test.mutexprofilefraction=1 \ + >"${prefix}.log" 2>&1 + cpu_profiles+=("${prefix}-cpu.pprof") + block_profiles+=("${prefix}-block.pprof") + mutex_profiles+=("${prefix}-mutex.pprof") +done +go tool pprof -top -nodecount=40 "${TEST_BINARY}" "${cpu_profiles[@]}" \ + >"${ARTIFACT_DIR}/profiles/cpu-top.txt" 2>&1 +go tool pprof -top -nodecount=40 "${TEST_BINARY}" "${block_profiles[@]}" \ + >"${ARTIFACT_DIR}/profiles/block-top.txt" 2>&1 +go tool pprof -top -nodecount=40 "${TEST_BINARY}" "${mutex_profiles[@]}" \ + >"${ARTIFACT_DIR}/profiles/mutex-top.txt" 2>&1 + +python3 - "${RESULTS}" "${SUMMARY}" "${RUNS}" "${MAX_RANGE}" <<'PY' +import json +import statistics +import sys +from collections import defaultdict + +results_path, summary_path, runs_text, max_range_text = sys.argv[1:] +runs = int(runs_text) +max_range = float(max_range_text) +rows = [json.loads(line) for line in open(results_path, encoding="utf-8") if line.strip()] +if len(rows) != 6 * runs: + raise SystemExit(f"NVMe fixed-work rows={len(rows)} want {6 * runs}") + +groups = defaultdict(list) +for row in rows: + if row["contract"] != "phase174-fixed-work-v1": + raise SystemExit(f"bad contract: {row}") + if row["layer"] != "nvme_tcp_rf1" or row["ack_profile"] != "local_durable": + raise SystemExit(f"bad layer contract: {row}") + if row["api_operations"] != 16384 or row["logical_bytes"] != 67108864: + raise SystemExit(f"bad fixed work: {row}") + for key in ( + "nvme_write_commands", "nvme_r2t_write_commands", "nvme_h2c_data_pdus", + "target_write_ops", "adapter_request_ops", "adapter_write_ops", + "adapter_storage_write_calls", "adapter_storage_write_blocks", + "primary_wal_write_ops", + ): + if row[key] != 16384: + raise SystemExit(f"{key} mismatch: {row}") + for key in ( + "nvme_r2t_write_bytes", "nvme_h2c_data_bytes", "target_write_bytes", + "adapter_request_bytes", "adapter_write_bytes", + ): + if row[key] != 67108864: + raise SystemExit(f"{key} mismatch: {row}") + if row["client_write_latency_ns"] < row["target_write_ns"]: + raise SystemExit(f"target duration exceeds client duration: {row}") + if row["nvme_round_trip_nonbackend_ns"] != row["client_write_latency_ns"] - row["target_write_ns"]: + raise SystemExit(f"non-backend duration mismatch: {row}") + if row["primary_stable_lsn"] != row["primary_head_lsn"]: + raise SystemExit(f"primary frontier mismatch: {row}") + if not row["flusher_phase_reset"] or not row["close_recover_complete"]: + raise SystemExit(f"recovery/reset missing: {row}") + if row["correctness_samples"] < 5 or row["foreground_ns"] <= 0 or row["p99_ns"] <= 0: + raise SystemExit(f"timing/correctness evidence missing: {row}") + if row["mounted_shape_comparable"] or row["mounted_throughput_ratio_allowed"]: + raise SystemExit(f"mounted diagnostic mislabelled comparable: {row}") + groups[(int(row["writers"]), int(row["set"]))].append(row) + +for key, values in groups.items(): + if len(values) != runs: + raise SystemExit(f"group {key} rows={len(values)} want {runs}") + +def all_rows(writers): + return groups[(writers, 1)] + groups[(writers, 2)] + +def median_rate(writers): + return statistics.median(row["mib_per_second"] for row in all_rows(writers)) + +def value_range(values): + return max(values) / min(values) + +def rate_range(writers, set_id=None): + values = all_rows(writers) if set_id is None else groups[(writers, set_id)] + return value_range([row["mib_per_second"] for row in values]) + +def median_per_op(rows, field): + return statistics.median(row[field] / row["api_operations"] for row in rows) + +four = all_rows(4) +frontend_stable = all(rate_range(4, set_id) <= max_range for set_id in (1, 2)) and rate_range(4) <= max_range +target_per_op = median_per_op(four, "target_write_ns") +roundtrip_per_op = median_per_op(four, "nvme_round_trip_nonbackend_ns") +dominant = "target_backend_call" if target_per_op >= roundtrip_per_op else "nvme_tcp_round_trip_nonbackend" + +with open(summary_path, "a", encoding="utf-8") as out: + for writers in (1, 4, 8): + out.write(f"nvme_tcp_rf1_writers_{writers}_median_mibps={median_rate(writers):.3f}\n") + out.write(f"nvme_tcp_rf1_writers_{writers}_max_min_ratio={rate_range(writers):.3f}\n") + out.write(f"nvme_tcp_rf1_writers_{writers}_set1_max_min_ratio={rate_range(writers, 1):.3f}\n") + out.write(f"nvme_tcp_rf1_writers_{writers}_set2_max_min_ratio={rate_range(writers, 2):.3f}\n") + for field in ( + "client_write_latency_ns", "nvme_round_trip_nonbackend_ns", "target_write_ns", + "adapter_write_ns", "primary_write_commit_lock_wait_ns", "primary_wal_encode_ns", + "primary_wal_append_ns", "primary_dirty_map_ns", + ): + out.write(f"nvme_tcp_rf1_writers_4_{field}_per_op={median_per_op(four, field):.3f}\n") + out.write(f"nvme_tcp_rf1_dominant_accumulated_boundary={dominant}\n") + out.write("nvme_tcp_rf1_counter_reconciliation=true\n") + out.write("nvme_tcp_rf1_close_recover_verified=true\n") + out.write(f"nvme_tcp_rf1_stability_gate={'pass' if frontend_stable else 'hold'}\n") + out.write("mounted_shape_comparable=false\n") + out.write("mounted_throughput_ratio_allowed=false\n") + out.write("architecture_candidate_selected=false\n") + out.write("phase174_nvme_tcp_fixed_work_status=ok\n") +PY + +cleanup +find "${STORE_DIR}" -type f -name '*.store' -print -quit 2>/dev/null | grep -q . && { + echo "phase174 NVMe store residue remains under ${STORE_DIR}" >&2 + exit 1 +} +write_summary "store_residue_count=0" +cat "${SUMMARY}"