Merge pull request #80 from seaweedfs/phase174-frontend-replication-execution

storage: close execution architecture decisions
This commit is contained in:
Ping Qiu authored and GitHub committed 2026-08-01 05:07:22 -07:00
commit b1ff581924
47 files changed
+7419 -263

No files matched your search

+3
View File
@@ -1027,6 +1027,9 @@ func run(f flags) int {
}
if status != nil {
status.SetFrontendCapabilities(nvmeFrontendCapabilities(f.nvmeListen, f.nvmeTransport, true))
if source, ok := nvmeTarget.(interface{ Stats() nvme.Stats }); ok {
status.SetNVMeStatusSource(source)
}
}
}
@@ -327,6 +327,13 @@ func (b *StorageBackend) SetWriteAckPolicy(policy WriteAckPolicy) {
b.mu.Unlock()
}
// WriteProfile returns a read-only snapshot of the adapter's existing
// cumulative write counters. It does not enable instrumentation or alter the
// write path.
func (b *StorageBackend) WriteProfile() WriteProfileStatus {
return b.profile.snapshot()
}
// SetOperational flips the readiness gate. evidence is surfaced
// in error strings and diagnostic logs — pass a short reason like
// "recovered LSN=123 epoch=4" or "superblock ahead of assignment".
@@ -60,6 +60,25 @@ type partialBatchStorage struct {
err error
}
func TestStorageBackend_WriteProfileReturnsCurrentSnapshot(t *testing.T) {
b, _, _ := newTestBackend(t, logicalStorageFactories()[0], 16, 4096)
payload := make([]byte, 4096)
if _, err := b.Write(context.Background(), 0, payload); err != nil {
t.Fatal(err)
}
profile := b.WriteProfile()
if profile.BackendWriteRequestOps != 1 || profile.BackendWriteRequestBytes != uint64(len(payload)) {
t.Fatalf("request profile=%+v", profile)
}
if profile.BackendWriteOps != 1 || profile.BackendWriteBytes != uint64(len(payload)) {
t.Fatalf("write profile=%+v", profile)
}
if profile.BackendStorageWriteCalls != 1 || profile.BackendStorageWriteBlocks != 1 {
t.Fatalf("storage profile=%+v", profile)
}
}
func (s partialBatchStorage) WriteBatch(_ uint32, _ [][]byte) ([]uint64, error) {
return []uint64{1}, s.err
}
@@ -0,0 +1,592 @@
//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"`
NVMeCapsuleReceiveParseOps uint64 `json:"nvme_capsule_receive_parse_ops"`
NVMeCapsuleReceiveParseNanos uint64 `json:"nvme_capsule_receive_parse_ns"`
NVMeR2TCollectionOps uint64 `json:"nvme_r2t_collection_ops"`
NVMeR2TCollectionNanos uint64 `json:"nvme_r2t_collection_ns"`
NVMeDispatchWaitOps uint64 `json:"nvme_dispatch_wait_ops"`
NVMeDispatchWaitNanos uint64 `json:"nvme_dispatch_wait_ns"`
NVMeHandlerOps uint64 `json:"nvme_handler_ops"`
NVMeHandlerNanos uint64 `json:"nvme_handler_ns"`
NVMeCompletionQueueWaitOps uint64 `json:"nvme_completion_queue_wait_ops"`
NVMeCompletionQueueWaitNanos uint64 `json:"nvme_completion_queue_wait_ns"`
NVMeCompletionSendOps uint64 `json:"nvme_completion_send_ops"`
NVMeCompletionSendNanos uint64 `json:"nvme_completion_send_ns"`
NVMeServerPhaseNanos uint64 `json:"nvme_server_phase_ns"`
NVMeClientResidualNanos uint64 `json:"nvme_client_residual_ns"`
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"`
FlusherCycles uint64 `json:"foreground_flusher_cycles"`
FlusherCycleNanos uint64 `json:"foreground_flusher_cycle_ns"`
FlusherExtentWriteOps uint64 `json:"foreground_flusher_extent_write_ops"`
FlusherExtentWriteNanos uint64 `json:"foreground_flusher_extent_write_ns"`
FlusherExtentSyncOps uint64 `json:"foreground_flusher_extent_sync_ops"`
FlusherExtentSyncNanos uint64 `json:"foreground_flusher_extent_sync_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()
flusherBefore := store.FlusherInstrumentation()
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 := phase174NVMeWaitForWritePhases(t, target, targetBefore, phase174NVMeAPIOperations)
adapterAfter := backend.WriteProfile()
storageAfter := store.WriteInstrumentation()
flusherAfter := store.FlusherInstrumentation()
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
}
serverPhaseNanos :=
(targetAfter.WriteCapsuleReceiveParseNanos - targetBefore.WriteCapsuleReceiveParseNanos) +
(targetAfter.R2TDataCollectionNanos - targetBefore.R2TDataCollectionNanos) +
(targetAfter.WriteDispatchWaitNanos - targetBefore.WriteDispatchWaitNanos) +
(targetAfter.WriteHandlerNanos - targetBefore.WriteHandlerNanos) +
(targetAfter.WriteCompletionQueueWaitNanos - targetBefore.WriteCompletionQueueWaitNanos) +
(targetAfter.WriteCompletionSendNanos - targetBefore.WriteCompletionSendNanos)
clientResidualNanos := uint64(0)
if clientLatencyNanos > serverPhaseNanos {
clientResidualNanos = clientLatencyNanos - serverPhaseNanos
}
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,
NVMeCapsuleReceiveParseOps: targetAfter.WriteCapsuleReceiveParseOps - targetBefore.WriteCapsuleReceiveParseOps,
NVMeCapsuleReceiveParseNanos: targetAfter.WriteCapsuleReceiveParseNanos - targetBefore.WriteCapsuleReceiveParseNanos,
NVMeR2TCollectionOps: targetAfter.R2TDataCollectionOps - targetBefore.R2TDataCollectionOps,
NVMeR2TCollectionNanos: targetAfter.R2TDataCollectionNanos - targetBefore.R2TDataCollectionNanos,
NVMeDispatchWaitOps: targetAfter.WriteDispatchWaitOps - targetBefore.WriteDispatchWaitOps,
NVMeDispatchWaitNanos: targetAfter.WriteDispatchWaitNanos - targetBefore.WriteDispatchWaitNanos,
NVMeHandlerOps: targetAfter.WriteHandlerOps - targetBefore.WriteHandlerOps,
NVMeHandlerNanos: targetAfter.WriteHandlerNanos - targetBefore.WriteHandlerNanos,
NVMeCompletionQueueWaitOps: targetAfter.WriteCompletionQueueWaitOps - targetBefore.WriteCompletionQueueWaitOps,
NVMeCompletionQueueWaitNanos: targetAfter.WriteCompletionQueueWaitNanos - targetBefore.WriteCompletionQueueWaitNanos,
NVMeCompletionSendOps: targetAfter.WriteCompletionSendOps - targetBefore.WriteCompletionSendOps,
NVMeCompletionSendNanos: targetAfter.WriteCompletionSendNanos - targetBefore.WriteCompletionSendNanos,
NVMeServerPhaseNanos: serverPhaseNanos,
NVMeClientResidualNanos: clientResidualNanos,
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,
FlusherCycles: flusherAfter.CyclesStarted - flusherBefore.CyclesStarted,
FlusherCycleNanos: flusherAfter.CycleDurationNanos - flusherBefore.CycleDurationNanos,
FlusherExtentWriteOps: flusherAfter.ExtentWriteOps - flusherBefore.ExtentWriteOps,
FlusherExtentWriteNanos: flusherAfter.ExtentWriteDurationNanos - flusherBefore.ExtentWriteDurationNanos,
FlusherExtentSyncOps: flusherAfter.ExtentSyncOps - flusherBefore.ExtentSyncOps,
FlusherExtentSyncNanos: flusherAfter.ExtentSyncDurationNanos - flusherBefore.ExtentSyncDurationNanos,
PrimaryStableLSN: stable, PrimaryHeadLSN: head, FlusherPhaseReset: true,
CloseRecoverComplete: true, CorrectnessSamples: samples,
MountedShapeComparable: false, MountedThroughputRatioAllowed: false,
}
phase174NVMeValidateResult(t, result)
return result
}
func phase174NVMeWaitForWritePhases(
t *testing.T,
target *nvme.Target,
before nvme.Stats,
want uint64,
) nvme.Stats {
t.Helper()
deadline := time.Now().Add(time.Second)
for {
after := target.Stats()
if after.WriteCapsuleReceiveParseOps-before.WriteCapsuleReceiveParseOps >= want &&
after.WriteDispatchWaitOps-before.WriteDispatchWaitOps >= want &&
after.WriteHandlerOps-before.WriteHandlerOps >= want &&
after.WriteCompletionQueueWaitOps-before.WriteCompletionQueueWaitOps >= want &&
after.WriteCompletionSendOps-before.WriteCompletionSendOps >= want {
return after
}
if time.Now().After(deadline) {
t.Fatalf("write phase stats did not reach %d: before=%+v after=%+v", want, before, after)
}
time.Sleep(time.Millisecond)
}
}
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,
"nvme_capsule_receive_parse_ops": result.NVMeCapsuleReceiveParseOps,
"nvme_r2t_collection_ops": result.NVMeR2TCollectionOps,
"nvme_dispatch_wait_ops": result.NVMeDispatchWaitOps,
"nvme_handler_ops": result.NVMeHandlerOps,
"nvme_completion_queue_wait_ops": result.NVMeCompletionQueueWaitOps,
"nvme_completion_send_ops": result.NVMeCompletionSendOps,
"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)
}
if result.NVMeServerPhaseNanos > result.ClientWriteLatencyNanos ||
result.NVMeClientResidualNanos != result.ClientWriteLatencyNanos-result.NVMeServerPhaseNanos {
t.Fatalf("NVMe phase time does not reconcile: client=%d server=%d residual=%d",
result.ClientWriteLatencyNanos, result.NVMeServerPhaseNanos, result.NVMeClientResidualNanos)
}
}
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
}
+71 -6
View File
@@ -67,6 +67,7 @@ import (
"net"
"sync"
"sync/atomic"
"time"
)
// errDisconnect is a sentinel returned by handleDisconnect (BUG-002)
@@ -76,10 +77,11 @@ var errDisconnect = errors.New("disconnect")
// Request represents an in-flight NVMe command being processed.
type Request struct {
capsule CapsuleCommand
payload []byte // inline/R2T-collected data for Write
resp CapsuleResponse
c2hData []byte // non-nil for Read/Identify responses
capsule CapsuleCommand
payload []byte // inline/R2T-collected data for Write
resp CapsuleResponse
c2hData []byte // non-nil for Read/Identify responses
dispatchReadyAt time.Time
}
// response represents a pending response to be written by txLoop.
@@ -92,6 +94,9 @@ type response struct {
r2t *R2THeader
r2tDone chan struct{}
writeCompletion bool
queuedAt time.Time
}
// Session carries per-connection NVMe/TCP state.
@@ -249,6 +254,7 @@ func (s *Session) rxLoop(ctx context.Context) error {
}
func (s *Session) parseCapsule() (*Request, error) {
start := time.Now()
var capsule CapsuleCommand
if err := s.wire.Receive(&capsule); err != nil {
return nil, err
@@ -262,6 +268,9 @@ func (s *Session) parseCapsule() (*Request, error) {
}
req := &Request{capsule: capsule, payload: payload}
req.resp.CID = capsule.CID
if s.qid > 0 && capsule.OpCode == ioWrite {
s.recordWriteCapsuleReceiveParse(time.Since(start))
}
return req, nil
}
@@ -312,6 +321,7 @@ func (s *Session) dispatchFromRx(ctx context.Context, req *Request) error {
} else {
s.recordInlineWrite(uint32(len(req.payload)))
}
req.dispatchReadyAt = time.Now()
}
s.cmdWg.Add(1)
@@ -328,6 +338,7 @@ func (s *Session) dispatchFromRx(ctx context.Context, req *Request) error {
// blocks rxLoop; pipelined Cmds arriving during this window are
// absorbed into pendingCapsules by bufferInterleaved.
func (s *Session) collectR2TData(req *Request) error {
start := time.Now()
totalBytes := req.capsule.LbaLength() * s.handler.BlockSize()
r2tDone := make(chan struct{})
@@ -356,6 +367,7 @@ func (s *Session) collectR2TData(req *Request) error {
return err
}
req.payload = data
s.recordR2TDataCollection(time.Since(start))
return nil
}
@@ -521,6 +533,9 @@ func (s *Session) writeResponse(resp *response) error {
} else {
resp.resp.SQHD = uint16(s.sqhd.Load())
}
if resp.writeCompletion {
s.recordWriteCompletionQueueWait(time.Since(resp.queuedAt))
}
if len(resp.c2hData) > 0 {
s.recordC2HData(uint32(len(resp.c2hData)))
@@ -533,7 +548,12 @@ func (s *Session) writeResponse(resp *response) error {
return err
}
}
return s.wire.SendHeaderOnly(pduCapsuleResp, &resp.resp, capsuleRespSize)
sendStart := time.Now()
err := s.wire.SendHeaderOnly(pduCapsuleResp, &resp.resp, capsuleRespSize)
if resp.writeCompletion {
s.recordWriteCompletionSend(time.Since(sendStart))
}
return err
}
func (s *Session) enqueueResponse(resp *response) {
@@ -563,6 +583,8 @@ func (s *Session) handleRead(ctx context.Context, req *Request) {
func (s *Session) handleWrite(ctx context.Context, req *Request) {
s.recordWriteCommand()
s.recordWriteDispatchWait(time.Since(req.dispatchReadyAt))
handlerStart := time.Now()
res := s.handler.Handle(ctx, IOCommand{
Opcode: req.capsule.OpCode,
NSID: req.capsule.NSID,
@@ -570,10 +592,11 @@ func (s *Session) handleWrite(ctx context.Context, req *Request) {
NLB: req.capsule.LbaLength(),
Data: req.payload,
})
s.recordWriteHandler(time.Since(handlerStart))
if res.AsError() != nil {
req.resp.Status = MakeStatusField(res.SCT, res.SC, true)
}
s.enqueueResponse(&response{resp: req.resp})
s.enqueueResponse(&response{resp: req.resp, writeCompletion: true, queuedAt: time.Now()})
}
// ---------- Fabric ----------
@@ -765,6 +788,48 @@ func (s *Session) recordC2HData(bytes uint32) {
}
}
func (s *Session) recordWriteCapsuleReceiveParse(d time.Duration) {
if s.target != nil {
s.target.stats.writeCapsuleReceiveParseOps.Add(1)
s.target.stats.writeCapsuleReceiveParseNanos.Add(statsDurationNanos(d))
}
}
func (s *Session) recordR2TDataCollection(d time.Duration) {
if s.target != nil {
s.target.stats.r2tDataCollectionOps.Add(1)
s.target.stats.r2tDataCollectionNanos.Add(statsDurationNanos(d))
}
}
func (s *Session) recordWriteDispatchWait(d time.Duration) {
if s.target != nil {
s.target.stats.writeDispatchWaitOps.Add(1)
s.target.stats.writeDispatchWaitNanos.Add(statsDurationNanos(d))
}
}
func (s *Session) recordWriteHandler(d time.Duration) {
if s.target != nil {
s.target.stats.writeHandlerOps.Add(1)
s.target.stats.writeHandlerNanos.Add(statsDurationNanos(d))
}
}
func (s *Session) recordWriteCompletionQueueWait(d time.Duration) {
if s.target != nil {
s.target.stats.writeCompletionQueueWaitOps.Add(1)
s.target.stats.writeCompletionQueueWaitNanos.Add(statsDurationNanos(d))
}
}
func (s *Session) recordWriteCompletionSend(d time.Duration) {
if s.target != nil {
s.target.stats.writeCompletionSendOps.Add(1)
s.target.stats.writeCompletionSendNanos.Add(statsDurationNanos(d))
}
}
// handleDisconnect (BUG-002).
func (s *Session) handleDisconnect(req *Request) error {
if s.logger != nil && s.ctrl != nil {
+68 -16
View File
@@ -1,12 +1,19 @@
package nvme
import "sync/atomic"
import (
"sync/atomic"
"time"
)
// Stats is a snapshot of target-level NVMe/TCP activity.
//
// It is intentionally transport-focused, not a performance API. The first use
// is lab evidence: after a real Linux initiator run, we need to know whether
// writes arrived inline in the capsule or through R2T/H2CData.
// writes arrived inline in the capsule or through R2T/H2CData. Phase timings
// are cumulative per-operation attribution evidence; concurrent phases can
// overlap in wall time and do not affect request handling. Capsule receive
// includes socket wait and decode. R2T collection includes target send,
// initiator response, and H2CData receive.
type Stats struct {
SessionsAccepted uint64 `json:"sessions_accepted"`
AdminConnects uint64 `json:"admin_connects"`
@@ -25,6 +32,19 @@ type Stats struct {
H2CDataBytes uint64 `json:"h2c_data_bytes"`
C2HDataPDUs uint64 `json:"c2h_data_pdus"`
C2HDataBytes uint64 `json:"c2h_data_bytes"`
WriteCapsuleReceiveParseOps uint64 `json:"write_capsule_receive_parse_ops"`
WriteCapsuleReceiveParseNanos uint64 `json:"write_capsule_receive_parse_ns"`
R2TDataCollectionOps uint64 `json:"r2t_data_collection_ops"`
R2TDataCollectionNanos uint64 `json:"r2t_data_collection_ns"`
WriteDispatchWaitOps uint64 `json:"write_dispatch_wait_ops"`
WriteDispatchWaitNanos uint64 `json:"write_dispatch_wait_ns"`
WriteHandlerOps uint64 `json:"write_handler_ops"`
WriteHandlerNanos uint64 `json:"write_handler_ns"`
WriteCompletionQueueWaitOps uint64 `json:"write_completion_queue_wait_ops"`
WriteCompletionQueueWaitNanos uint64 `json:"write_completion_queue_wait_ns"`
WriteCompletionSendOps uint64 `json:"write_completion_send_ops"`
WriteCompletionSendNanos uint64 `json:"write_completion_send_ns"`
}
type targetStats struct {
@@ -45,6 +65,19 @@ type targetStats struct {
h2cDataBytes atomic.Uint64
c2hDataPDUs atomic.Uint64
c2hDataBytes atomic.Uint64
writeCapsuleReceiveParseOps atomic.Uint64
writeCapsuleReceiveParseNanos atomic.Uint64
r2tDataCollectionOps atomic.Uint64
r2tDataCollectionNanos atomic.Uint64
writeDispatchWaitOps atomic.Uint64
writeDispatchWaitNanos atomic.Uint64
writeHandlerOps atomic.Uint64
writeHandlerNanos atomic.Uint64
writeCompletionQueueWaitOps atomic.Uint64
writeCompletionQueueWaitNanos atomic.Uint64
writeCompletionSendOps atomic.Uint64
writeCompletionSendNanos atomic.Uint64
}
func (s *targetStats) snapshot() Stats {
@@ -52,19 +85,38 @@ func (s *targetStats) snapshot() Stats {
return Stats{}
}
return Stats{
SessionsAccepted: s.sessionsAccepted.Load(),
AdminConnects: s.adminConnects.Load(),
IOConnects: s.ioConnects.Load(),
ReadCommands: s.readCommands.Load(),
WriteCommands: s.writeCommands.Load(),
FlushCommands: s.flushCommands.Load(),
InlineWriteCommands: s.inlineWriteCommands.Load(),
InlineWriteBytes: s.inlineWriteBytes.Load(),
R2TWriteCommands: s.r2tWriteCommands.Load(),
R2TWriteBytes: s.r2tWriteBytes.Load(),
H2CDataPDUs: s.h2cDataPDUs.Load(),
H2CDataBytes: s.h2cDataBytes.Load(),
C2HDataPDUs: s.c2hDataPDUs.Load(),
C2HDataBytes: s.c2hDataBytes.Load(),
SessionsAccepted: s.sessionsAccepted.Load(),
AdminConnects: s.adminConnects.Load(),
IOConnects: s.ioConnects.Load(),
ReadCommands: s.readCommands.Load(),
WriteCommands: s.writeCommands.Load(),
FlushCommands: s.flushCommands.Load(),
InlineWriteCommands: s.inlineWriteCommands.Load(),
InlineWriteBytes: s.inlineWriteBytes.Load(),
R2TWriteCommands: s.r2tWriteCommands.Load(),
R2TWriteBytes: s.r2tWriteBytes.Load(),
H2CDataPDUs: s.h2cDataPDUs.Load(),
H2CDataBytes: s.h2cDataBytes.Load(),
C2HDataPDUs: s.c2hDataPDUs.Load(),
C2HDataBytes: s.c2hDataBytes.Load(),
WriteCapsuleReceiveParseOps: s.writeCapsuleReceiveParseOps.Load(),
WriteCapsuleReceiveParseNanos: s.writeCapsuleReceiveParseNanos.Load(),
R2TDataCollectionOps: s.r2tDataCollectionOps.Load(),
R2TDataCollectionNanos: s.r2tDataCollectionNanos.Load(),
WriteDispatchWaitOps: s.writeDispatchWaitOps.Load(),
WriteDispatchWaitNanos: s.writeDispatchWaitNanos.Load(),
WriteHandlerOps: s.writeHandlerOps.Load(),
WriteHandlerNanos: s.writeHandlerNanos.Load(),
WriteCompletionQueueWaitOps: s.writeCompletionQueueWaitOps.Load(),
WriteCompletionQueueWaitNanos: s.writeCompletionQueueWaitNanos.Load(),
WriteCompletionSendOps: s.writeCompletionSendOps.Load(),
WriteCompletionSendNanos: s.writeCompletionSendNanos.Load(),
}
}
func statsDurationNanos(d time.Duration) uint64 {
if d <= 0 {
return 0
}
return uint64(d.Nanoseconds())
}
+35 -1
View File
@@ -2,6 +2,7 @@ package nvme_test
import (
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend"
"github.com/seaweedfs/seaweed-block/core/frontend/nvme"
@@ -45,7 +46,7 @@ func TestTargetStats_RecordInlineAndR2TWrites(t *testing.T) {
status = writeChunkedOnClient(t, cli, 1, 2, r2tPayload, 2)
expectStatusSuccess(t, status, "R2T Write")
st := tg.Stats()
st := waitForWritePhaseStats(t, tg, 2)
if st.AdminConnects != 1 || st.IOConnects != 1 {
t.Fatalf("connect stats admin=%d io=%d want 1/1", st.AdminConnects, st.IOConnects)
}
@@ -64,6 +65,39 @@ func TestTargetStats_RecordInlineAndR2TWrites(t *testing.T) {
t.Fatalf("h2c stats pdus=%d bytes=%d want 2/%d",
st.H2CDataPDUs, st.H2CDataBytes, len(r2tPayload))
}
for name, got := range map[string]uint64{
"write capsule receive/parse": st.WriteCapsuleReceiveParseOps,
"write dispatch wait": st.WriteDispatchWaitOps,
"write handler": st.WriteHandlerOps,
"write completion queue wait": st.WriteCompletionQueueWaitOps,
"write completion send": st.WriteCompletionSendOps,
} {
if got != 2 {
t.Fatalf("%s ops=%d want 2", name, got)
}
}
if st.R2TDataCollectionOps != 1 {
t.Fatalf("R2T data collection ops=%d want 1", st.R2TDataCollectionOps)
}
}
func waitForWritePhaseStats(t *testing.T, target *nvme.Target, want uint64) nvme.Stats {
t.Helper()
deadline := time.Now().Add(time.Second)
for {
stats := target.Stats()
if stats.WriteCapsuleReceiveParseOps >= want &&
stats.WriteDispatchWaitOps >= want &&
stats.WriteHandlerOps >= want &&
stats.WriteCompletionQueueWaitOps >= want &&
stats.WriteCompletionSendOps >= want {
return stats
}
if time.Now().After(deadline) {
t.Fatalf("write phase stats did not reach %d: %+v", want, stats)
}
time.Sleep(time.Millisecond)
}
}
func TestTargetStats_RecordReadAndFlush(t *testing.T) {
@@ -13,6 +13,7 @@ import (
"github.com/seaweedfs/seaweed-block/core/engine"
"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/replication"
)
@@ -40,6 +41,10 @@ import (
// -> 400 (missing volume query param)
// -> 403 (non-loopback client)
//
// GET /status/nvme?volume=<id>
// -> 200 JSON read-only NVMe target counters (when a TCP target is wired)
// -> 404 (wrong volume or no TCP source)
//
// The server binds on a caller-supplied addr (":0" for tests);
// the actual bound addr is available via Addr() after Start.
type StatusServer struct {
@@ -54,6 +59,7 @@ type StatusServer struct {
allowExternal bool
peerSource peerStatusSource
durableSource durableStatusSource
nvmeSource nvmeStatusSource
runtimeSource runtimeRecoverySource
frontendCaps []FrontendTransportCapability
}
@@ -66,6 +72,10 @@ type durableStatusSource interface {
DurableStatuses() []durable.VolumeStatus
}
type nvmeStatusSource interface {
Stats() nvme.Stats
}
type runtimeRecoverySource interface {
StartRuntimeRecovery(context.Context, replication.RuntimeRecoveryRequest) error
RuntimeRecoveryStatus(context.Context, replication.RuntimeRecoveryRequest) (replication.RuntimeRecoveryStatus, error)
@@ -122,6 +132,11 @@ type FrontendCapabilitiesStatus struct {
FrontendTransports []FrontendTransportCapability `json:"frontendTransports"`
}
type NVMeStatus struct {
VolumeID string `json:"volumeID"`
Stats nvme.Stats `json:"stats"`
}
const (
AuthorityRolePrimary = "primary"
AuthorityRoleSuperseded = "superseded"
@@ -208,6 +223,14 @@ func (s *StatusServer) SetDurableStatusSource(src durableStatusSource) {
s.durableSource = src
}
// SetNVMeStatusSource enables /status/nvme with a read-only target snapshot.
// It may be called before or after Start.
func (s *StatusServer) SetNVMeStatusSource(src nvmeStatusSource) {
s.mu.Lock()
defer s.mu.Unlock()
s.nvmeSource = src
}
func (s *StatusServer) SetRuntimeRecoverySource(src runtimeRecoverySource) {
s.mu.Lock()
defer s.mu.Unlock()
@@ -251,6 +274,7 @@ func (s *StatusServer) Start(addr string) (string, error) {
mux.HandleFunc("/status", s.handleStatus)
mux.HandleFunc("/status/peers", s.handleStatusPeers)
mux.HandleFunc("/status/durable", s.handleStatusDurable)
mux.HandleFunc("/status/nvme", s.handleStatusNVMe)
mux.HandleFunc("/status/frontend-capabilities", s.handleFrontendCapabilities)
if s.recoveryEnabled {
mux.HandleFunc("/status/recovery", s.handleStatusRecovery)
@@ -335,6 +359,32 @@ func (s *StatusServer) handleFrontendCapabilities(w http.ResponseWriter, r *http
})
}
func (s *StatusServer) handleStatusNVMe(w http.ResponseWriter, r *http.Request) {
if !s.externalAccessAllowed() && !isLoopbackRemote(r.RemoteAddr) {
http.Error(w, "status endpoint restricted to loopback", http.StatusForbidden)
return
}
vol := r.URL.Query().Get("volume")
if vol == "" {
http.Error(w, "missing volume query param", http.StatusBadRequest)
return
}
p := s.statusProjection()
if p.VolumeID != vol {
http.Error(w, fmt.Sprintf("volume %q not served by this host (serves %q)", vol, p.VolumeID), http.StatusNotFound)
return
}
s.mu.Lock()
src := s.nvmeSource
s.mu.Unlock()
if src == nil {
http.Error(w, "NVMe status source unavailable", http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(NVMeStatus{VolumeID: p.VolumeID, Stats: src.Stats()})
}
func (s *StatusServer) statusProjection() StatusProjection {
p, superseded := s.view.projectionWithSupersede()
ep := s.view.EngineProjection()
@@ -16,6 +16,7 @@ import (
"github.com/seaweedfs/seaweed-block/core/adapter"
"github.com/seaweedfs/seaweed-block/core/engine"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
"github.com/seaweedfs/seaweed-block/core/frontend/nvme"
"github.com/seaweedfs/seaweed-block/core/replication"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
)
@@ -131,6 +132,55 @@ func TestStatusServer_FrontendCapabilitiesReportsTransportBoundary(t *testing.T)
}
}
type stubNVMeStatusSource struct {
stats nvme.Stats
}
func (s stubNVMeStatusSource) Stats() nvme.Stats { return s.stats }
func TestStatusServer_NVMeStatusEndpoint(t *testing.T) {
s := NewStatusServer(NewAdapterProjectionView(stubProjector{}, "v1", "r1", nil))
addr, err := s.Start("127.0.0.1:0")
if err != nil {
t.Fatalf("start: %v", err)
}
defer func() { _ = s.Close(context.Background()) }()
resp, err := http.Get("http://" + addr + "/status/nvme?volume=v1")
if err != nil {
t.Fatalf("get without source: %v", err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusNotFound {
t.Fatalf("status without source=%d want 404", resp.StatusCode)
}
s.SetNVMeStatusSource(stubNVMeStatusSource{stats: nvme.Stats{
WriteCommands: 17,
R2TWriteCommands: 17,
WriteCapsuleReceiveParseOps: 17,
WriteHandlerOps: 17,
WriteCompletionSendOps: 17,
}})
resp, err = http.Get("http://" + addr + "/status/nvme?volume=v1")
if err != nil {
t.Fatalf("get with source: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Fatalf("status with source=%d want 200", resp.StatusCode)
}
var body NVMeStatus
if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
t.Fatalf("decode: %v", err)
}
if body.VolumeID != "v1" || body.Stats.WriteCommands != 17 ||
body.Stats.R2TWriteCommands != 17 || body.Stats.WriteCapsuleReceiveParseOps != 17 ||
body.Stats.WriteHandlerOps != 17 || body.Stats.WriteCompletionSendOps != 17 {
t.Fatalf("unexpected NVMe status: %+v", body)
}
}
func TestNodeLoss_StatusServer_ExternalBindPolicyRequiresConcreteHost(t *testing.T) {
if err := enforceExplicitExternalBind("10.0.0.12:23260"); err != nil {
t.Fatalf("concrete node address rejected: %v", err)
@@ -0,0 +1,834 @@
package replication
import (
"bytes"
"context"
"encoding/binary"
"encoding/json"
"fmt"
"io"
"log"
"os"
"path/filepath"
"runtime"
"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/storage"
"github.com/seaweedfs/seaweed-block/core/transport"
)
const (
phase174LayerEnv = "SW_BLOCK_PHASE174_LAYER"
phase174WritersEnv = "SW_BLOCK_PHASE174_WRITERS"
phase174RunEnv = "SW_BLOCK_PHASE174_RUN"
phase174SetEnv = "SW_BLOCK_PHASE174_SET"
phase174StoreDirEnv = "SW_BLOCK_PHASE174_STORE_DIR"
phase174BlockSize = 4096
phase174NumBlocks = 65536
phase174RegionBlocks = phase174NumBlocks / 2
phase174APIOperations = 16384
phase174WarmupOperations = 1024
phase174Runs = 5
)
type phase174Layer string
const (
phase174DirectWALStore phase174Layer = "direct_walstore"
phase174AdapterRF1 phase174Layer = "adapter_rf1"
phase174RF3TCP phase174Layer = "rf3_tcp"
)
type phase174FixedWorkResult 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"`
FinalSyncNanos int64 `json:"final_sync_ns"`
CloseRecoverNanos int64 `json:"close_recover_ns"`
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"`
PrimaryAppendWaitNanos uint64 `json:"primary_wal_append_lock_wait_ns"`
PrimaryCommitWaitNanos uint64 `json:"primary_commit_lock_wait_ns"`
PrimaryDirtyMapNanos uint64 `json:"primary_dirty_map_ns"`
AdapterRequestOps uint64 `json:"adapter_request_ops,omitempty"`
AdapterRequestBytes uint64 `json:"adapter_request_bytes,omitempty"`
AdapterWriteOps uint64 `json:"adapter_write_ops,omitempty"`
AdapterWriteBytes uint64 `json:"adapter_write_bytes,omitempty"`
AdapterWriteNanos uint64 `json:"adapter_write_ns,omitempty"`
AdapterStorageCalls uint64 `json:"adapter_storage_write_calls,omitempty"`
AdapterStorageBlocks uint64 `json:"adapter_storage_write_blocks,omitempty"`
FlusherCycles uint64 `json:"foreground_flusher_cycles"`
FlusherCycleNanos uint64 `json:"foreground_flusher_cycle_ns"`
FlusherExtentWriteOps uint64 `json:"foreground_flusher_extent_write_ops"`
FlusherExtentWriteNanos uint64 `json:"foreground_flusher_extent_write_ns"`
FlusherExtentSyncOps uint64 `json:"foreground_flusher_extent_sync_ops"`
FlusherExtentSyncNanos uint64 `json:"foreground_flusher_extent_sync_ns"`
PrimaryStableLSN uint64 `json:"primary_stable_lsn"`
PrimaryHeadLSN uint64 `json:"primary_head_lsn"`
ReplicationWrites uint64 `json:"replication_write_ops,omitempty"`
ReplicationFanoutNanos uint64 `json:"replication_fanout_ns,omitempty"`
ReplicationAckWaitNanos uint64 `json:"replication_ack_wait_ns,omitempty"`
PeerQueueMaxDepth uint64 `json:"peer_queue_max_depth,omitempty"`
PeerQueueSaturated uint64 `json:"peer_queue_saturated,omitempty"`
PostMeasurementDrain bool `json:"post_measurement_sync_all"`
PostMeasurementDrainNS int64 `json:"post_measurement_sync_all_ns,omitempty"`
PostMeasurementRecovery bool `json:"post_measurement_recovery"`
ReplicaProbeCount int `json:"replica_probe_count,omitempty"`
ReplicaCatchUpCount int `json:"replica_catchup_count,omitempty"`
ReplicaRebuildCount int `json:"replica_rebuild_count,omitempty"`
MaxReplicaLagLSN uint64 `json:"max_replica_lag_lsn,omitempty"`
RemoteReplicaEvidence bool `json:"remote_replica_evidence_required"`
ReplicaCount int `json:"replica_count"`
ReplicaDurableCount int `json:"replica_durable_count"`
ReplicaFrontiersEqual bool `json:"replica_frontiers_equal"`
FlusherPhaseReset bool `json:"flusher_phase_reset"`
CloseRecoverComplete bool `json:"close_recover_complete"`
CorrectnessSamples int `json:"correctness_samples"`
}
type phase174HealthyView struct {
projection frontend.Projection
}
func (v *phase174HealthyView) Projection() frontend.Projection {
return v.projection
}
type phase174Pipeline struct {
layer phase174Layer
primaryPath string
replicaPaths []string
primary *storage.WALStore
replicas []*storage.WALStore
backend *durable.StorageBackend
replication *ReplicationVolume
listeners []*transport.ReplicaListener
configuredReplicas int
remoteReplicas bool
closed bool
}
type phase174RecoveryEvidence struct {
probeCount int
catchUpCount int
rebuildCount int
maxLagLSN uint64
}
type phase174RecoveryKind string
const (
phase174RecoveryNone phase174RecoveryKind = "none"
phase174RecoveryCatchUp phase174RecoveryKind = "catch_up"
phase174RecoveryRebuild phase174RecoveryKind = "rebuild"
)
func TestPhase174FixedWorkContract(t *testing.T) {
for _, layer := range []phase174Layer{phase174DirectWALStore, phase174AdapterRF1, phase174RF3TCP} {
if _, _, err := phase174LayerContract(layer); err != nil {
t.Fatalf("layer %q: %v", layer, err)
}
}
for _, writers := range []int{1, 4, 8} {
if err := phase174ValidateWriters(writers); err != nil {
t.Fatal(err)
}
seen := make(map[uint32]struct{}, phase174APIOperations)
for operation := 0; operation < phase174APIOperations; operation++ {
lba := phase174OperationLBA(operation, 0)
if _, exists := seen[lba]; exists {
t.Fatalf("writers=%d duplicate measured LBA %d", writers, lba)
}
seen[lba] = struct{}{}
}
}
if _, _, err := phase174LayerContract("unknown"); err == nil {
t.Fatal("unknown layer accepted")
}
if err := phase174ValidateWriters(3); err == nil {
t.Fatal("writers=3 accepted")
}
for _, tc := range []struct {
name string
replicaR uint64
primaryS uint64
primaryH uint64
want phase174RecoveryKind
}{
{name: "current", replicaR: 100, primaryS: 50, primaryH: 100, want: phase174RecoveryNone},
{name: "retained", replicaR: 75, primaryS: 50, primaryH: 100, want: phase174RecoveryCatchUp},
{name: "recycled", replicaR: 49, primaryS: 50, primaryH: 100, want: phase174RecoveryRebuild},
} {
t.Run("recovery_"+tc.name, func(t *testing.T) {
if got := phase174RecoveryKindFor(tc.replicaR, tc.primaryS, tc.primaryH); got != tc.want {
t.Fatalf("kind=%s want %s", got, tc.want)
}
})
}
}
func TestPhase174FixedWorkPipeline(t *testing.T) {
storeRoot := os.Getenv(phase174StoreDirEnv)
if storeRoot == "" {
t.Skip("formal fixed-work run requires " + phase174StoreDirEnv)
}
layer := phase174Layer(os.Getenv(phase174LayerEnv))
if _, _, err := phase174LayerContract(layer); err != nil {
t.Fatal(err)
}
writers, err := strconv.Atoi(os.Getenv(phase174WritersEnv))
if err != nil {
t.Fatalf("parse %s: %v", phase174WritersEnv, err)
}
if err := phase174ValidateWriters(writers); err != nil {
t.Fatal(err)
}
run, err := strconv.Atoi(os.Getenv(phase174RunEnv))
if err != nil || run < 0 || run > phase174Runs {
t.Fatalf("%s must be in [0,%d]", phase174RunEnv, phase174Runs)
}
set, err := strconv.Atoi(os.Getenv(phase174SetEnv))
if err != nil || set < 1 || set > 2 {
t.Fatalf("%s must be 1 or 2", phase174SetEnv)
}
if os.Getenv(phase174RemoteReplicasEnv) != "" {
peerSessionIDCounter.Store(phase174RemoteSessionBase(set, run, writers))
}
oldLogWriter := log.Writer()
if os.Getenv("SW_BLOCK_BENCH_VERBOSE") == "" {
log.SetOutput(io.Discard)
defer log.SetOutput(oldLogWriter)
}
groupDir := filepath.Join(storeRoot, fmt.Sprintf("set%d-%s-writers%d", set, layer, writers))
create := run == 0
if layer == phase174RF3TCP && os.Getenv(phase174RemoteReplicasEnv) == "" {
// Same-host durable RF3 is diagnostic: sync-quorum may let one peer
// lag, so every sample needs independent stores rather than inheriting
// an intentionally incomplete replica from the previous sample.
groupDir = filepath.Join(groupDir, fmt.Sprintf("run%d", run))
create = true
}
if create {
for _, name := range []string{"primary.store", "replica-1.store", "replica-2.store"} {
if err := os.Remove(filepath.Join(groupDir, name)); err != nil && !os.IsNotExist(err) {
t.Fatal(err)
}
}
}
if err := os.MkdirAll(groupDir, 0o755); err != nil {
t.Fatal(err)
}
pipeline := newPhase174Pipeline(t, layer, groupDir, create)
result := runPhase174FixedWork(t, pipeline, set, run, writers)
if run == 0 {
return
}
encoded, err := json.Marshal(result)
if err != nil {
t.Fatal(err)
}
fmt.Printf("phase174_fixed_work_result=%s\n", encoded)
}
func phase174ValidateWriters(writers int) error {
switch writers {
case 1, 4, 8:
return nil
default:
return fmt.Errorf("phase174: writers=%d want one of 1,4,8", writers)
}
}
func phase174LayerContract(layer phase174Layer) (scope, ackProfile string, err error) {
switch layer {
case phase174DirectWALStore:
return "walstore_engine", "local_durable", nil
case phase174AdapterRF1:
return "durable_adapter", "local_durable", nil
case phase174RF3TCP:
return "durable_adapter_replication_real_tcp", "sync_quorum_rf3", nil
default:
return "", "", fmt.Errorf("phase174: unsupported layer %q", layer)
}
}
func newPhase174Pipeline(t *testing.T, layer phase174Layer, dir string, create bool) *phase174Pipeline {
t.Helper()
p := &phase174Pipeline{
layer: layer,
primaryPath: filepath.Join(dir, "primary.store"),
}
p.primary = phase174OpenWALStore(t, p.primaryPath, create)
if layer != phase174DirectWALStore {
id := frontend.Identity{VolumeID: "phase174", ReplicaID: "primary", Epoch: 1, EndpointVersion: 1}
view := &phase174HealthyView{projection: frontend.Projection{
VolumeID: id.VolumeID, ReplicaID: id.ReplicaID, Epoch: id.Epoch,
EndpointVersion: id.EndpointVersion, Healthy: true,
}}
p.backend = durable.NewStorageBackend(p.primary, view, id)
p.backend.SetOperational(true, "phase174 fixed-work")
}
if layer == phase174RF3TCP {
p.replication = NewReplicationVolume("phase174", p.primary)
p.replication.SetDurabilityMode(DurabilitySyncQuorum)
targets, err := phase174RemoteReplicaTargets()
if err != nil {
t.Fatal(err)
}
if len(targets) > 0 {
p.remoteReplicas = true
} else {
targets = make([]ReplicaTarget, 0, 2)
for replica := 1; replica <= 2; replica++ {
path := filepath.Join(dir, fmt.Sprintf("replica-%d.store", replica))
store := phase174OpenWALStore(t, path, create)
listener, err := transport.NewReplicaListener("127.0.0.1:0", store)
if err != nil {
t.Fatal(err)
}
listener.Serve()
p.replicaPaths = append(p.replicaPaths, path)
p.replicas = append(p.replicas, store)
p.listeners = append(p.listeners, listener)
targets = append(targets, ReplicaTarget{
ReplicaID: fmt.Sprintf("r%d", replica), DataAddr: listener.Addr(),
ControlAddr: listener.Addr(), Epoch: 1, EndpointVersion: 1,
})
}
}
p.configuredReplicas = len(targets)
if err := p.replication.UpdateReplicaSet(1, targets); err != nil {
t.Fatal(err)
}
p.backend.SetWriteObserver(p.replication)
p.backend.SetWriteAckPolicy(durable.WriteAckRequireObserverAck)
}
t.Cleanup(func() { _ = p.close() })
return p
}
func phase174OpenWALStore(t *testing.T, path string, create bool) *storage.WALStore {
t.Helper()
var (
store *storage.WALStore
err error
)
if create {
store, err = storage.CreateWALStore(path, phase174NumBlocks, phase174BlockSize)
} else {
store, err = storage.OpenWALStore(path)
}
if err != nil {
t.Fatal(err)
}
if !create {
if _, err := store.Recover(); err != nil {
_ = store.Close()
t.Fatal(err)
}
}
return store
}
func runPhase174FixedWork(t *testing.T, p *phase174Pipeline, set, run, writers int) phase174FixedWorkResult {
t.Helper()
warmupPayloads := phase174Payloads(phase174WarmupOperations, set, run, 0x1740)
if _, _, err := phase174RunWrites(p, writers, phase174RegionBlocks, warmupPayloads, false); err != nil {
t.Fatalf("warmup writes: %v", err)
}
if err := p.sync(context.Background()); err != nil {
t.Fatalf("warmup sync: %v", err)
}
if reached := p.waitForReplicaFrontier(time.Second); len(p.replicas) > 0 && reached < 1 {
t.Fatal("no replica reached warmup frontier")
}
runtime.GC()
time.Sleep(100 * time.Millisecond)
flusherPhaseReset, err := p.resetFlushersForMeasurement()
if err != nil {
t.Fatalf("reset flusher phase: %v", err)
}
writeBefore := p.primary.WriteInstrumentation()
flusherBefore := p.primary.FlusherInstrumentation()
adapterBefore := p.adapterProfile()
replicationBefore := p.replicationStats()
payloads := phase174Payloads(phase174APIOperations, set, run, 0x1741)
foreground, latencies, err := phase174RunWrites(p, writers, 0, payloads, true)
if err != nil {
t.Fatalf("measured writes: %v", err)
}
writeForeground := p.primary.WriteInstrumentation()
flusherForeground := p.primary.FlusherInstrumentation()
adapterForeground := p.adapterProfile()
syncStart := time.Now()
if err := p.sync(context.Background()); err != nil {
t.Fatalf("final sync: %v", err)
}
finalSync := time.Since(syncStart)
if reached := p.waitForReplicaFrontier(2 * time.Second); len(p.replicas) > 0 && reached < 1 {
t.Fatalf("no replica reached final frontier")
}
var postMeasurementDrain time.Duration
var recoveryEvidence phase174RecoveryEvidence
if p.remoteReplicas {
drainStart := time.Now()
_, _, targetLSN := p.primary.Boundaries()
recoveryEvidence, err = p.recoverRemoteReplicas(context.Background(), set, run, writers, targetLSN)
if err != nil {
t.Fatalf("post-measurement replica recovery: %v", err)
}
p.replication.SetDurabilityMode(DurabilitySyncAll)
if err := p.sync(context.Background()); err != nil {
t.Fatalf("post-measurement sync-all: %v", err)
}
postMeasurementDrain = time.Since(drainStart)
}
writeAfter := p.primary.WriteInstrumentation()
replicationAfter := p.replicationStats()
if got := writeAfter.WALEncodeOps - writeBefore.WALEncodeOps; got != phase174APIOperations {
t.Fatalf("primary WAL writes=%d want %d", got, phase174APIOperations)
}
if p.replication != nil && replicationAfter.WriteOps-replicationBefore.WriteOps != phase174APIOperations {
t.Fatalf("replication writes=%d want %d", replicationAfter.WriteOps-replicationBefore.WriteOps, phase174APIOperations)
}
closeStart := time.Now()
if err := p.close(); err != nil {
t.Fatal(err)
}
primaryR, primaryH, durableReplicas, replicasEqual, correctness := phase174RecoverAndVerify(
t, p.primaryPath, p.replicaPaths, payloads,
)
closeRecover := time.Since(closeStart)
if primaryR != primaryH {
t.Fatalf("recovered primary stable=%d head=%d", primaryR, primaryH)
}
scope, ackProfile, err := phase174LayerContract(p.layer)
if err != nil {
t.Fatal(err)
}
logicalBytes := uint64(phase174APIOperations * phase174BlockSize)
p50, p95, p99 := phase174Percentiles(latencies)
result := phase174FixedWorkResult{
Contract: "phase174-fixed-work-v1", Layer: string(p.layer), Scope: scope,
AckProfile: ackProfile, Set: set, Run: run, Writers: writers,
APIOperations: phase174APIOperations, LogicalBytes: logicalBytes,
ForegroundNanos: foreground.Nanoseconds(),
MiBPerSecond: (float64(logicalBytes) / (1024 * 1024)) / foreground.Seconds(),
P50Nanos: p50, P95Nanos: p95, P99Nanos: p99,
FinalSyncNanos: finalSync.Nanoseconds(), CloseRecoverNanos: closeRecover.Nanoseconds(),
PrimaryWALWrites: writeAfter.WALEncodeOps - writeBefore.WALEncodeOps,
PrimaryWALCopyNanos: writeForeground.WALCopyDurationNanos - writeBefore.WALCopyDurationNanos,
PrimaryWALEncodeNanos: writeForeground.WALEncodeDurationNanos - writeBefore.WALEncodeDurationNanos,
PrimaryWALChecksumNanos: writeForeground.WALChecksumDurationNanos - writeBefore.WALChecksumDurationNanos,
PrimaryWALAppendNanos: writeForeground.WALAppendDurationNanos - writeBefore.WALAppendDurationNanos,
PrimaryAppendWaitNanos: writeForeground.WALAppendLockWaitNanos - writeBefore.WALAppendLockWaitNanos,
PrimaryCommitWaitNanos: writeForeground.WriteCommitLockWaitNanos - writeBefore.WriteCommitLockWaitNanos,
PrimaryDirtyMapNanos: writeForeground.DirtyMapUpdateDurationNanos - writeBefore.DirtyMapUpdateDurationNanos,
AdapterRequestOps: adapterForeground.BackendWriteRequestOps - adapterBefore.BackendWriteRequestOps,
AdapterRequestBytes: adapterForeground.BackendWriteRequestBytes - adapterBefore.BackendWriteRequestBytes,
AdapterWriteOps: adapterForeground.BackendWriteOps - adapterBefore.BackendWriteOps,
AdapterWriteBytes: adapterForeground.BackendWriteBytes - adapterBefore.BackendWriteBytes,
AdapterWriteNanos: adapterForeground.BackendWriteDurationNanos - adapterBefore.BackendWriteDurationNanos,
AdapterStorageCalls: adapterForeground.BackendStorageWriteCalls - adapterBefore.BackendStorageWriteCalls,
AdapterStorageBlocks: adapterForeground.BackendStorageWriteBlocks - adapterBefore.BackendStorageWriteBlocks,
FlusherCycles: flusherForeground.CyclesStarted - flusherBefore.CyclesStarted,
FlusherCycleNanos: flusherForeground.CycleDurationNanos - flusherBefore.CycleDurationNanos,
FlusherExtentWriteOps: flusherForeground.ExtentWriteOps - flusherBefore.ExtentWriteOps,
FlusherExtentWriteNanos: flusherForeground.ExtentWriteDurationNanos - flusherBefore.ExtentWriteDurationNanos,
FlusherExtentSyncOps: flusherForeground.ExtentSyncOps - flusherBefore.ExtentSyncOps,
FlusherExtentSyncNanos: flusherForeground.ExtentSyncDurationNanos - flusherBefore.ExtentSyncDurationNanos,
PrimaryStableLSN: primaryR, PrimaryHeadLSN: primaryH,
PostMeasurementDrain: p.remoteReplicas, PostMeasurementDrainNS: postMeasurementDrain.Nanoseconds(),
PostMeasurementRecovery: p.remoteReplicas,
ReplicaProbeCount: recoveryEvidence.probeCount,
ReplicaCatchUpCount: recoveryEvidence.catchUpCount,
ReplicaRebuildCount: recoveryEvidence.rebuildCount,
MaxReplicaLagLSN: recoveryEvidence.maxLagLSN,
RemoteReplicaEvidence: p.remoteReplicas,
ReplicaCount: p.configuredReplicas, ReplicaDurableCount: durableReplicas,
ReplicaFrontiersEqual: replicasEqual,
FlusherPhaseReset: flusherPhaseReset,
CloseRecoverComplete: true, CorrectnessSamples: correctness,
}
if p.replication != nil {
result.ReplicationWrites = replicationAfter.WriteOps - replicationBefore.WriteOps
result.ReplicationFanoutNanos = replicationAfter.WriteFanoutNanos - replicationBefore.WriteFanoutNanos
result.ReplicationAckWaitNanos = replicationAfter.WriteAckWaitNanos - replicationBefore.WriteAckWaitNanos
result.PeerQueueMaxDepth = replicationAfter.PeerQueueMaxDepth
result.PeerQueueSaturated = replicationAfter.PeerQueueSaturated - replicationBefore.PeerQueueSaturated
}
return result
}
func phase174RunWrites(
p *phase174Pipeline,
writers int,
base uint32,
payloads [][]byte,
measureLatency bool,
) (time.Duration, []int64, error) {
latencies := make([]int64, len(payloads))
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()
start := make(chan struct{})
var wg sync.WaitGroup
var firstErr error
var errOnce sync.Once
wallStart := time.Now()
for worker := 0; worker < writers; worker++ {
wg.Add(1)
go func(worker int) {
defer wg.Done()
<-start
for operation := worker; operation < len(payloads); operation += writers {
opStart := time.Now()
lba := phase174OperationLBA(operation, base)
var err error
if p.backend == nil {
_, err = p.primary.Write(lba, payloads[operation])
} else {
_, err = p.backend.Write(ctx, int64(lba*phase174BlockSize), payloads[operation])
}
if measureLatency {
latencies[operation] = time.Since(opStart).Nanoseconds()
}
if err != nil {
errOnce.Do(func() { firstErr = err })
return
}
}
}(worker)
}
close(start)
wg.Wait()
return time.Since(wallStart), latencies, firstErr
}
func (p *phase174Pipeline) sync(ctx context.Context) error {
if p.backend != nil {
return p.backend.Sync(ctx)
}
_, err := p.primary.Sync()
return err
}
func phase174RemoteSessionBase(set, run, writers int) uint64 {
return 1_740_000_000 + uint64(set)*100_000_000 + uint64(writers)*1_000_000 + uint64(run)*1_000
}
func phase174RecoveryKindFor(replicaR, primaryS, primaryH uint64) phase174RecoveryKind {
if replicaR >= primaryH {
return phase174RecoveryNone
}
if replicaR < primaryS {
return phase174RecoveryRebuild
}
return phase174RecoveryCatchUp
}
func (p *phase174Pipeline) recoverRemoteReplicas(
ctx context.Context,
set, run, writers int,
targetLSN uint64,
) (phase174RecoveryEvidence, error) {
var evidence phase174RecoveryEvidence
if p.replication == nil || !p.remoteReplicas {
return evidence, nil
}
p.replication.mu.Lock()
peers := make([]*ReplicaPeer, 0, len(p.replication.peers))
for _, peer := range p.replication.peers {
peers = append(peers, peer)
}
p.replication.mu.Unlock()
sort.Slice(peers, func(i, j int) bool {
return peers[i].Target().ReplicaID < peers[j].Target().ReplicaID
})
for index := range peers {
peer := peers[index]
target := peer.Target()
sessionBase := phase174RemoteSessionBase(set, run, writers) + 100 + uint64(index)*10
probe := peer.Executor().Probe(
target.ReplicaID, target.DataAddr, target.ControlAddr,
sessionBase, target.Epoch, target.EndpointVersion,
)
if !probe.Success {
return evidence, fmt.Errorf("probe peer %s: %s", target.ReplicaID, probe.FailReason)
}
evidence.probeCount++
if probe.ReplicaFlushedLSN > targetLSN {
return evidence, fmt.Errorf("probe peer %s frontier %d exceeds primary target %d",
target.ReplicaID, probe.ReplicaFlushedLSN, targetLSN)
}
lag := targetLSN - probe.ReplicaFlushedLSN
if lag > evidence.maxLagLSN {
evidence.maxLagLSN = lag
}
completedSessionID := sessionBase
achievedLSN := probe.ReplicaFlushedLSN
if lag > 0 {
completedSessionID++
peer.SetState(ReplicaCatchingUp)
req := RuntimeRecoveryRequest{
ReplicaID: target.ReplicaID,
TargetDataAddr: target.DataAddr,
SessionID: completedSessionID,
Epoch: target.Epoch,
EndpointVersion: target.EndpointVersion,
FrontierHintLSN: targetLSN,
}
if phase174RecoveryKindFor(probe.ReplicaFlushedLSN, probe.PrimaryTailLSN, targetLSN) == phase174RecoveryRebuild {
evidence.rebuildCount++
} else {
req.FromLSN = probe.ReplicaFlushedLSN + 1
evidence.catchUpCount++
}
if err := p.replication.StartRuntimeRecovery(ctx, req); err != nil {
peer.Invalidate("phase174 recovery start failed: " + err.Error())
return evidence, fmt.Errorf("start recovery peer %s: %w", target.ReplicaID, err)
}
deadline := time.Now().Add(2 * time.Minute)
for {
status, err := p.replication.RuntimeRecoveryStatus(ctx, req)
if err != nil {
return evidence, fmt.Errorf("recovery status peer %s: %w", target.ReplicaID, err)
}
if status.State == "caught_up" {
achievedLSN = status.AchievedLSN
break
}
if status.State == "failed" {
peer.Invalidate("phase174 recovery failed: " + status.FailReason)
return evidence, fmt.Errorf("recovery peer %s failed kind=%s reason=%s",
target.ReplicaID, status.FailureKind, status.FailReason)
}
if time.Now().After(deadline) {
return evidence, fmt.Errorf("recovery peer %s timed out", target.ReplicaID)
}
select {
case <-ctx.Done():
return evidence, ctx.Err()
case <-time.After(10 * time.Millisecond):
}
}
}
if achievedLSN < targetLSN {
return evidence, fmt.Errorf("peer %s achieved %d below target %d",
target.ReplicaID, achievedLSN, targetLSN)
}
if err := peer.RefreshLiveShipSessionAfter(completedSessionID, achievedLSN, "phase174 recovery completed"); err != nil {
peer.Invalidate("phase174 live session refresh failed: " + err.Error())
return evidence, fmt.Errorf("refresh live session peer %s: %w", target.ReplicaID, err)
}
peer.SetState(ReplicaHealthy)
}
return evidence, nil
}
func (p *phase174Pipeline) replicationStats() VolumeStats {
if p.replication == nil {
return VolumeStats{}
}
return p.replication.Stats()
}
func (p *phase174Pipeline) adapterProfile() durable.WriteProfileStatus {
if p.backend == nil {
return durable.WriteProfileStatus{}
}
return p.backend.WriteProfile()
}
type phase174FlusherResetter interface {
ResetFlusherForMeasurement() error
}
func (p *phase174Pipeline) resetFlushersForMeasurement() (bool, error) {
stores := make([]*storage.WALStore, 0, 1+len(p.replicas))
stores = append(stores, p.primary)
stores = append(stores, p.replicas...)
for _, store := range stores {
resetter, ok := any(store).(phase174FlusherResetter)
if !ok {
return false, nil
}
if err := resetter.ResetFlusherForMeasurement(); err != nil {
return false, err
}
}
return true, nil
}
func (p *phase174Pipeline) waitForReplicaFrontier(timeout time.Duration) int {
if len(p.replicas) == 0 {
return 0
}
_, _, want := p.primary.Boundaries()
deadline := time.Now().Add(timeout)
for {
reached := 0
for _, replica := range p.replicas {
r, _, h := replica.Boundaries()
if r >= want && h >= want {
reached++
}
}
if reached == len(p.replicas) || time.Now().After(deadline) {
return reached
}
time.Sleep(time.Millisecond)
}
}
func (p *phase174Pipeline) close() error {
if p.closed {
return nil
}
p.closed = true
var firstErr error
if p.backend != nil {
firstErr = p.backend.Close()
}
if p.replication != nil {
if err := p.replication.Close(); firstErr == nil {
firstErr = err
}
}
for _, listener := range p.listeners {
listener.Stop()
}
if err := p.primary.Close(); firstErr == nil {
firstErr = err
}
for _, replica := range p.replicas {
if err := replica.Close(); firstErr == nil {
firstErr = err
}
}
return firstErr
}
func phase174RecoverAndVerify(
t *testing.T,
primaryPath string,
replicaPaths []string,
payloads [][]byte,
) (primaryR, primaryH uint64, durableReplicas int, replicasEqual bool, samples int) {
t.Helper()
paths := append([]string{primaryPath}, replicaPaths...)
frontiers := make([]uint64, 0, len(paths))
replicasEqual = true
for pathIndex, path := range paths {
store, err := storage.OpenWALStore(path)
if err != nil {
t.Fatal(err)
}
if _, err := store.Recover(); err != nil {
_ = store.Close()
t.Fatal(err)
}
r, _, h := store.Boundaries()
if r != h {
_ = store.Close()
t.Fatalf("path=%s stable=%d head=%d", path, r, h)
}
frontiers = append(frontiers, h)
if pathIndex > 0 && h != primaryH {
if err := store.Close(); err != nil {
t.Fatal(err)
}
continue
}
if pathIndex > 0 {
durableReplicas++
}
for _, operation := range phase174SampleOperations(len(payloads)) {
got, err := store.Read(phase174OperationLBA(operation, 0))
if err != nil {
_ = store.Close()
t.Fatal(err)
}
if !bytes.Equal(got, payloads[operation]) {
_ = store.Close()
t.Fatalf("path=%s operation=%d data mismatch", path, operation)
}
samples++
}
if err := store.Close(); err != nil {
t.Fatal(err)
}
if pathIndex == 0 {
primaryR, primaryH = r, h
}
}
for _, frontier := range frontiers[1:] {
if frontier != frontiers[0] {
replicasEqual = false
}
}
return primaryR, primaryH, durableReplicas, replicasEqual, samples
}
func phase174OperationLBA(operation int, base uint32) uint32 {
return base + uint32((operation*7919)%phase174RegionBlocks)
}
func phase174Payloads(operations, set, run int, marker uint64) [][]byte {
payloads := make([][]byte, operations)
for operation := range payloads {
payload := make([]byte, phase174BlockSize)
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 phase174SampleOperations(operations int) []int {
samples := []int{0, operations / 7, operations / 3, operations / 2, operations - 1}
sort.Ints(samples)
return samples
}
func phase174Percentiles(samples []int64) (p50, p95, p99 int64) {
ordered := append([]int64(nil), samples...)
sort.Slice(ordered, func(i, j int) bool { return ordered[i] < ordered[j] })
at := func(percent int) int64 {
index := (len(ordered)*percent + 99) / 100
if index > 0 {
index--
}
return ordered[index]
}
return at(50), at(95), at(99)
}
@@ -0,0 +1,211 @@
package replication
import (
"bytes"
"encoding/json"
"fmt"
"net"
"os"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/storage"
"github.com/seaweedfs/seaweed-block/core/transport"
)
const (
phase174RemoteReplicasEnv = "SW_BLOCK_PHASE174_REMOTE_REPLICAS"
phase174ReplicaStoreEnv = "SW_BLOCK_PHASE174_REPLICA_STORE"
phase174ReplicaListenEnv = "SW_BLOCK_PHASE174_REPLICA_LISTEN"
phase174ReplicaReadyFileEnv = "SW_BLOCK_PHASE174_REPLICA_READY_FILE"
phase174ReplicaStopFileEnv = "SW_BLOCK_PHASE174_REPLICA_STOP_FILE"
phase174ReplicaResultEnv = "SW_BLOCK_PHASE174_REPLICA_RESULT_FILE"
phase174ReplicaFinalSetEnv = "SW_BLOCK_PHASE174_REPLICA_FINAL_SET"
phase174ReplicaFinalRunEnv = "SW_BLOCK_PHASE174_REPLICA_FINAL_RUN"
)
type phase174RemoteReplicaResult struct {
Status string `json:"status"`
ListenAddress string `json:"listen_address"`
StableLSN uint64 `json:"stable_lsn"`
HeadLSN uint64 `json:"head_lsn"`
ExpectedHeadLSN uint64 `json:"expected_head_lsn"`
CorrectnessSamples int `json:"correctness_samples"`
}
func phase174RemoteReplicaTargets() ([]ReplicaTarget, error) {
raw := strings.TrimSpace(os.Getenv(phase174RemoteReplicasEnv))
if raw == "" {
return nil, nil
}
addresses := strings.Split(raw, ",")
if len(addresses) != 2 {
return nil, fmt.Errorf("phase174: %s must contain exactly two addresses", phase174RemoteReplicasEnv)
}
targets := make([]ReplicaTarget, 0, len(addresses))
hosts := make(map[string]struct{}, len(addresses))
for index, value := range addresses {
address := strings.TrimSpace(value)
host, port, err := net.SplitHostPort(address)
if err != nil {
return nil, fmt.Errorf("phase174: remote replica address %q: %w", address, err)
}
ip := net.ParseIP(host)
if ip == nil || ip.IsLoopback() || ip.IsUnspecified() {
return nil, fmt.Errorf("phase174: remote replica host %q must be a non-loopback IP", host)
}
if _, err := strconv.ParseUint(port, 10, 16); err != nil {
return nil, fmt.Errorf("phase174: remote replica port %q: %w", port, err)
}
if _, exists := hosts[ip.String()]; exists {
return nil, fmt.Errorf("phase174: remote replicas must use distinct hosts")
}
hosts[ip.String()] = struct{}{}
targets = append(targets, ReplicaTarget{
ReplicaID: fmt.Sprintf("remote-r%d", index+1), DataAddr: address,
ControlAddr: address, Epoch: 1, EndpointVersion: 1,
})
}
return targets, nil
}
func TestPhase174RemoteReplicaTargetContract(t *testing.T) {
t.Setenv(phase174RemoteReplicasEnv, "192.0.2.1:17411,192.0.2.2:17412")
targets, err := phase174RemoteReplicaTargets()
if err != nil {
t.Fatal(err)
}
if len(targets) != 2 || targets[0].DataAddr != "192.0.2.1:17411" || targets[1].DataAddr != "192.0.2.2:17412" {
t.Fatalf("targets=%+v", targets)
}
for _, invalid := range []string{
"192.0.2.1:17411",
"127.0.0.1:17411,192.0.2.2:17412",
"192.0.2.1:17411,192.0.2.1:17412",
} {
t.Setenv(phase174RemoteReplicasEnv, invalid)
if _, err := phase174RemoteReplicaTargets(); err == nil {
t.Fatalf("accepted remote replica addresses %q", invalid)
}
}
}
func TestPhase174RemoteReplicaProcess(t *testing.T) {
storePath := os.Getenv(phase174ReplicaStoreEnv)
if storePath == "" {
t.Skip("remote replica process requires " + phase174ReplicaStoreEnv)
}
listenAddress := os.Getenv(phase174ReplicaListenEnv)
readyFile := os.Getenv(phase174ReplicaReadyFileEnv)
stopFile := os.Getenv(phase174ReplicaStopFileEnv)
resultFile := os.Getenv(phase174ReplicaResultEnv)
if listenAddress == "" || readyFile == "" || stopFile == "" || resultFile == "" {
t.Fatal("remote replica process requires listen, ready, stop, and result paths")
}
finalSet := phase174RequiredPositiveInt(t, phase174ReplicaFinalSetEnv)
finalRun := phase174RequiredPositiveInt(t, phase174ReplicaFinalRunEnv)
if err := os.MkdirAll(filepath.Dir(storePath), 0o755); err != nil {
t.Fatal(err)
}
store, err := storage.CreateWALStore(storePath, phase174NumBlocks, phase174BlockSize)
if err != nil {
t.Fatal(err)
}
storeOpen := true
defer func() {
if storeOpen {
_ = store.Close()
}
}()
listener, err := transport.NewReplicaListener(listenAddress, store)
if err != nil {
t.Fatal(err)
}
listenerRunning := true
defer func() {
if listenerRunning {
listener.Stop()
}
}()
listener.Serve()
if err := os.WriteFile(readyFile, []byte(listener.Addr()+"\n"), 0o644); err != nil {
t.Fatal(err)
}
deadline := time.Now().Add(15 * time.Minute)
for {
if _, err := os.Stat(stopFile); err == nil {
break
} else if !os.IsNotExist(err) {
t.Fatal(err)
}
if time.Now().After(deadline) {
t.Fatal("timed out waiting for remote replica stop file")
}
time.Sleep(100 * time.Millisecond)
}
listener.Stop()
listenerRunning = false
if _, err := store.Sync(); err != nil {
t.Fatal(err)
}
if err := store.Close(); err != nil {
t.Fatal(err)
}
storeOpen = false
reopened, err := storage.OpenWALStore(storePath)
if err != nil {
t.Fatal(err)
}
defer reopened.Close()
if _, err := reopened.Recover(); err != nil {
t.Fatal(err)
}
stable, _, head := reopened.Boundaries()
expectedHead := uint64((phase174Runs + 1) * (phase174WarmupOperations + phase174APIOperations))
if stable != head || head != expectedHead {
t.Fatalf("remote replica frontier stable=%d head=%d want=%d", stable, head, expectedHead)
}
payloads := phase174Payloads(phase174APIOperations, finalSet, finalRun, 0x1741)
samples := 0
for _, operation := range phase174SampleOperations(len(payloads)) {
got, err := reopened.Read(phase174OperationLBA(operation, 0))
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(got, payloads[operation]) {
t.Fatalf("operation=%d data mismatch", operation)
}
samples++
}
result := phase174RemoteReplicaResult{
Status: "ok", ListenAddress: listener.Addr(), StableLSN: stable,
HeadLSN: head, ExpectedHeadLSN: expectedHead, CorrectnessSamples: samples,
}
encoded, err := json.Marshal(result)
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(resultFile, append(encoded, '\n'), 0o644); err != nil {
t.Fatal(err)
}
fmt.Printf("phase174_remote_replica_result=%s\n", encoded)
}
func phase174RequiredPositiveInt(t *testing.T, name string) int {
t.Helper()
value, err := strconv.Atoi(os.Getenv(name))
if err != nil || value <= 0 {
t.Fatalf("%s must be a positive integer", name)
}
return value
}
+7 -1
View File
@@ -487,12 +487,18 @@ func (v *ReplicationVolume) replaceTerminalPeerQueueLocked(id string, old *peerW
if old == nil || v.peerQueues[id] != old || !old.isTerminal() {
return v.peerQueues[id]
}
old.closeAndWait()
peer := v.peers[id]
if peer == nil || v.closed {
old.closeAndWait()
delete(v.peerQueues, id)
return nil
}
// Saturation degrades the peer before this call returns. Recovery must
// close the LSN gap before a fresh queue can accept steady writes.
if peer.State() != ReplicaHealthy {
return old
}
old.closeAndWait()
replacement := newPeerWorkQueue(peer, v.peerQueueDepth)
v.peerQueues[id] = replacement
return replacement
@@ -155,11 +155,20 @@ func TestReplicationVolume_SyncAllWaitsForSlowBarrier(t *testing.T) {
}
func TestReplicationVolume_QueueSaturationIsTypedAndCounted(t *testing.T) {
v := NewReplicationVolume("queue-saturation", storage.NewBlockStore(64, 4096))
addr, _ := replicaHarness(t, "queue-saturation")
v := volumeHarness(t, "queue-saturation")
if err := v.UpdateReplicaSet(1, []ReplicaTarget{targetFor("slow", addr, 1, 1)}); err != nil {
t.Fatal(err)
}
started := make(chan struct{})
releaseCh := make(chan struct{})
var releaseOnce sync.Once
release := func() { releaseOnce.Do(func() { close(releaseCh) }) }
v.mu.Lock()
oldQueue := v.peerQueues["slow"]
peer := v.peers["slow"]
v.mu.Unlock()
oldQueue.closeAndWait()
q := newPeerWorkQueueWithOps("slow", 1, peerWorkQueueOps{
ship: func(ctx context.Context, _ LocalWrite) (bool, error) {
select {
@@ -174,11 +183,11 @@ func TestReplicationVolume_QueueSaturationIsTypedAndCounted(t *testing.T) {
return false, ctx.Err()
}
},
invalidate: peer.Invalidate,
})
v.mu.Lock()
v.peerQueues["slow"] = q
v.mu.Unlock()
t.Cleanup(func() { _ = v.Close() })
t.Cleanup(release)
first, err := v.enqueueLocalWrite(LocalWrite{LBA: 0, LSN: 1, Data: make([]byte, 4096)})
@@ -205,6 +214,12 @@ func TestReplicationVolume_QueueSaturationIsTypedAndCounted(t *testing.T) {
if got := v.Stats().PeerQueueSaturated; got != 1 {
t.Fatalf("PeerQueueSaturated=%d want 1", got)
}
v.mu.Lock()
current := v.peerQueues["slow"]
v.mu.Unlock()
if current != q {
t.Fatal("saturated queue changed before peer recovery completed")
}
release()
<-first.result
<-second.result
+9
View File
@@ -91,9 +91,16 @@ func (f *flusher) NotifyUrgent() {
// run drives the flush loop. Wakes on either the periodic ticker
// or an explicit Notify(). Call once in a goroutine.
func (f *flusher) run() {
f.runWithStartSignal(nil)
}
func (f *flusher) runWithStartSignal(started chan<- struct{}) {
defer close(f.doneCh)
ticker := time.NewTicker(f.interval)
defer ticker.Stop()
if started != nil {
close(started)
}
for {
select {
case <-f.stopCh:
@@ -321,7 +328,9 @@ func (f *flusher) readDirtyRecord(e snapshotEntry) (data []byte, entrySize uint6
"flusher: invalid dirty WAL record LBA %d offset %d record size %d expected %d",
e.LBA, e.WALOffset, entrySize, expectedRecordSize)
}
decodeStart := time.Now()
entry, err := decodeWALEntry(full)
f.instr.recordWALRecordDecode(len(full), time.Since(decodeStart), err)
if err != nil {
return nil, 0, fmt.Errorf(
"flusher: invalid dirty WAL record LBA %d offset %d: %w",
@@ -41,6 +41,10 @@ type FlusherInstrumentationStatus struct {
WALRecordReadFailures uint64
WALRecordReadBytes uint64
WALRecordReadDurationNanos uint64
WALRecordDecodeOps uint64
WALRecordDecodeFailures uint64
WALRecordDecodeBytes uint64
WALRecordDecodeDurationNanos uint64
ExtentWriteOps uint64
ExtentWriteFailures uint64
ExtentWriteBytes uint64
@@ -88,6 +92,10 @@ type flusherInstrumentation struct {
walRecordReadFailures atomic.Uint64
walRecordReadBytes atomic.Uint64
walRecordReadDurationNanos atomic.Uint64
walRecordDecodeOps atomic.Uint64
walRecordDecodeFailures atomic.Uint64
walRecordDecodeBytes atomic.Uint64
walRecordDecodeDurationNanos atomic.Uint64
extentWriteOps atomic.Uint64
extentWriteFailures atomic.Uint64
extentWriteBytes atomic.Uint64
@@ -206,6 +214,15 @@ func (i *flusherInstrumentation) recordWALRecordRead(bytes int, duration time.Du
}
}
func (i *flusherInstrumentation) recordWALRecordDecode(bytes int, duration time.Duration, err error) {
i.walRecordDecodeOps.Add(1)
i.walRecordDecodeBytes.Add(uint64(bytes))
i.walRecordDecodeDurationNanos.Add(storageDurationNanos(duration))
if err != nil {
i.walRecordDecodeFailures.Add(1)
}
}
func (i *flusherInstrumentation) recordValidatedRecord() {
i.validatedRecords.Add(1)
}
@@ -296,6 +313,10 @@ func (i *flusherInstrumentation) snapshot() FlusherInstrumentationStatus {
WALRecordReadFailures: i.walRecordReadFailures.Load(),
WALRecordReadBytes: i.walRecordReadBytes.Load(),
WALRecordReadDurationNanos: i.walRecordReadDurationNanos.Load(),
WALRecordDecodeOps: i.walRecordDecodeOps.Load(),
WALRecordDecodeFailures: i.walRecordDecodeFailures.Load(),
WALRecordDecodeBytes: i.walRecordDecodeBytes.Load(),
WALRecordDecodeDurationNanos: i.walRecordDecodeDurationNanos.Load(),
ExtentWriteOps: i.extentWriteOps.Load(),
ExtentWriteFailures: i.extentWriteFailures.Load(),
ExtentWriteBytes: i.extentWriteBytes.Load(),
@@ -61,9 +61,13 @@ func TestFlusherInstrumentationCountsCompleteCycle(t *testing.T) {
t.Fatalf("snapshot/validated/superseded=%d/%d/%d want 4/4/0",
got.SnapshotEntries, got.ValidatedRecords, got.SupersededEntries)
}
if got.WALHeaderReadOps != 4 || got.WALRecordReadOps != 4 {
t.Fatalf("header/record reads=%d/%d want 4/4",
got.WALHeaderReadOps, got.WALRecordReadOps)
if got.WALHeaderReadOps != 4 || got.WALRecordReadOps != 4 ||
got.WALRecordDecodeOps != 4 || got.WALRecordDecodeBytes == 0 ||
got.WALRecordDecodeDurationNanos == 0 {
t.Fatalf("header/record reads and decode ops/bytes/ns=%d/%d %d/%d/%d want 4/4 4/nonzero/nonzero",
got.WALHeaderReadOps, got.WALRecordReadOps,
got.WALRecordDecodeOps, got.WALRecordDecodeBytes,
got.WALRecordDecodeDurationNanos)
}
if got.ExtentWriteOps != 4 || got.ExtentWriteBytes != 4*4096 ||
got.ExtentWriteMaxBytes != 4096 || got.ExtentWriteFailures != 0 {
@@ -230,6 +234,7 @@ func TestFlusherInstrumentationCountsExtentFailures(t *testing.T) {
instr.recordExtentSync(time.Nanosecond, injected)
instr.recordWALHeaderRead(12, time.Nanosecond, injected)
instr.recordWALRecordRead(34, time.Nanosecond, injected)
instr.recordWALRecordDecode(34, time.Nanosecond, injected)
got := instr.snapshot()
if got.ExtentWriteOps != 1 || got.ExtentWriteFailures != 1 ||
@@ -245,10 +250,13 @@ func TestFlusherInstrumentationCountsExtentFailures(t *testing.T) {
if got.WALHeaderReadOps != 1 || got.WALHeaderReadFailures != 1 ||
got.WALHeaderReadBytes != 12 ||
got.WALRecordReadOps != 1 || got.WALRecordReadFailures != 1 ||
got.WALRecordReadBytes != 34 {
t.Fatalf("WAL header ops/failures/bytes and record ops/failures/bytes=%d/%d/%d %d/%d/%d want 1/1/12 1/1/34",
got.WALRecordReadBytes != 34 ||
got.WALRecordDecodeOps != 1 || got.WALRecordDecodeFailures != 1 ||
got.WALRecordDecodeBytes != 34 {
t.Fatalf("WAL header/read/decode ops/failures/bytes=%d/%d/%d %d/%d/%d %d/%d/%d want 1/1/12 1/1/34 1/1/34",
got.WALHeaderReadOps, got.WALHeaderReadFailures, got.WALHeaderReadBytes,
got.WALRecordReadOps, got.WALRecordReadFailures, got.WALRecordReadBytes)
got.WALRecordReadOps, got.WALRecordReadFailures, got.WALRecordReadBytes,
got.WALRecordDecodeOps, got.WALRecordDecodeFailures, got.WALRecordDecodeBytes)
}
}
@@ -0,0 +1,617 @@
package storage
import (
"bytes"
"encoding/json"
"fmt"
"os"
"path/filepath"
"runtime"
"sort"
"strconv"
"sync"
"testing"
"time"
)
const (
phase173ControlStoreEnv = "SW_BLOCK_PHASE173_ARCH_CONTROL_STORE_DIR"
phase173ControlNameEnv = "SW_BLOCK_PHASE173_ARCH_CONTROL"
phase173ControlRunEnv = "SW_BLOCK_PHASE173_ARCH_CONTROL_RUN"
phase173ControlRuns = 5
phase173ControlAPIOps = 2320
phase173ControlWarmup = 80
phase173ScratchBlocks = 14500
phase173ScratchPasses = 3
)
type phase173ArchitectureControlResult struct {
Contract string `json:"contract"`
Control string `json:"control"`
Scope string `json:"scope"`
Run int `json:"run"`
Writers int `json:"writers"`
LogicalBlocks uint64 `json:"logical_blocks"`
LogicalBytes uint64 `json:"logical_bytes"`
DurationNanos int64 `json:"duration_ns"`
MiBPerSecond float64 `json:"mib_per_second"`
P99Nanos int64 `json:"p99_ns,omitempty"`
FinalSyncNanos int64 `json:"final_sync_ns,omitempty"`
FinalDrainNanos int64 `json:"final_drain_ns,omitempty"`
CommitLockWaitOps uint64 `json:"commit_lock_wait_ops,omitempty"`
CommitLockWaitNanos uint64 `json:"commit_lock_wait_ns,omitempty"`
WALAppendLockWaitNanos uint64 `json:"wal_append_lock_wait_ns,omitempty"`
WALWriteAtCalls uint64 `json:"wal_writeat_calls,omitempty"`
FlushCycles uint64 `json:"flush_cycles,omitempty"`
FlushCycleNanos uint64 `json:"flush_cycle_ns,omitempty"`
FlushRecordReads uint64 `json:"flush_record_reads,omitempty"`
FlushDecodeOps uint64 `json:"flush_decode_ops,omitempty"`
ExtentWriteOps uint64 `json:"extent_write_ops,omitempty"`
ExtentSyncOps uint64 `json:"extent_sync_ops,omitempty"`
CheckpointSyncOps uint64 `json:"checkpoint_sync_ops,omitempty"`
ScratchPReadOps uint64 `json:"scratch_pread_ops,omitempty"`
ScratchPWriteOps uint64 `json:"scratch_pwrite_ops,omitempty"`
ScratchSyncOps uint64 `json:"scratch_sync_ops,omitempty"`
MeasuredAllocBytes uint64 `json:"measured_alloc_bytes,omitempty"`
MeasuredMallocs uint64 `json:"measured_mallocs,omitempty"`
MeasuredGCCycles uint32 `json:"measured_gc_cycles,omitempty"`
MeasuredGCPauseNanos uint64 `json:"measured_gc_pause_ns,omitempty"`
MeasuredHeapAllocStart uint64 `json:"measured_heap_alloc_start,omitempty"`
MeasuredHeapAllocEnd uint64 `json:"measured_heap_alloc_end,omitempty"`
CorrectnessSamples int `json:"correctness_samples"`
}
func TestPhase173ArchitectureControlContract(t *testing.T) {
for _, writers := range []int{1, 4} {
cfg := phase173ControlConfig(writers)
if cfg.APILogicalBlocks() != phase173ScratchBlocks {
t.Fatalf("writers=%d logical blocks=%d want %d", writers, cfg.APILogicalBlocks(), phase173ScratchBlocks)
}
if cfg.WarmupLogicalBlocks() != 500 {
t.Fatalf("writers=%d warmup blocks=%d want 500", writers, cfg.WarmupLogicalBlocks())
}
}
for worker := 0; worker < 4; worker++ {
start, end := phase173BalancedOperationRange(worker, 4, phase173ControlAPIOps)
if end-start != phase173ControlAPIOps/4 || start%4 != 0 || end%4 != 0 {
t.Fatalf("worker=%d range=[%d,%d) is not a balanced mixed-pattern partition", worker, start, end)
}
}
}
func TestPhase173ArchitectureControls(t *testing.T) {
dir := os.Getenv(phase173ControlStoreEnv)
if dir == "" {
t.Skip("formal architecture controls require " + phase173ControlStoreEnv)
}
control := os.Getenv(phase173ControlNameEnv)
run, err := strconv.Atoi(os.Getenv(phase173ControlRunEnv))
if err != nil || run < 0 || run > phase173ControlRuns {
t.Fatalf("%s must be in [0,%d]", phase173ControlRunEnv, phase173ControlRuns)
}
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
for _, tc := range []struct {
name string
control string
writers int
live bool
}{
{name: "shipped_concurrent_writers_4", control: "shipped_concurrent", writers: 4, live: true},
{name: "deferred_foreground_writers_1", control: "deferred_foreground", writers: 1, live: false},
{name: "deferred_foreground_writers_4", control: "deferred_foreground", writers: 4, live: false},
} {
if control != tc.name {
continue
}
path := filepath.Join(dir, fmt.Sprintf("phase173-control-%s.store", tc.name))
if run == 0 {
s := preparePhase173ControlStore(t, path, tc.writers)
if err := s.Close(); err != nil {
t.Fatal(err)
}
return
}
s := openPhase173ControlStore(t, path)
runtime.GC()
time.Sleep(100 * time.Millisecond)
foreground, flusher := runPhase173WALStoreControl(t, s, tc.control, tc.writers, tc.live, run)
emitPhase173ArchitectureControl(t, foreground)
if tc.writers == 4 && !tc.live {
emitPhase173ArchitectureControl(t, flusher)
}
if err := s.Close(); err != nil {
t.Fatal(err)
}
return
}
if control == "shared_file_scratch" || control == "split_file_scratch" {
scratch := preparePhase173FileLayoutScratch(t, dir)
defer scratch.close(t)
runtime.GC()
time.Sleep(100 * time.Millisecond)
emitPhase173ArchitectureControl(t, scratch.run(t, control == "split_file_scratch", run))
return
}
t.Fatalf("unsupported %s=%q", phase173ControlNameEnv, control)
}
func phase173ControlConfig(writers int) phase173FixedWorkConfig {
return phase173FixedWorkConfig{
Shape: "mounted_mixed",
Writers: writers,
APIOperations: phase173ControlAPIOps,
WarmupAPIOps: phase173ControlWarmup,
}
}
func preparePhase173ControlStore(t *testing.T, path string, writers int) *WALStore {
t.Helper()
if err := os.Remove(path); err != nil && !os.IsNotExist(err) {
t.Fatal(err)
}
s, err := CreateWALStore(path, phase173FixedWorkNumBlocks, phase173FixedWorkBlockSize)
if err != nil {
t.Fatal(err)
}
cfg := phase173ControlConfig(writers)
payloads := phase173Payloads(writers)
if _, _, err := runPhase173Operations(s, cfg, cfg.APIOperations, 0, payloads, false); err != nil {
t.Fatal(err)
}
synced, err := s.Sync()
if err != nil {
t.Fatal(err)
}
if err := s.flusher.Stop(); err != nil {
t.Fatal(err)
}
assertPhase173ControlDrained(t, s, synced)
if err := s.Close(); err != nil {
t.Fatal(err)
}
return openPhase173ControlStore(t, path)
}
func openPhase173ControlStore(t *testing.T, path string) *WALStore {
t.Helper()
s, err := OpenWALStore(path)
if err != nil {
t.Fatal(err)
}
if _, err := s.Recover(); err != nil {
_ = s.Close()
t.Fatal(err)
}
if err := s.flusher.Stop(); err != nil {
_ = s.Close()
t.Fatal(err)
}
return s
}
func runPhase173WALStoreControl(
t *testing.T,
s *WALStore,
control string,
writers int,
live bool,
run int,
) (phase173ArchitectureControlResult, phase173ArchitectureControlResult) {
t.Helper()
cfg := phase173ControlConfig(writers)
payloads := phase173Payloads(writers)
startPhase173ControlFlusher(s)
if _, _, err := runPhase173BalancedOperations(s, cfg, cfg.WarmupAPIOps, phase173FixedWorkRegionBlocks, payloads, false); err != nil {
t.Fatal(err)
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
if err := s.flusher.Stop(); err != nil {
t.Fatal(err)
}
if s.dm.len() != 0 {
t.Fatalf("warmup dirty entries=%d", s.dm.len())
}
if live {
startPhase173ControlFlusher(s)
}
writeBefore := s.WriteInstrumentation()
var memoryBefore runtime.MemStats
runtime.ReadMemStats(&memoryBefore)
foreground, latencies, err := runPhase173BalancedOperations(s, cfg, cfg.APIOperations, 0, payloads, true)
var memoryAfter runtime.MemStats
runtime.ReadMemStats(&memoryAfter)
if err != nil {
t.Fatal(err)
}
syncStart := time.Now()
synced, err := s.Sync()
finalSync := time.Since(syncStart)
if err != nil {
t.Fatal(err)
}
if !live {
startPhase173ControlFlusher(s)
}
drainStart := time.Now()
if err := s.flusher.Stop(); err != nil {
t.Fatal(err)
}
finalDrain := time.Since(drainStart)
assertPhase173ControlDrained(t, s, synced)
correctness, err := verifyPhase173BalancedSamples(s, cfg, payloads)
if err != nil {
t.Fatal(err)
}
writeAfter := s.WriteInstrumentation()
flush := s.FlusherInstrumentation()
if flush.CycleDurationNanos == 0 {
t.Fatalf("control=%s writers=%d recorded no flusher duration", control, writers)
}
logicalBlocks := cfg.APILogicalBlocks()
logicalBytes := logicalBlocks * phase173FixedWorkBlockSize
if got := writeAfter.WALEncodeOps - writeBefore.WALEncodeOps; got != logicalBlocks {
t.Fatalf("control=%s writers=%d encoded=%d want %d", control, writers, got, logicalBlocks)
}
if flush.ValidatedRecords != logicalBlocks || flush.ExtentWriteOps != logicalBlocks ||
flush.ValidationFailures != 0 || flush.WALRecordDecodeFailures != 0 {
t.Fatalf("control=%s writers=%d flush=%+v", control, writers, flush)
}
_, _, p99 := phase173Percentiles(latencies)
foregroundResult := phase173ArchitectureControlResult{
Contract: "phase173-architecture-controls-v1",
Control: control,
Scope: map[bool]string{true: "shipped_durable_path", false: "non_product_deferred_writeback"}[live],
Run: run,
Writers: writers,
LogicalBlocks: logicalBlocks,
LogicalBytes: logicalBytes,
DurationNanos: foreground.Nanoseconds(),
MiBPerSecond: phase173Rate(logicalBytes, foreground),
P99Nanos: p99,
FinalSyncNanos: finalSync.Nanoseconds(),
FinalDrainNanos: finalDrain.Nanoseconds(),
CommitLockWaitOps: writeAfter.WriteCommitLockWaitOps - writeBefore.WriteCommitLockWaitOps,
CommitLockWaitNanos: writeAfter.WriteCommitLockWaitNanos - writeBefore.WriteCommitLockWaitNanos,
WALAppendLockWaitNanos: writeAfter.WALAppendLockWaitNanos - writeBefore.WALAppendLockWaitNanos,
WALWriteAtCalls: writeAfter.WALAppendWriteAtCalls - writeBefore.WALAppendWriteAtCalls,
FlushCycles: flush.CyclesStarted,
FlushCycleNanos: flush.CycleDurationNanos,
FlushRecordReads: flush.WALRecordReadOps,
FlushDecodeOps: flush.WALRecordDecodeOps,
ExtentWriteOps: flush.ExtentWriteOps,
ExtentSyncOps: flush.ExtentSyncOps,
CheckpointSyncOps: flush.CheckpointMetadataSyncOps,
MeasuredAllocBytes: memoryAfter.TotalAlloc - memoryBefore.TotalAlloc,
MeasuredMallocs: memoryAfter.Mallocs - memoryBefore.Mallocs,
MeasuredGCCycles: memoryAfter.NumGC - memoryBefore.NumGC,
MeasuredGCPauseNanos: memoryAfter.PauseTotalNs - memoryBefore.PauseTotalNs,
MeasuredHeapAllocStart: memoryBefore.HeapAlloc,
MeasuredHeapAllocEnd: memoryAfter.HeapAlloc,
CorrectnessSamples: correctness,
}
flusherResult := phase173ArchitectureControlResult{
Contract: "phase173-architecture-controls-v1",
Control: "prefilled_flusher",
Scope: "real_flusher_without_foreground_writers",
Run: run,
Writers: 0,
LogicalBlocks: logicalBlocks,
LogicalBytes: logicalBytes,
DurationNanos: int64(flush.CycleDurationNanos),
MiBPerSecond: phase173Rate(logicalBytes, time.Duration(flush.CycleDurationNanos)),
FlushCycles: flush.CyclesStarted,
FlushCycleNanos: flush.CycleDurationNanos,
FlushRecordReads: flush.WALRecordReadOps,
FlushDecodeOps: flush.WALRecordDecodeOps,
ExtentWriteOps: flush.ExtentWriteOps,
ExtentSyncOps: flush.ExtentSyncOps,
CheckpointSyncOps: flush.CheckpointMetadataSyncOps,
CorrectnessSamples: correctness,
}
return foregroundResult, flusherResult
}
func runPhase173BalancedOperations(
s *WALStore,
cfg phase173FixedWorkConfig,
operations int,
base uint32,
payloads []map[int][][]byte,
recordLatency bool,
) (time.Duration, []int64, error) {
latencies := make([]int64, operations)
start := make(chan struct{})
var wg sync.WaitGroup
var ready sync.WaitGroup
var firstErr error
var errOnce sync.Once
for worker := 0; worker < cfg.Writers; worker++ {
first, last := phase173BalancedOperationRange(worker, cfg.Writers, operations)
wg.Add(1)
ready.Add(1)
go func(worker, first, last int) {
defer wg.Done()
ready.Done()
<-start
for index := first; index < last; index++ {
lba, blocks := cfg.operation(index, base)
opStart := time.Now()
var err error
if blocks == 1 {
_, err = s.Write(lba, payloads[worker][1][0])
} else {
_, err = s.WriteBatch(lba, payloads[worker][blocks])
}
if recordLatency {
latencies[index] = time.Since(opStart).Nanoseconds()
}
if err != nil {
errOnce.Do(func() { firstErr = err })
return
}
}
}(worker, first, last)
}
ready.Wait()
begin := time.Now()
close(start)
wg.Wait()
return time.Since(begin), latencies, firstErr
}
func phase173BalancedOperationRange(worker, writers, operations int) (int, int) {
return worker * operations / writers, (worker + 1) * operations / writers
}
func verifyPhase173BalancedSamples(
s *WALStore,
cfg phase173FixedWorkConfig,
payloads []map[int][][]byte,
) (int, error) {
indexes := map[int]struct{}{0: {}, cfg.APIOperations / 2: {}, cfg.APIOperations - 1: {}}
for worker := 0; worker < cfg.Writers; worker++ {
first, _ := phase173BalancedOperationRange(worker, cfg.Writers, cfg.APIOperations)
indexes[first] = struct{}{}
}
ordered := make([]int, 0, len(indexes))
for index := range indexes {
ordered = append(ordered, index)
}
sort.Ints(ordered)
samples := 0
for _, index := range ordered {
worker := index * cfg.Writers / cfg.APIOperations
if worker >= cfg.Writers {
worker = cfg.Writers - 1
}
lba, blocks := cfg.operation(index, 0)
for _, block := range []int{0, blocks - 1} {
data, err := s.Read(lba + uint32(block))
if err != nil {
return samples, err
}
want := payloads[worker][blocks][block]
if len(data) != len(want) || data[0] != want[0] || data[1] != want[1] || data[2] != want[2] {
return samples, fmt.Errorf("phase173 balanced data mismatch op=%d block=%d", index, block)
}
samples++
if blocks == 1 {
break
}
}
}
return samples, nil
}
func startPhase173ControlFlusher(s *WALStore) {
s.flusher = newFlusher(s, flusherConfig{Interval: 100 * time.Millisecond})
started := make(chan struct{})
go s.flusher.runWithStartSignal(started)
<-started
}
func assertPhase173ControlDrained(t *testing.T, s *WALStore, synced uint64) {
t.Helper()
_, _, head := s.Boundaries()
if s.dm.len() != 0 || s.CheckpointLSN() != synced || head != synced {
t.Fatalf("dirty=%d checkpoint=%d head=%d synced=%d", s.dm.len(), s.CheckpointLSN(), head, synced)
}
}
func phase173Rate(logicalBytes uint64, duration time.Duration) float64 {
return float64(logicalBytes) / (1024 * 1024) / duration.Seconds()
}
func emitPhase173ArchitectureControl(t *testing.T, result phase173ArchitectureControlResult) {
t.Helper()
encoded, err := json.Marshal(result)
if err != nil {
t.Fatal(err)
}
fmt.Printf("phase173_architecture_control_result=%s\n", encoded)
}
type phase173FileLayoutScratch struct {
shared *os.File
wal *os.File
extent *os.File
recordSize int
walBase int64
extentBase int64
logicalData []byte
paths []string
}
func preparePhase173FileLayoutScratch(t *testing.T, dir string) *phase173FileLayoutScratch {
t.Helper()
paths := []string{
filepath.Join(dir, "phase173-control-shared.scratch"),
filepath.Join(dir, "phase173-control-split-wal.scratch"),
filepath.Join(dir, "phase173-control-split-extent.scratch"),
}
for _, path := range paths {
if err := os.Remove(path); err != nil && !os.IsNotExist(err) {
t.Fatal(err)
}
}
open := func(path string) *os.File {
file, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0o644)
if err != nil {
t.Fatal(err)
}
return file
}
scratch := &phase173FileLayoutScratch{
shared: open(paths[0]),
wal: open(paths[1]),
extent: open(paths[2]),
walBase: 4096,
logicalData: make([]byte, phase173FixedWorkBlockSize),
paths: paths,
}
for index := range scratch.logicalData {
scratch.logicalData[index] = byte(index*17 + 3)
}
for index := 0; index < phase173ScratchBlocks; index++ {
entry := walEntry{
LSN: uint64(index + 1),
Type: walEntryWrite,
LBA: uint64(index),
Length: phase173FixedWorkBlockSize,
Data: scratch.logicalData,
}
encoded, err := entry.encodeWithInstrumentation(nil)
if err != nil {
t.Fatal(err)
}
if scratch.recordSize == 0 {
scratch.recordSize = len(encoded)
scratch.extentBase = scratch.walBase + int64(scratch.recordSize*phase173ScratchBlocks)
}
offset := scratch.walBase + int64(index*scratch.recordSize)
for _, file := range []*os.File{scratch.shared, scratch.wal} {
if _, err := file.WriteAt(encoded, offset); err != nil {
t.Fatal(err)
}
}
}
zeroExtent := make([]byte, phase173ScratchBlocks*phase173FixedWorkBlockSize)
if _, err := scratch.shared.WriteAt(zeroExtent, scratch.extentBase); err != nil {
t.Fatal(err)
}
if _, err := scratch.extent.WriteAt(zeroExtent, 0); err != nil {
t.Fatal(err)
}
for _, file := range []*os.File{scratch.shared, scratch.wal, scratch.extent} {
if err := file.Sync(); err != nil {
t.Fatal(err)
}
}
return scratch
}
func (s *phase173FileLayoutScratch) run(t *testing.T, split bool, run int) phase173ArchitectureControlResult {
t.Helper()
walFile := s.shared
extentFile := s.shared
extentBase := s.extentBase
control := "shared_file_scratch"
if split {
walFile = s.wal
extentFile = s.extent
extentBase = 0
control = "split_file_scratch"
}
start := time.Now()
for pass := 0; pass < phase173ScratchPasses; pass++ {
for index := 0; index < phase173ScratchBlocks; index++ {
offset := s.walBase + int64(index*s.recordSize)
header := make([]byte, walEntryHeaderSize)
if _, err := walFile.ReadAt(header, offset); err != nil {
t.Fatal(err)
}
full := make([]byte, s.recordSize)
if _, err := walFile.ReadAt(full, offset); err != nil {
t.Fatal(err)
}
entry, err := decodeWALEntry(full)
if err != nil {
t.Fatal(err)
}
if entry.LBA != uint64(index) || !bytes.Equal(entry.Data, s.logicalData) {
t.Fatalf("scratch record %d mismatch", index)
}
if _, err := extentFile.WriteAt(entry.Data, extentBase+int64(index*phase173FixedWorkBlockSize)); err != nil {
t.Fatal(err)
}
}
}
if err := extentFile.Sync(); err != nil {
t.Fatal(err)
}
if _, err := walFile.WriteAt(make([]byte, 4096), 0); err != nil {
t.Fatal(err)
}
if err := walFile.Sync(); err != nil {
t.Fatal(err)
}
duration := time.Since(start)
samples := 0
for _, index := range []int{0, phase173ScratchBlocks / 2, phase173ScratchBlocks - 1} {
got := make([]byte, phase173FixedWorkBlockSize)
if _, err := extentFile.ReadAt(got, extentBase+int64(index*phase173FixedWorkBlockSize)); err != nil {
t.Fatal(err)
}
if !bytes.Equal(got, s.logicalData) {
t.Fatalf("scratch extent %d mismatch", index)
}
samples++
}
logicalBlocks := uint64(phase173ScratchBlocks * phase173ScratchPasses)
logicalBytes := logicalBlocks * phase173FixedWorkBlockSize
return phase173ArchitectureControlResult{
Contract: "phase173-architecture-controls-v1",
Control: control,
Scope: "same_device_scratch_no_recovery_contract",
Run: run,
LogicalBlocks: logicalBlocks,
LogicalBytes: logicalBytes,
DurationNanos: duration.Nanoseconds(),
MiBPerSecond: phase173Rate(logicalBytes, duration),
ScratchPReadOps: phase173ScratchBlocks * phase173ScratchPasses * 2,
ScratchPWriteOps: phase173ScratchBlocks*phase173ScratchPasses + 1,
ScratchSyncOps: 2,
CorrectnessSamples: samples,
}
}
func (s *phase173FileLayoutScratch) close(t *testing.T) {
t.Helper()
var errs []error
for _, file := range []*os.File{s.shared, s.wal, s.extent} {
if err := file.Close(); err != nil {
errs = append(errs, err)
}
}
for _, path := range s.paths {
if err := os.Remove(path); err != nil && !os.IsNotExist(err) {
errs = append(errs, err)
}
}
if len(errs) > 0 {
sort.Slice(errs, func(i, j int) bool { return errs[i].Error() < errs[j].Error() })
t.Fatal(errs)
}
}
@@ -0,0 +1,779 @@
package storage
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"runtime"
"runtime/pprof"
"sort"
"strconv"
"sync"
"testing"
"time"
)
const (
phase173FixedWorkShapeEnv = "SW_BLOCK_PHASE173_SHAPE"
phase173FixedWorkWritersEnv = "SW_BLOCK_PHASE173_WRITERS"
phase173FixedWorkRunIDEnv = "SW_BLOCK_PHASE173_RUN_ID"
phase173FixedWorkStoreEnv = "SW_BLOCK_PHASE173_STORE_DIR"
phase173FixedWorkStoreIDEnv = "SW_BLOCK_PHASE173_STORE_ID"
phase173FixedWorkReuseEnv = "SW_BLOCK_PHASE173_REUSE_STORE"
phase173FixedWorkControlEnv = "SW_BLOCK_PHASE173_CONTROL_DIR"
phase173FixedWorkProfileEnv = "SW_BLOCK_PHASE173_PROFILE_DIR"
phase173FixedWorkBlockSize = 4096
phase173FixedWorkNumBlocks = 65536
phase173FixedWorkRegionBlocks = phase173FixedWorkNumBlocks / 2
)
type phase173FixedWorkConfig struct {
Shape string
Writers int
APIOperations int
WarmupAPIOps int
}
type phase173FixedWorkResult struct {
Contract string `json:"contract"`
RunID string `json:"run_id"`
StoreID string `json:"store_id"`
StoreReused bool `json:"store_reused"`
Shape string `json:"shape"`
Writers int `json:"writers"`
APIOperations int `json:"api_operations"`
LogicalBlocks uint64 `json:"logical_blocks"`
LogicalBytes uint64 `json:"logical_bytes"`
WarmupAPIOperations int `json:"warmup_api_operations"`
WarmupLogicalBlocks uint64 `json:"warmup_logical_blocks"`
BlockSize int `json:"block_size"`
NumBlocks int `json:"num_blocks"`
FlusherIntervalMillis int64 `json:"flusher_interval_ms"`
FlusherPhaseReset bool `json:"flusher_phase_reset"`
ForegroundNanos int64 `json:"foreground_ns"`
ForegroundMiBPerSecond float64 `json:"foreground_mib_per_second"`
P50Nanos int64 `json:"p50_ns"`
P95Nanos int64 `json:"p95_ns"`
P99Nanos int64 `json:"p99_ns"`
FinalSyncNanos int64 `json:"final_sync_ns"`
FinalDrainNanos int64 `json:"final_drain_ns"`
FinalSyncCalls uint64 `json:"final_sync_calls"`
MeasuredAllocBytes uint64 `json:"measured_alloc_bytes"`
MeasuredMallocs uint64 `json:"measured_mallocs"`
MeasuredFrees uint64 `json:"measured_frees"`
MeasuredHeapAllocStart uint64 `json:"measured_heap_alloc_start"`
MeasuredHeapAllocEnd uint64 `json:"measured_heap_alloc_end"`
SyncedLSN uint64 `json:"synced_lsn"`
CheckpointLSN uint64 `json:"checkpoint_lsn"`
HeadLSN uint64 `json:"head_lsn"`
DirtyEntries int `json:"dirty_entries"`
WALCopyOps uint64 `json:"wal_copy_ops"`
WALCopyBytes uint64 `json:"wal_copy_bytes"`
WALCopyNanos uint64 `json:"wal_copy_ns"`
WALEncodeOps uint64 `json:"wal_encode_ops"`
WALEncodeBytes uint64 `json:"wal_encode_bytes"`
WALEncodeNanos uint64 `json:"wal_encode_ns"`
WALChecksumOps uint64 `json:"wal_checksum_ops"`
WALChecksumBytes uint64 `json:"wal_checksum_bytes"`
WALChecksumNanos uint64 `json:"wal_checksum_ns"`
WALAppendOps uint64 `json:"wal_append_ops"`
WALAppendBytes uint64 `json:"wal_append_bytes"`
WALWriteAtCalls uint64 `json:"wal_writeat_calls"`
WALWriteAtBytes uint64 `json:"wal_writeat_bytes"`
WALWraps uint64 `json:"wal_wraps"`
WALPaddingBytes uint64 `json:"wal_padding_bytes"`
WALAppendNanos uint64 `json:"wal_append_ns"`
WALAppendLockWaitNanos uint64 `json:"wal_append_lock_wait_ns"`
CommitLockWaitOps uint64 `json:"commit_lock_wait_ops"`
CommitLockWaitNanos uint64 `json:"commit_lock_wait_ns"`
DirtyMapUpdateOps uint64 `json:"dirty_map_update_ops"`
DirtyMapUpdateNanos uint64 `json:"dirty_map_update_ns"`
FlushCycles uint64 `json:"flush_cycles"`
FlushSnapshotEntries uint64 `json:"flush_snapshot_entries"`
FlushCycleNanos uint64 `json:"flush_cycle_ns"`
FlushSnapshotNanos uint64 `json:"flush_snapshot_ns"`
FlushOpportunityNanos uint64 `json:"flush_opportunity_ns"`
FlushHeaderReads uint64 `json:"flush_header_reads"`
FlushHeaderReadBytes uint64 `json:"flush_header_read_bytes"`
FlushHeaderReadNanos uint64 `json:"flush_header_read_ns"`
FlushRecordReads uint64 `json:"flush_record_reads"`
FlushRecordReadBytes uint64 `json:"flush_record_read_bytes"`
FlushRecordReadNanos uint64 `json:"flush_record_read_ns"`
FlushRecordDecodeOps uint64 `json:"flush_record_decode_ops"`
FlushRecordDecodeBytes uint64 `json:"flush_record_decode_bytes"`
FlushRecordDecodeNanos uint64 `json:"flush_record_decode_ns"`
FlushDecodeFailures uint64 `json:"flush_record_decode_failures"`
ValidatedRecords uint64 `json:"validated_records"`
SupersededEntries uint64 `json:"superseded_entries"`
ExtentWriteOps uint64 `json:"extent_write_ops"`
ExtentWriteBytes uint64 `json:"extent_write_bytes"`
ExtentWriteNanos uint64 `json:"extent_write_ns"`
ExtentSyncOps uint64 `json:"extent_sync_ops"`
ExtentSyncNanos uint64 `json:"extent_sync_ns"`
CheckpointWriteOps uint64 `json:"checkpoint_write_ops"`
CheckpointWriteNanos uint64 `json:"checkpoint_write_ns"`
CheckpointSyncOps uint64 `json:"checkpoint_sync_ops"`
CheckpointSyncNanos uint64 `json:"checkpoint_sync_ns"`
ValidationFailures uint64 `json:"validation_failures"`
CorrectnessSamples int `json:"correctness_samples"`
}
func TestPhase173MeasurementControlHandshake(t *testing.T) {
control := phase173MeasurementControl{dir: t.TempDir()}
started := make(chan error, 1)
go func() {
active, err := control.awaitStart()
if err == nil && !active {
err = errors.New("phase173 control did not activate")
}
started <- err
}()
if err := phase173WaitForPath(filepath.Join(control.dir, "ready"), time.Second); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(control.dir, "go"), nil, 0o644); err != nil {
t.Fatal(err)
}
if err := <-started; err != nil {
t.Fatal(err)
}
finished := make(chan error, 1)
go func() { finished <- control.finish() }()
if err := phase173WaitForPath(filepath.Join(control.dir, "done"), time.Second); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(control.dir, "detached"), nil, 0o644); err != nil {
t.Fatal(err)
}
if err := <-finished; err != nil {
t.Fatal(err)
}
}
func TestPhase173MeasuredProfiles(t *testing.T) {
dir := t.TempDir()
stop, err := startPhase173Profiles(dir)
if err != nil {
t.Fatal(err)
}
deadline := time.Now().Add(25 * time.Millisecond)
for time.Now().Before(deadline) {
runtime.Gosched()
}
if err := stop(); err != nil {
t.Fatal(err)
}
for _, name := range []string{"cpu.pprof", "heap.pprof", "allocs.pprof"} {
info, err := os.Stat(filepath.Join(dir, name))
if err != nil {
t.Fatal(err)
}
if info.Size() == 0 {
t.Fatalf("%s is empty", name)
}
}
}
func TestPhase173FixedWorkContract(t *testing.T) {
for _, writers := range []int{1, 2, 4, 8} {
for _, shape := range []string{"sequential_4k", "scattered_4k", "batch_16", "mounted_mixed"} {
cfg, err := newPhase173FixedWorkConfig(shape, writers)
if err != nil {
t.Fatalf("shape=%s writers=%d: %v", shape, writers, err)
}
if cfg.APILogicalBlocks() < 16000 || cfg.APILogicalBlocks() > 16384 {
t.Fatalf("shape=%s logical blocks=%d want [16000,16384]", shape, cfg.APILogicalBlocks())
}
if cfg.WarmupLogicalBlocks() < 1000 || cfg.WarmupLogicalBlocks() > 1024 {
t.Fatalf("shape=%s warmup logical blocks=%d want [1000,1024]", shape, cfg.WarmupLogicalBlocks())
}
for index := 0; index < cfg.APIOperations; index++ {
start, blocks := cfg.operation(index, 0)
if start+uint32(blocks) > phase173FixedWorkRegionBlocks {
t.Fatalf("shape=%s op=%d range=[%d,%d) exceeds measured region", shape, index, start, start+uint32(blocks))
}
}
}
}
if _, err := newPhase173FixedWorkConfig("unknown", 4); err == nil {
t.Fatal("unknown shape accepted")
}
if _, err := newPhase173FixedWorkConfig("sequential_4k", 3); err == nil {
t.Fatal("unsupported writer count accepted")
}
}
func TestPhase173WALStoreFixedWork(t *testing.T) {
shape := os.Getenv(phase173FixedWorkShapeEnv)
if shape == "" {
t.Skip("formal fixed-work run requires SW_BLOCK_PHASE173_SHAPE")
}
writers, err := strconv.Atoi(os.Getenv(phase173FixedWorkWritersEnv))
if err != nil {
t.Fatalf("parse %s: %v", phase173FixedWorkWritersEnv, err)
}
cfg, err := newPhase173FixedWorkConfig(shape, writers)
if err != nil {
t.Fatal(err)
}
result, err := runPhase173FixedWork(
t,
cfg,
os.Getenv(phase173FixedWorkRunIDEnv),
os.Getenv(phase173FixedWorkStoreIDEnv),
os.Getenv(phase173FixedWorkStoreEnv),
os.Getenv(phase173FixedWorkReuseEnv) == "true",
)
if err != nil {
t.Fatal(err)
}
encoded, err := json.Marshal(result)
if err != nil {
t.Fatal(err)
}
fmt.Printf("phase173_fixed_work_result=%s\n", encoded)
}
func newPhase173FixedWorkConfig(shape string, writers int) (phase173FixedWorkConfig, error) {
if writers != 1 && writers != 2 && writers != 4 && writers != 8 {
return phase173FixedWorkConfig{}, fmt.Errorf("phase173: writers=%d want one of 1,2,4,8", writers)
}
cfg := phase173FixedWorkConfig{Shape: shape, Writers: writers}
switch shape {
case "sequential_4k", "scattered_4k":
cfg.APIOperations = 16384
cfg.WarmupAPIOps = 1024
case "batch_16":
cfg.APIOperations = 1024
cfg.WarmupAPIOps = 64
case "mounted_mixed":
// 640 fixed cycles of 4K, 16K, 64K, and 16K requests.
cfg.APIOperations = 2560
cfg.WarmupAPIOps = 160
default:
return phase173FixedWorkConfig{}, fmt.Errorf("phase173: unsupported shape %q", shape)
}
return cfg, nil
}
func (c phase173FixedWorkConfig) APILogicalBlocks() uint64 {
return phase173LogicalBlocks(c.Shape, c.APIOperations)
}
func (c phase173FixedWorkConfig) WarmupLogicalBlocks() uint64 {
return phase173LogicalBlocks(c.Shape, c.WarmupAPIOps)
}
func phase173LogicalBlocks(shape string, operations int) uint64 {
var total uint64
for index := 0; index < operations; index++ {
_, blocks := phase173Operation(shape, index, 0)
total += uint64(blocks)
}
return total
}
func (c phase173FixedWorkConfig) operation(index int, base uint32) (uint32, int) {
return phase173Operation(c.Shape, index, base)
}
func phase173Operation(shape string, index int, base uint32) (uint32, int) {
switch shape {
case "sequential_4k":
return base + uint32(index), 1
case "scattered_4k":
return base + uint32((index*7919)%phase173FixedWorkRegionBlocks), 1
case "batch_16":
return base + uint32(index*16), 16
case "mounted_mixed":
pattern := [...]int{1, 4, 16, 4}
cycle := index / len(pattern)
position := index % len(pattern)
start := cycle * 25
for i := 0; i < position; i++ {
start += pattern[i]
}
return base + uint32(start), pattern[position]
default:
panic("validated phase173 shape reached operation planner: " + shape)
}
}
func runPhase173FixedWork(
t *testing.T,
cfg phase173FixedWorkConfig,
runID string,
storeID string,
storeDir string,
reuseStore bool,
) (phase173FixedWorkResult, error) {
t.Helper()
if storeDir == "" {
storeDir = t.TempDir()
}
if storeID == "" {
storeID = runID
}
if err := os.MkdirAll(storeDir, 0o755); err != nil {
return phase173FixedWorkResult{}, err
}
storePath := filepath.Join(storeDir, fmt.Sprintf("phase173-%s-%d-%s.store", cfg.Shape, cfg.Writers, storeID))
var s *WALStore
var err error
storeReused := false
if reuseStore {
if _, statErr := os.Stat(storePath); statErr == nil {
s, err = OpenWALStore(storePath)
if err == nil {
_, err = s.Recover()
}
storeReused = err == nil
} else if !os.IsNotExist(statErr) {
return phase173FixedWorkResult{}, statErr
}
}
if s == nil && err == nil {
if removeErr := os.Remove(storePath); removeErr != nil && !os.IsNotExist(removeErr) {
return phase173FixedWorkResult{}, removeErr
}
s, err = CreateWALStore(storePath, phase173FixedWorkNumBlocks, phase173FixedWorkBlockSize)
}
if err != nil {
if s != nil {
_ = s.Close()
}
return phase173FixedWorkResult{}, err
}
closed := false
defer func() {
if !closed {
_ = s.Close()
}
if !reuseStore {
_ = os.Remove(storePath)
}
}()
if s.flusher == nil || s.flusher.interval != 100*time.Millisecond {
return phase173FixedWorkResult{}, fmt.Errorf("phase173: flusher interval=%v want 100ms", s.flusher.interval)
}
payloads := phase173Payloads(cfg.Writers)
if _, _, err := runPhase173Operations(s, cfg, cfg.WarmupAPIOps, phase173FixedWorkRegionBlocks, payloads, false); err != nil {
return phase173FixedWorkResult{}, fmt.Errorf("phase173 warmup: %w", err)
}
warmupLSN, err := s.Sync()
if err != nil {
return phase173FixedWorkResult{}, fmt.Errorf("phase173 warmup sync: %w", err)
}
if err := s.flusher.Stop(); err != nil {
return phase173FixedWorkResult{}, fmt.Errorf("phase173 warmup drain: %w", err)
}
_, _, warmupHeadLSN := s.Boundaries()
if s.dm.len() != 0 || s.CheckpointLSN() != warmupLSN || warmupHeadLSN != warmupLSN {
return phase173FixedWorkResult{}, fmt.Errorf(
"phase173 warmup drain incomplete dirty=%d checkpoint=%d head=%d synced=%d",
s.dm.len(), s.CheckpointLSN(), warmupHeadLSN, warmupLSN,
)
}
control := phase173MeasurementControl{dir: os.Getenv(phase173FixedWorkControlEnv)}
controlActive, err := control.awaitStart()
if err != nil {
return phase173FixedWorkResult{}, err
}
defer func() {
if controlActive {
_ = control.finish()
}
}()
s.flusher = newFlusher(s, flusherConfig{Interval: 100 * time.Millisecond})
flusherStarted := make(chan struct{})
go s.flusher.runWithStartSignal(flusherStarted)
<-flusherStarted
writeBefore := s.WriteInstrumentation()
flushBefore := s.FlusherInstrumentation()
syncBefore := s.syncs.Load()
stopProfiles, err := startPhase173Profiles(os.Getenv(phase173FixedWorkProfileEnv))
if err != nil {
return phase173FixedWorkResult{}, err
}
profilesActive := stopProfiles != nil
defer func() {
if profilesActive {
_ = stopProfiles()
}
}()
var memoryBefore runtime.MemStats
runtime.ReadMemStats(&memoryBefore)
foreground, latencies, err := runPhase173Operations(s, cfg, cfg.APIOperations, 0, payloads, true)
if err != nil {
return phase173FixedWorkResult{}, fmt.Errorf("phase173 foreground: %w", err)
}
syncStart := time.Now()
syncedLSN, err := s.Sync()
finalSync := time.Since(syncStart)
if err != nil {
return phase173FixedWorkResult{}, fmt.Errorf("phase173 final sync: %w", err)
}
drainStart := time.Now()
if err := s.flusher.Stop(); err != nil {
return phase173FixedWorkResult{}, fmt.Errorf("phase173 final drain: %w", err)
}
finalDrain := time.Since(drainStart)
var memoryAfter runtime.MemStats
runtime.ReadMemStats(&memoryAfter)
if profilesActive {
if err := stopProfiles(); err != nil {
return phase173FixedWorkResult{}, err
}
profilesActive = false
}
writeAfter := s.WriteInstrumentation()
flushAfter := s.FlusherInstrumentation()
_, _, headLSN := s.Boundaries()
checkpointLSN := s.CheckpointLSN()
dirtyEntries := s.dm.len()
if dirtyEntries != 0 || checkpointLSN != syncedLSN || headLSN != syncedLSN {
return phase173FixedWorkResult{}, fmt.Errorf(
"phase173 incomplete drain dirty=%d checkpoint=%d head=%d synced=%d",
dirtyEntries, checkpointLSN, headLSN, syncedLSN,
)
}
logicalBlocks := cfg.APILogicalBlocks()
if got := writeAfter.WALEncodeOps - writeBefore.WALEncodeOps; got != logicalBlocks {
return phase173FixedWorkResult{}, fmt.Errorf("phase173 WAL encode ops=%d want logical blocks=%d", got, logicalBlocks)
}
appendOps := writeAfter.WALAppendOps - writeBefore.WALAppendOps
if appendOps < uint64(cfg.APIOperations) {
return phase173FixedWorkResult{}, fmt.Errorf("phase173 WAL append ops=%d want at least API operations=%d", appendOps, cfg.APIOperations)
}
writeAtCalls := writeAfter.WALAppendWriteAtCalls - writeBefore.WALAppendWriteAtCalls
wraps := writeAfter.WALAppendWrapCount - writeBefore.WALAppendWrapCount
if writeAtCalls < appendOps || writeAtCalls-appendOps > wraps {
return phase173FixedWorkResult{}, fmt.Errorf("phase173 WAL writeat calls=%d append ops=%d wraps=%d", writeAtCalls, appendOps, wraps)
}
if got := writeAfter.WriteCommitLockWaitOps - writeBefore.WriteCommitLockWaitOps; got != uint64(cfg.APIOperations) {
return phase173FixedWorkResult{}, fmt.Errorf("phase173 commit lock ops=%d want API operations=%d", got, cfg.APIOperations)
}
if got := s.syncs.Load() - syncBefore; got != 1 {
return phase173FixedWorkResult{}, fmt.Errorf("phase173 final sync calls=%d want 1", got)
}
correctnessSamples, err := verifyPhase173Samples(s, cfg, payloads)
if err != nil {
return phase173FixedWorkResult{}, err
}
if controlActive {
if err := control.finish(); err != nil {
return phase173FixedWorkResult{}, err
}
controlActive = false
}
if err := s.Close(); err != nil {
return phase173FixedWorkResult{}, err
}
closed = true
if !reuseStore {
if err := os.Remove(storePath); err != nil && !os.IsNotExist(err) {
return phase173FixedWorkResult{}, err
}
}
p50, p95, p99 := phase173Percentiles(latencies)
logicalBytes := logicalBlocks * phase173FixedWorkBlockSize
result := phase173FixedWorkResult{
Contract: "phase173-fixed-work-v1",
RunID: runID,
StoreID: storeID,
StoreReused: storeReused,
Shape: cfg.Shape,
Writers: cfg.Writers,
APIOperations: cfg.APIOperations,
LogicalBlocks: logicalBlocks,
LogicalBytes: logicalBytes,
WarmupAPIOperations: cfg.WarmupAPIOps,
WarmupLogicalBlocks: cfg.WarmupLogicalBlocks(),
BlockSize: phase173FixedWorkBlockSize,
NumBlocks: phase173FixedWorkNumBlocks,
FlusherIntervalMillis: s.flusher.interval.Milliseconds(),
FlusherPhaseReset: true,
ForegroundNanos: foreground.Nanoseconds(),
ForegroundMiBPerSecond: float64(logicalBytes) / (1024 * 1024) / foreground.Seconds(),
P50Nanos: p50,
P95Nanos: p95,
P99Nanos: p99,
FinalSyncNanos: finalSync.Nanoseconds(),
FinalDrainNanos: finalDrain.Nanoseconds(),
FinalSyncCalls: s.syncs.Load() - syncBefore,
MeasuredAllocBytes: memoryAfter.TotalAlloc - memoryBefore.TotalAlloc,
MeasuredMallocs: memoryAfter.Mallocs - memoryBefore.Mallocs,
MeasuredFrees: memoryAfter.Frees - memoryBefore.Frees,
MeasuredHeapAllocStart: memoryBefore.HeapAlloc,
MeasuredHeapAllocEnd: memoryAfter.HeapAlloc,
SyncedLSN: syncedLSN,
CheckpointLSN: checkpointLSN,
HeadLSN: headLSN,
DirtyEntries: dirtyEntries,
WALCopyOps: writeAfter.WALCopyOps - writeBefore.WALCopyOps,
WALCopyBytes: writeAfter.WALCopyBytes - writeBefore.WALCopyBytes,
WALCopyNanos: writeAfter.WALCopyDurationNanos - writeBefore.WALCopyDurationNanos,
WALEncodeOps: writeAfter.WALEncodeOps - writeBefore.WALEncodeOps,
WALEncodeBytes: writeAfter.WALEncodeBytes - writeBefore.WALEncodeBytes,
WALEncodeNanos: writeAfter.WALEncodeDurationNanos - writeBefore.WALEncodeDurationNanos,
WALChecksumOps: writeAfter.WALChecksumOps - writeBefore.WALChecksumOps,
WALChecksumBytes: writeAfter.WALChecksumBytes - writeBefore.WALChecksumBytes,
WALChecksumNanos: writeAfter.WALChecksumDurationNanos - writeBefore.WALChecksumDurationNanos,
WALAppendOps: writeAfter.WALAppendOps - writeBefore.WALAppendOps,
WALAppendBytes: writeAfter.WALAppendBytes - writeBefore.WALAppendBytes,
WALWriteAtCalls: writeAfter.WALAppendWriteAtCalls - writeBefore.WALAppendWriteAtCalls,
WALWriteAtBytes: writeAfter.WALAppendWriteAtBytes - writeBefore.WALAppendWriteAtBytes,
WALWraps: wraps,
WALPaddingBytes: writeAfter.WALAppendPaddingBytes - writeBefore.WALAppendPaddingBytes,
WALAppendNanos: writeAfter.WALAppendDurationNanos - writeBefore.WALAppendDurationNanos,
WALAppendLockWaitNanos: writeAfter.WALAppendLockWaitNanos - writeBefore.WALAppendLockWaitNanos,
CommitLockWaitOps: writeAfter.WriteCommitLockWaitOps - writeBefore.WriteCommitLockWaitOps,
CommitLockWaitNanos: writeAfter.WriteCommitLockWaitNanos - writeBefore.WriteCommitLockWaitNanos,
DirtyMapUpdateOps: writeAfter.DirtyMapUpdateOps - writeBefore.DirtyMapUpdateOps,
DirtyMapUpdateNanos: writeAfter.DirtyMapUpdateDurationNanos - writeBefore.DirtyMapUpdateDurationNanos,
FlushCycles: flushAfter.CyclesStarted - flushBefore.CyclesStarted,
FlushSnapshotEntries: flushAfter.SnapshotEntries - flushBefore.SnapshotEntries,
FlushCycleNanos: flushAfter.CycleDurationNanos - flushBefore.CycleDurationNanos,
FlushSnapshotNanos: flushAfter.SnapshotDurationNanos - flushBefore.SnapshotDurationNanos,
FlushOpportunityNanos: flushAfter.OpportunityAnalysisNanos - flushBefore.OpportunityAnalysisNanos,
FlushHeaderReads: flushAfter.WALHeaderReadOps - flushBefore.WALHeaderReadOps,
FlushHeaderReadBytes: flushAfter.WALHeaderReadBytes - flushBefore.WALHeaderReadBytes,
FlushHeaderReadNanos: flushAfter.WALHeaderReadDurationNanos - flushBefore.WALHeaderReadDurationNanos,
FlushRecordReads: flushAfter.WALRecordReadOps - flushBefore.WALRecordReadOps,
FlushRecordReadBytes: flushAfter.WALRecordReadBytes - flushBefore.WALRecordReadBytes,
FlushRecordReadNanos: flushAfter.WALRecordReadDurationNanos - flushBefore.WALRecordReadDurationNanos,
FlushRecordDecodeOps: flushAfter.WALRecordDecodeOps - flushBefore.WALRecordDecodeOps,
FlushRecordDecodeBytes: flushAfter.WALRecordDecodeBytes - flushBefore.WALRecordDecodeBytes,
FlushRecordDecodeNanos: flushAfter.WALRecordDecodeDurationNanos - flushBefore.WALRecordDecodeDurationNanos,
FlushDecodeFailures: flushAfter.WALRecordDecodeFailures - flushBefore.WALRecordDecodeFailures,
ValidatedRecords: flushAfter.ValidatedRecords - flushBefore.ValidatedRecords,
SupersededEntries: flushAfter.SupersededEntries - flushBefore.SupersededEntries,
ExtentWriteOps: flushAfter.ExtentWriteOps - flushBefore.ExtentWriteOps,
ExtentWriteBytes: flushAfter.ExtentWriteBytes - flushBefore.ExtentWriteBytes,
ExtentWriteNanos: flushAfter.ExtentWriteDurationNanos - flushBefore.ExtentWriteDurationNanos,
ExtentSyncOps: flushAfter.ExtentSyncOps - flushBefore.ExtentSyncOps,
ExtentSyncNanos: flushAfter.ExtentSyncDurationNanos - flushBefore.ExtentSyncDurationNanos,
CheckpointWriteOps: flushAfter.CheckpointMetadataWriteOps - flushBefore.CheckpointMetadataWriteOps,
CheckpointWriteNanos: flushAfter.CheckpointMetadataWriteNanos - flushBefore.CheckpointMetadataWriteNanos,
CheckpointSyncOps: flushAfter.CheckpointMetadataSyncOps - flushBefore.CheckpointMetadataSyncOps,
CheckpointSyncNanos: flushAfter.CheckpointMetadataSyncNanos - flushBefore.CheckpointMetadataSyncNanos,
ValidationFailures: flushAfter.ValidationFailures - flushBefore.ValidationFailures,
CorrectnessSamples: correctnessSamples,
}
return result, nil
}
type phase173MeasurementControl struct {
dir string
}
func (c phase173MeasurementControl) awaitStart() (bool, error) {
if c.dir == "" {
return false, nil
}
if err := os.MkdirAll(c.dir, 0o755); err != nil {
return false, err
}
for _, name := range []string{"ready", "go", "done", "detached"} {
if err := os.Remove(filepath.Join(c.dir, name)); err != nil && !os.IsNotExist(err) {
return false, err
}
}
if err := os.WriteFile(filepath.Join(c.dir, "ready"), []byte(strconv.Itoa(os.Getpid())), 0o644); err != nil {
return false, err
}
if err := phase173WaitForPath(filepath.Join(c.dir, "go"), 30*time.Second); err != nil {
return false, fmt.Errorf("phase173 measurement start: %w", err)
}
return true, nil
}
func (c phase173MeasurementControl) finish() error {
if c.dir == "" {
return nil
}
if err := os.WriteFile(filepath.Join(c.dir, "done"), []byte("done\n"), 0o644); err != nil {
return err
}
if err := phase173WaitForPath(filepath.Join(c.dir, "detached"), 30*time.Second); err != nil {
return fmt.Errorf("phase173 measurement detach: %w", err)
}
return nil
}
func phase173WaitForPath(path string, timeout time.Duration) error {
deadline := time.Now().Add(timeout)
for time.Now().Before(deadline) {
if _, err := os.Stat(path); err == nil {
return nil
} else if !os.IsNotExist(err) {
return err
}
time.Sleep(10 * time.Millisecond)
}
return fmt.Errorf("timeout waiting for %s", path)
}
func startPhase173Profiles(dir string) (func() error, error) {
if dir == "" {
return nil, nil
}
if err := os.MkdirAll(dir, 0o755); err != nil {
return nil, err
}
cpu, err := os.Create(filepath.Join(dir, "cpu.pprof"))
if err != nil {
return nil, err
}
if err := pprof.StartCPUProfile(cpu); err != nil {
_ = cpu.Close()
return nil, err
}
return func() error {
pprof.StopCPUProfile()
var errs []error
if err := cpu.Close(); err != nil {
errs = append(errs, err)
}
runtime.GC()
for _, name := range []string{"heap", "allocs"} {
file, err := os.Create(filepath.Join(dir, name+".pprof"))
if err != nil {
errs = append(errs, err)
continue
}
profile := pprof.Lookup(name)
if profile == nil {
errs = append(errs, fmt.Errorf("phase173 profile %s unavailable", name))
} else if err := profile.WriteTo(file, 0); err != nil {
errs = append(errs, err)
}
if err := file.Close(); err != nil {
errs = append(errs, err)
}
}
return errors.Join(errs...)
}, nil
}
func phase173Payloads(writers int) []map[int][][]byte {
payloads := make([]map[int][][]byte, writers)
for worker := 0; worker < writers; worker++ {
payloads[worker] = make(map[int][][]byte)
for _, count := range []int{1, 4, 16} {
blocks := make([][]byte, count)
for block := range blocks {
blocks[block] = make([]byte, phase173FixedWorkBlockSize)
blocks[block][0] = byte(worker + 1)
blocks[block][1] = byte(count)
blocks[block][2] = byte(block)
}
payloads[worker][count] = blocks
}
}
return payloads
}
func runPhase173Operations(
s *WALStore,
cfg phase173FixedWorkConfig,
operations int,
base uint32,
payloads []map[int][][]byte,
recordLatency bool,
) (time.Duration, []int64, error) {
latencies := make([]int64, operations)
start := make(chan struct{})
var wg sync.WaitGroup
var ready sync.WaitGroup
var firstErr error
var errOnce sync.Once
for worker := 0; worker < cfg.Writers; worker++ {
wg.Add(1)
ready.Add(1)
go func(worker int) {
defer wg.Done()
ready.Done()
<-start
for index := worker; index < operations; index += cfg.Writers {
lba, blocks := cfg.operation(index, base)
opStart := time.Now()
var err error
if blocks == 1 {
_, err = s.Write(lba, payloads[worker][1][0])
} else {
_, err = s.WriteBatch(lba, payloads[worker][blocks])
}
if recordLatency {
latencies[index] = time.Since(opStart).Nanoseconds()
}
if err != nil {
errOnce.Do(func() { firstErr = err })
return
}
}
}(worker)
}
ready.Wait()
begin := time.Now()
close(start)
wg.Wait()
return time.Since(begin), latencies, firstErr
}
func verifyPhase173Samples(s *WALStore, cfg phase173FixedWorkConfig, payloads []map[int][][]byte) (int, error) {
indexes := map[int]struct{}{0: {}, cfg.APIOperations / 2: {}, cfg.APIOperations - 1: {}}
for worker := 0; worker < cfg.Writers; worker++ {
indexes[worker] = struct{}{}
}
ordered := make([]int, 0, len(indexes))
for index := range indexes {
ordered = append(ordered, index)
}
sort.Ints(ordered)
samples := 0
for _, index := range ordered {
if index < 0 || index >= cfg.APIOperations {
continue
}
worker := index % cfg.Writers
lba, blocks := cfg.operation(index, 0)
for _, block := range []int{0, blocks - 1} {
data, err := s.Read(lba + uint32(block))
if err != nil {
return samples, err
}
want := payloads[worker][blocks][block]
if len(data) != len(want) || data[0] != want[0] || data[1] != want[1] || data[2] != want[2] {
return samples, fmt.Errorf("phase173 data mismatch shape=%s op=%d block=%d", cfg.Shape, index, block)
}
samples++
if blocks == 1 {
break
}
}
}
return samples, nil
}
func phase173Percentiles(samples []int64) (int64, int64, int64) {
ordered := append([]int64(nil), samples...)
sort.Slice(ordered, func(i, j int) bool { return ordered[i] < ordered[j] })
at := func(percent int) int64 {
index := (len(ordered)*percent + 99) / 100
if index > 0 {
index--
}
return ordered[index]
}
return at(50), at(95), at(99)
}
@@ -0,0 +1,17 @@
//go:build swblock_testtools
package storage
// ResetFlusherForMeasurement restarts the default flusher from a known tick
// origin. It is available only to fixed-work test binaries built with the
// swblock_testtools tag and is never part of a shipped product binary.
func (s *WALStore) ResetFlusherForMeasurement() error {
if err := s.flusher.Stop(); err != nil {
return err
}
s.flusher = newFlusher(s, flusherConfig{})
started := make(chan struct{})
go s.flusher.runWithStartSignal(started)
<-started
return nil
}
-217
View File
@@ -1,217 +0,0 @@
# Current Plan: Phase 173 Storage Execution Architecture Decision
Status: active evidence-first architecture milestone.
## Why This Is Next
Phases 167-172 rejected five plausible optimizations without weakening their
gates:
- a parallel WAL backend did not beat the shipped path;
- native `io_uring` reduced no dominant persistence round;
- segmented group commit did not scale;
- staged append ownership had no stable batching headroom;
- extent coalescing opportunity was workload-dependent;
- WAL materialization cut physical reads but improved four-writer throughput
only `1.068x` and produced a `2.031x` sample range.
The Phase 172 CPU profile explains why another local patch is unlikely to
close the gap:
```text
flusher.flushOnceInternal cumulative CPU: 38.6%
WALStore.Write cumulative CPU: 34.2%
syscall flat CPU: 32.9%
foreground WAL pwrite cumulative CPU: 17.8%
flusher pread cumulative CPU: 13.3%
mutex lock/spin cumulative CPU: about 11%
```
No single stage dominates. Foreground append, background WAL readback, extent
writeback, fsync, and lock scheduling share one file and one volume-level
execution context. Vitastor's useful lesson is not a specific algorithm to
copy; it is to make journal/data ownership, queue depth, durability boundaries,
and completion order explicit before optimizing.
Phase 173 is therefore one large decision-and-delivery milestone. It first
stabilizes the measurement model, then attributes the complete shipped path,
then selects at most one architectural candidate. Implementation, recovery,
replication, mounted validation, and promotion remain in this phase rather
than being split into many semantic micro-phases.
## Goal
Produce one defensible answer to:
```text
Which architectural boundary, if any, can materially improve shipped
WALStore throughput while preserving its durability and recovery contract?
```
The eligible outcomes are:
1. implement and promote one evidence-selected architecture;
2. implement and retain one opt-in candidate with named blockers;
3. reject all candidates and publish the measured shipped-backend envelope.
All three are valid. Repeating a previously rejected mechanism without new
evidence is not.
## Non-Goals
- No immediate `io_uring`, SQPOLL, fixed-buffer, `O_DIRECT`, FUA, or raw-device
implementation.
- No automatic switch from `walstore` to `parallel-walstore` or `smartwal`.
- No disk-format change before a format/recovery design is selected.
- No disabled-flusher, checkpoint-free, page-cache-only, or sink-only number
may be presented as product throughput.
- No frontend, replication, or mounted result may be inferred from an engine
microbenchmark.
- No threshold changes after candidate results are visible.
## Required Invariants
1. Acknowledged writes remain recoverable after process kill and host restart.
2. Checkpoint and recyclable tail never advance over incomplete work.
3. Same-LBA order is deterministic; cross-LBA concurrency cannot publish a
non-contiguous durable frontier.
4. Direct BASE/rebuild ownership cannot race with background writeback.
5. WAL corruption and malformed geometry fail closed with typed evidence.
6. Sync fences every write admitted before the call and does not wait for work
admitted later.
7. Close blocks new mutation, drains owned work, and reports terminal failure.
8. RF3 acknowledgement and catch-up semantics remain unchanged.
9. Memory and queue ownership are bounded and visible.
10. Rejected candidates leave the shipped format and defaults unchanged.
## Deliverables
### D1. Deterministic Fixed-Work Measurement Contract
- Replace Go benchmark auto-calibration as the admission source with a
fixed-operation harness. Keep Go benchmarks as diagnostics only.
- Use a predeclared operation count, warmup, file size, LBA sequence, writer
count, 100 ms flusher, one final Sync, and complete drain.
- Run ordinary sequential/scattered 4 KiB, explicit 16-block batch, and
mounted-sized mixed write shapes at 1/2/4/8 writers.
- Record foreground wall time and p50/p95/p99 separately from Sync/drain.
- Record CPU affinity, scheduler, kernel, filesystem, mount options, device,
page-cache policy, free space, temperature/throttling evidence, and
background load.
- Require two independent five-run baseline sets with four-writer max/min
range at most `1.25x` before any architecture admission. If the harness
cannot meet that bound, fix the harness/lab and stop.
### D2. Complete Shipped-Path Attribution
- Correlate product counters with exact-path `strace`, `perf stat`, CPU/memory
profiles, lock wait, `iostat`, and final checkpoint evidence.
- Attribute foreground WAL encode/copy/CRC/pwrite/lock, flusher
snapshot/pread/decode/extent-pwrite/fsync/checkpoint, replication wait, and
frontend cost separately.
- Report time and operation count, not percentages alone.
- Prove all counters reconcile with fixed logical operations and bytes.
### D3. Diagnostic Architecture Controls
Run test-only controls in the same session; none are product candidates:
- foreground append ceiling with writeback deferred, clearly labeled
non-durable/non-product;
- prefilled flusher-only drain with no foreground writers;
- current shared-file WAL/extent path versus a same-device split-file scratch
control;
- current volume lock versus a bounded no-contention single-writer control;
- engine-only versus NVMe/TCP frontend and RF1 versus RF3 acknowledgement.
Select at most one direction:
- **Owner/queue redesign** only if lock/scheduling is a stable dominant cost;
- **WAL/extent media separation** only if same-file I/O/fsync interference is
a stable dominant cost;
- **No backend change** if frontend, replication, device, or benchmark
variance dominates or the shipped path already meets the target envelope.
### D4. Selected Architecture Contract
Required only when D3 selects a candidate.
- Define owner, queue, backpressure, durability frontier, checkpoint, recycle,
Close, and failure semantics before code.
- If storage layout changes, version it explicitly and define create, reopen,
upgrade refusal, rollback refusal, support-bundle evidence, and cleanup.
- Add one dry-run/diagnostic proof and one fail-closed rejected operation
before implementing mutation.
- Independent design review must find no unresolved correctness blocker.
### D5. Bounded Candidate Implementation
- Implement only the selected architecture behind an internal or explicit
opt-in boundary.
- Add no second candidate and no speculative configurability.
- Keep allocations, queues, buffers, and in-flight operations bounded.
- Add exact counters for ownership, queue depth, I/O rounds, bytes, wait,
completion, failure, and fallback.
### D6. Correctness, Recovery, And Replication Gate
- Same-LBA and cross-LBA concurrency, partial writes, batch wrap, WAL pressure,
Sync/Close, direct BASE, recycle floors, malformed records, and crash
windows.
- Reopen, `ScanLBAs`, catch-up, returned-replica rebuild, RF1, and RF3
component suites.
- CGO race repetition and real Linux SIGKILL windows.
- No fallback or recovery branch may hide candidate failure.
### D7. Same-Run Performance Admission
Use the D1 fixed-work harness and unchanged thresholds:
- one-writer ordinary throughput at least `0.95x` shipped baseline;
- four-writer ordinary median at least `1.30x` shipped baseline;
- candidate four-writer max/min range at most `1.25x`;
- ordinary four-writer p99 no worse than `1.10x`;
- no workload regresses more than 10%;
- failed operations/cycles zero and checkpoint coverage complete;
- product counters agree with OS/device evidence.
Reject and remove the candidate if any required condition fails.
### D8. Mounted RF1/RF3 Close Gate
Run only after D7 admits the candidate:
- exact matching product/CSI images;
- mounted NVMe/TCP RF1 concurrent write/read/checksum, sustained pressure,
restart, and zero-residue cleanup;
- RF3 sync-quorum with delayed peer, catch-up/rebuild, restart, honest status,
and continuous mounted I/O;
- same-session shipped baseline/candidate comparison;
- no default promotion until both correctness and performance gates pass.
## Stop Rules
Stop before implementation when:
- fixed-work baseline remains noisier than `1.25x`;
- counters do not reconcile with logical work;
- diagnostic controls identify no dominant architecture boundary;
- the proposed direction repeats a Phase 167-172 rejection without new
evidence;
- the candidate requires weaker durability, recovery, corruption, cleanup,
or RF3 semantics;
- benefit exists only in a non-product control.
## Exit Criteria
```text
stable fixed-work baseline
-> complete shipped-path attribution
-> diagnostic architecture controls
-> one selected design or honest no-change decision
-> bounded implementation only if selected
-> correctness/recovery/replication
-> same-run admission
-> mounted RF1/RF3 only if admitted
-> promote, retain opt-in with blockers, or remove
```
@@ -0,0 +1,61 @@
# Finished Plan: Phase 173 Storage Execution Architecture Decision
Status: closed with the evidence-selected **no backend change** outcome.
## Product Question
Phase 173 asked which storage execution boundary, if any, could materially
improve shipped WALStore throughput without weakening durability, recovery,
checkpoint, replication, or cleanup semantics.
## Delivered
- D1 replaced auto-calibrated admission data with a deterministic fixed-work
Linux harness. Two independent sets and all four required four-writer shapes
passed the `1.25x` stability gate.
- D2 reconciled 16,000 logical blocks with product counters, exact `strace`,
perf, CPU/memory profiles, iostat, and complete checkpoint/drain evidence.
- D3 measured shipped concurrent execution, deferred foreground work,
flusher-only drain, shared/split-file scratch, RF1 durable adapter, RF3 TCP,
and mounted NVMe/TCP.
- The mounted close gate now waits for the exact PV to be deleted before CSI
teardown and proves zero residue.
## Decision
No local backend architecture was selected:
```text
owner_queue_signal=false
writeback_interference_signal=false
media_separation_signal=false
counterfactual_control_stability_gate=inconclusive
diagnostic_controls_candidate_eligible=false
architecture_candidate_selected=false
```
The stable shipped control reached `255.743 MiB/s`; the split-file scratch path
was `0.993x` the shared path. Deferred-writeback controls did not expose a
useful product ceiling and two counterfactual groups were too noisy for
candidate admission. Implementing a storage owner, media split, `io_uring`, or
format change would therefore be speculation.
D4-D8 were intentionally not run because they require an admitted candidate.
WALStore, its format, durability behavior, and defaults remain unchanged.
## Next Boundary
The diagnostic adapter/frontend/replication results are materially below the
local engine envelope and RF3 four-writer ACK wait increased sharply. These
numbers are not directly comparable throughput claims, but they move the next
investigation above the backend: Phase 174 measures the complete
frontend/adapter/replication execution path with one fixed contract before
selecting any implementation.
## Evidence
- `internal/docs/qa-assignments/phase173-d1-fixed-work-baseline-qa-signoff.md`
- `internal/docs/qa-assignments/phase173-d2-shipped-path-attribution-qa-signoff.md`
- `internal/docs/qa-assignments/phase173-d3-architecture-decision-qa-signoff.md`
No user-visible feature or release claim changed in this phase.
@@ -0,0 +1,193 @@
# Finished Plan: Phase 174 Frontend And Replication Execution Architecture
Status: closed with no architecture candidate. Phase 173 closed with no
storage-backend change. Phase 174 D1
completed its local fixed-work matrix at `ed270f3`: direct WALStore was stable,
but durable-adapter RF1 remained above the unchanged `1.25x` range limit. D1 is
HOLD. D2's RF1 slice at `4034f37` reconciled all counters and attributed the
variance to foreground/background flusher overlap rather than an adapter CPU
hotspot. The distinct-node RF3 slice passed at `7d75a47`: 15 primary samples,
30 live probes, eight real rebuilds, six independently reopened remote stores,
and zero residue. Its one-writer shape remained unstable and the management-LAN
numbers select no candidate. The NVMe/TCP RF1 slice passed at `706b173`: all 30
rows reconciled from protocol command through recovered WAL bytes, and the
four-writer admission shape was stable at `1.035x`. Detailed phase attribution
passed at `c588800`: all 30 rows reconciled six target phases, Linux race passed,
and the current run was stable at `1.019x/1.037x/1.121x` for one/four/eight IO
queues. Four-queue accumulated latency splits into R2T collection `30.10 us/op`,
client/wire residual `15.92 us/op`, handler `8.20 us/op`, completion send
`3.71 us/op`, and smaller receive/dispatch/queue phases. Cross-run D1 stability
remains HOLD because the prior semantically identical one-queue run reached
`1.530x`; instrumentation alone is not a stability fix. The exact mounted
kernel gate passed at `415942e`: all 8,200 writes were inline, none used R2T,
all phase counters reconciled, the handler bucket dominated, mounted data was
verified, and cleanup was zero. The synthetic R2T shape therefore does not
represent the shipped mounted path. No architecture implementation is eligible.
## Why This Is Next
Phase 173 proved the shipped WALStore engine is stable enough to measure and
found no evidence for an owner/queue rewrite or WAL/extent media split. The
remaining diagnostic gap is above the backend:
```text
WALStore shipped control, 4 writers: 255.743 MiB/s
RF1 durable adapter diagnostic: 61.28 MiB/s
RF3 TCP diagnostic, 1 writer: 91.56 MiB/s
RF3 TCP diagnostic, 4 writers: 14.69 MiB/s
mounted NVMe/TCP sequential write: 127.49 MiB/s
```
These values use different work shapes and cannot be divided into a valid
performance ratio. They do show that another backend patch is the wrong next
move. Phase 174 creates one comparable contract across frontend, adapter,
replication, and mounted paths, attributes each boundary, and selects at most
one non-backend architecture candidate.
## Goal
Answer one product question:
```text
Which frontend, adapter, or replication ownership boundary limits concurrent
shipped writes, and can one bounded change improve it without weakening ACK,
ordering, recovery, fencing, or mounted I/O semantics?
```
Valid outcomes are promote one candidate, retain one opt-in candidate with
named blockers, or select no change. A diagnostic with different durability or
payload semantics is not a candidate.
## Non-Goals
- No WALStore format or backend ownership redesign.
- No RDMA transport optimization; Phase 174 first establishes the TCP shipped
path contract.
- No weakened RF3 quorum, asynchronous acknowledgement, sink peer, disabled
persistence, or loopback-only number as a product claim.
- No batch/request-size change before identical logical work and durability
are proven.
- No broad rewrite of CSI, NVMe target, replication, and adapter together.
## Required Invariants
1. RF1 and RF3 ACK profiles remain explicit and unchanged.
2. Acknowledged writes survive process restart and required replica recovery.
3. Same-LBA order, global durable frontier, and fencing remain deterministic.
4. Per-peer and frontend queues are bounded, observable, and fail closed.
5. Backpressure cannot silently drop, reorder, or acknowledge work early.
6. Sync fences all prior admitted work and excludes later work.
7. Peer failure, timeout, close, and reconnect have terminal evidence.
8. Mounted data and checksums remain correct through restart and catch-up.
9. No fallback path may hide candidate failure.
10. Rejected work leaves defaults and shipped behavior unchanged.
## Deliverables
### D1. Comparable Fixed-Work Pipeline Contract
- Define one fixed logical payload, LBA sequence, operation count, writer
matrix, queue limits, ACK profile, warmup, Sync, and complete drain.
- Run engine, durable adapter RF1, RF3 real TCP, NVMe/TCP target, and mounted
controls with identical logical work and an explicit unchanged ACK profile
at each layer. Compare throughput ratios only inside compatible profiles.
- Record one/four/eight writers, throughput, p50/p95/p99, Sync/drain, CPU
affinity, network route, device, and run stability.
- Require two independent five-run sets with the admission shape at or below
`1.25x` max/min before selecting a candidate.
- Where a layer cannot implement the identical contract, label it diagnostic
and do not compare its throughput ratio.
### D2. Complete Boundary Attribution
- Measure frontend parse/copy/queue/completion, adapter mapping and commit,
replication fanout, per-peer enqueue/send/ACK, backend commit, Sync, and
completion publication.
- Reconcile logical operations and bytes with every queue, peer, backend, TCP,
and acknowledgement counter.
- Correlate product counters with CPU/heap/block profiles, socket statistics,
`perf`, and network/device evidence.
- Separate accumulated concurrent wait from wall time.
Result: complete. RF1 variance followed flusher overlap, RF3 management-LAN
evidence selected no candidate, synthetic NVMe/TCP phases reconciled, and the
mounted kernel cross-check proved that the synthetic R2T-dominant shape does
not occur on the shipped mounted write path.
### D3. Architecture Controls And Selection
Run test-only controls for:
- direct backend versus durable adapter with identical fixed work;
- frontend request/completion overhead without bypassing durability;
- RF1 versus RF3 with one peer delayed and with queue limits reached;
- per-request versus bounded batch submission where ordering is unchanged;
- one shared replication owner versus bounded per-peer ownership.
Select at most one direction only when the effect is stable and at least
`1.30x` on the four-writer admission shape. Otherwise select no change.
Result: no change selected. No measured frontend, adapter, or replication
direction met the stability, comparable-shape, and gain requirements together.
### D4. Selected Architecture Contract
Required only if D3 selects a candidate. Define owner, queue, admission,
backpressure, ordering, ACK frontier, Sync, Close, reconnect, failure, and
evidence semantics before implementation. Require independent correctness
review and one fail-closed rejected operation.
### D5. Bounded Candidate Implementation
Implement only the selected direction behind an internal or explicit opt-in
boundary. Add exact counters for queue depth, wait, batches, bytes, completion,
failure, timeout, and fallback. Keep all memory and in-flight work bounded.
### D6. Correctness, Failure, And Recovery
- Same/cross-LBA concurrency, partial requests, queue pressure, Sync/Close,
timeout, peer loss, reconnect, process kill, and malformed completion.
- RF1 and RF3 recovery, catch-up, returned-replica rebuild, and authority
fencing.
- Race tests and real Linux failure windows; zero hidden fallback.
### D7. Same-Run Performance Admission
- one-writer throughput at least `0.95x` shipped;
- four-writer median at least `1.30x` shipped;
- candidate max/min at most `1.25x`;
- four-writer p99 no worse than `1.10x` shipped;
- no required shape regresses more than 10%;
- zero failed work and complete counter reconciliation.
Reject and remove the candidate if any required gate fails.
### D8. Mounted RF1/RF3 Close Gate
- matching product/CSI images and 100 GbE data-plane route;
- mounted NVMe/TCP fixed-work comparison against the same-session shipped
path;
- RF1 restart and RF3 delayed-peer/catch-up while mounted checksums continue;
- honest status, no false Ready, safe detach, exact PV deletion before CSI
teardown, and zero residue;
- promote no default until correctness and performance both pass.
## Stop Rules
Stop before implementation if the comparable baseline is unstable, counters
do not reconcile, no single boundary dominates, the gain exists only in a
weakened/non-product control, or the candidate requires weaker durability,
recovery, fencing, or cleanup semantics.
## Exit Criteria
```text
comparable fixed-work contract
-> complete frontend/adapter/replication attribution
-> one selected design or honest no-change decision
-> bounded implementation only if selected
-> correctness and recovery
-> same-run performance admission
-> mounted RF1/RF3 close
-> promote, retain opt-in with blockers, or remove
```
+29 -14
View File
@@ -131,9 +131,10 @@ This is the short internal roadmap. Keep it current and readable.
168 then rejected native `io_uring` execution, Phase 169 rejected a
segmented group-commit format, and Phase 170 rejected a default-WAL staged
append owner. Phase 171 hardened the shipped checkpoint path and rejected
bounded extent coalescing at its D1 admission gate. Phase 172 now targets the
stable two-read WAL materialization amplification without adding another
backend or append queue.
bounded extent coalescing at its D1 admission gate. Phase 172 reduced WAL
materialization reads but rejected the candidate on performance stability.
Phases 173-174 then completed backend and frontend/replication architecture
decisions with no qualifying change; shipped defaults remain unchanged.
Do not skip from scripts directly to mutating operator lifecycle. Helm has
stabilized the installation contract, and Phase 35 added read-only CRD status,
@@ -611,12 +612,17 @@ rebuild, delete safety, or cleanup must start as a separate gated phase.
`1.15x`, and candidate range was `2.031x` against the `1.50x` bound. The
candidate and measurement-only overhead were removed. Legacy range-trim and
recovery correctness fixes remain.
- Active next: Phase 173 establishes a fixed-work performance contract,
attributes the complete shipped path, and uses diagnostic controls to choose
at most one architecture direction: owner/queue redesign, WAL/extent media
separation, or no backend change. No candidate is implemented until the
baseline range is at most `1.25x` and OS/device evidence reconciles with
product counters.
- Closed decision: Phase 173 established a stable fixed-work performance
contract, reconciled the complete shipped WALStore path with product and OS
evidence, and selected no backend change. Owner/queue, deferred-writeback,
and media-separation controls produced no stable `1.30x` direction signal;
WALStore and its defaults remain unchanged.
- Closed decision: Phase 174 moved the same discipline above the backend and
selected no frontend, adapter, or replication architecture change. RF1/RF3
and NVMe/TCP counters reconciled, but no direction met comparable-shape,
stability, and gain requirements together. The mounted Linux kernel path
used inline Write capsules rather than the synthetic gate's R2T shape, so an
R2T optimization was explicitly rejected as a shipped-path candidate.
- Protocol hardening now has a dedicated working area under
`internal/docs/protocol/`. New protocol semantics should update the control
model, invariant ledger, and anti-pattern checklist there before release
@@ -1268,11 +1274,20 @@ Approximate engineering effort if scope remains tight:
the pre-declared gate. The candidate was removed while independent recovery
fixes remained. The finished plan is
`internal/docs/finished-plans/phase172_finishedplan_wal_materialization_pipeline.md`.
- Phase 173 Storage Execution Architecture Decision is active. It replaces
auto-calibrated admission data with a fixed-work harness, attributes
foreground, flusher, lock, syscall, fsync, frontend, and replication costs,
and permits only one evidence-selected architecture candidate. The contract
is `internal/docs/current-plan.md`.
- Phase 173 Storage Execution Architecture Decision is closed with no backend
candidate. The exact Linux fixed-work baseline passed on dedicated m02 NVMe;
shipped logical work reconciled with product counters, `strace`, perf,
profiles, iostat, and checkpoint evidence. D3 then found no stable
owner/queue, writeback-interference, or media-separation signal and closed
with a real 100 GbE mounted NVMe/TCP writer/read/cleanup gate. The finished
plan is
`internal/docs/finished-plans/phase173_finishedplan_storage_execution_architecture_decision.md`.
- Phase 174 Frontend And Replication Execution Architecture is closed with no
architecture candidate. RF1 variance followed flusher overlap, the RF3
management-LAN shape remained unstable, and the mounted Linux kernel
NVMe/TCP path proved the synthetic R2T-dominant shape was not representative.
Shipped defaults remain unchanged. The finished plan is
`internal/docs/finished-plans/phase174_finishedplan_frontend_replication_execution_architecture.md`.
- Phase 41-44 are the Operation Layer v0.5 release train: lifecycle-owner
foundation, real API/admission proof, first bounded finalizer mutation, and
delete lifecycle close gate.
@@ -0,0 +1,108 @@
# Phase 173 D1 Fixed-Work Baseline QA Sign-Off
Verdict: **PASS** at `29897cc` on the dedicated m02 NVMe filesystem.
## Source And Run
```text
commit=29897cc
branch=phase173-storage-execution-architecture
host=M02
kernel=Linux 6.17.0-23-generic x86_64
go=go1.25.0 linux/amd64
store_source=/dev/nvme0n1p1
store_filesystem=ext4 rw,noatime
cpu_affinity=0-15
scheduler=SCHED_OTHER priority 0
thermal_celsius=34.0,27.8,34.0
```
```bash
SW_BLOCK_ARTIFACT_DIR=/mnt/smb/work/share/g15d-k8s/20260801T071605Z-phase173-d1-fixed-work-nvme \
SW_BLOCK_PHASE173_STORE_DIR=/data/nvme/block/phase173-d1-stores-29897cc \
bash scripts/run-phase173-fixed-work-baseline-gate.sh \
/tmp/seaweed-block-qa-phase173-d1-29897cc
```
The gate used fixed operations rather than Go benchmark auto-calibration. Each
matrix point ran one full precondition pass against a persistent store. The
measured runs reopened and recovered that same store. The second set used
separate files and reversed shape/writer order.
## Terminal Evidence
```text
contract=phase173-fixed-work-v1
sets=2
four_writer_runs_per_set=5
diagnostic_runs_per_set=1
fixed_work_result_count=64
precondition_runs=32
measured_store_reuse_required=true
flusher_interval_ms=100
flusher_phase_policy=restart_after_warmup_with_start_signal
go_benchmark_autocalibration_allowed=false
fixed_work_counter_reconciliation=true
fixed_work_complete_drain=true
fixed_work_correctness_samples=true
four_writer_stability_gate=pass
architecture_candidate_admission_allowed=true
phase173_fixed_work_baseline_status=ok
```
Every result had one final `Sync`, zero dirty entries, equal
checkpoint/head/synced frontiers, `store_reused=true`, and
`flusher_phase_reset=true`. Logical blocks reconciled with encoded WAL records;
API calls reconciled with commit-lock observations; physical appends, wrap
padding, and `WriteAt` calls reconciled separately.
## Stability Result
```text
shape set1 set2 combined median MiB/s median p99 ns
sequential_4k 1.065 1.143 1.143 208.383 1,144,308
scattered_4k 1.042 1.129 1.129 214.366 1,147,132
batch_16 1.047 1.076 1.078 277.290 5,336,886
mounted_mixed 1.143 1.048 1.143 250.480 3,359,970
limit <=1.250
```
These are engine fixed-work baseline values. They are not mounted NVMe,
frontend, RF3, or release performance claims.
## Harness Findings Retained
Earlier runs correctly held architecture admission and were not relabeled as
passes:
- short 32 MiB samples could finish before one 100 ms flusher period;
- `/tmp` selected the shared OS SATA SSD rather than the dedicated NVMe;
- 256 MiB samples exhausted a different consumer-NVMe write/GC state across
the full matrix;
- recreating sparse store files measured allocator/device churn rather than a
long-lived block volume;
- the flusher ticker started at store creation, so post-warmup foreground runs
inherited a random periodic phase and could report false-fast samples.
The final gate fixes those measurement defects without changing the shipped
WALStore algorithm, durability boundary, default interval, or threshold.
## Additional Validation And Cleanup
```text
linux_storage_tests=pass
linux_storage_race=pass
linux_storage_vet=pass
store_residue_count=0
```
Artifact:
```text
/mnt/smb/work/share/g15d-k8s/20260801T071605Z-phase173-d1-fixed-work-nvme.tar.gz
sha256=760805ac218b0b5e112d56976623669335c593fd1af88cfb3ae0ac190da07db1
```
m02's k3s API was unavailable during preflight. D1 is an engine/filesystem
gate and did not use Kubernetes; this does not weaken its result, but it must
be repaired before any later mounted or cluster gate.
@@ -0,0 +1,72 @@
# Phase 173 D1 Fixed-Work Baseline QA
Source: use the commit that adds this assignment and
`scripts/run-phase173-fixed-work-baseline-gate.sh`.
## Purpose
Prove that architecture admission no longer depends on Go benchmark
auto-calibration. The gate executes a fixed logical workload through the
shipped WALStore path and measures foreground writes separately from the one
final `Sync` and complete flusher drain.
This is a measurement gate, not an architecture or performance promotion.
## Run
Run on the Linux storage host and place the store directory on the filesystem
being evaluated:
```bash
cd /path/to/seaweed_block
export SW_BLOCK_ARTIFACT_DIR=/path/to/results/phase173-d1
export SW_BLOCK_PHASE173_STORE_DIR=/path/on/evaluated/filesystem/phase173-d1-stores
bash scripts/run-phase173-fixed-work-baseline-gate.sh "$PWD"
```
Do not lower run counts or change the `1.25x` threshold after seeing results.
## Required Evidence
- `phase173_fixed_work_baseline_status=ok`
- `fixed_work_result_count=64`
- `fixed_work_counter_reconciliation=true`
- `fixed_work_complete_drain=true`
- `fixed_work_correctness_samples=true`
- `precondition_runs=32`
- `measured_store_reuse_required=true`, with `store_reused=true` in every
measured JSON row
- `flusher_phase_policy=restart_after_warmup_with_start_signal`, with
`flusher_phase_reset=true` in every measured JSON row
- `four_writer_stability_gate=pass`
- `architecture_candidate_admission_allowed=true`
- every `*_writers_4_set_{1,2}_max_min_ratio` and combined ratio is at most
`1.25`
- environment evidence identifies kernel, CPU/affinity/scheduler, filesystem,
mount options, backing device, free space, load, and available thermal data
- `store_source` is the dedicated local block device under evaluation, not the
OS/root filesystem by convenience and never CIFS/NFS/tmpfs/overlay
- the store directory contains no `phase173-*.store` residue after the gate
Each JSON result must show one final sync, `dirty_entries=0`, and equal
checkpoint/head/synced frontiers. WAL encode operations must equal logical
blocks, commit-lock operations must equal fixed API operations, and physical
WAL append calls must reconcile independently with `WriteAt` calls. A batch
may encode 16 records while coalescing them into one physical append. A WAL
wrap may add one separately counted padding `WriteAt`; `wal_wraps` and
`wal_padding_bytes` make that physical I/O explicit.
## Verdict
- `PASS`: all required evidence is present and both independent five-run
four-writer sets remain within the predeclared range. Each fixed-work sample
writes about 64 MiB so foreground execution crosses multiple 100 ms flusher
periods; 1/2/8 writers are diagnostic matrix points, while four writers use
the two independent five-run admission sets. The second set reverses shape
and writer order; the gate syncs between samples and records each set's
starting device/load evidence. Each matrix point first runs one unmeasured
full precondition pass, then reopens and recovers the same allocated store
for measured samples. The two sets never share store files.
- `FAIL`: a correctness, counter, drain, or residue invariant fails.
- `HOLD`: the stability range exceeds `1.25x`; fix the harness or lab before
D2/D3 and do not implement an architecture candidate.
@@ -0,0 +1,172 @@
# Phase 173 D2 Shipped-Path Attribution QA Sign-Off
Verdict: **PASS** at `f780cc4` on the dedicated m02 NVMe filesystem.
## Source And Run
```text
commit=f780cc4
branch=phase173-storage-execution-architecture
host=M02
kernel=Linux 6.17.0-23-generic x86_64
go=go1.25.0 linux/amd64
store_source=/dev/nvme0n1p1
store_filesystem=ext4 rw,noatime
shape=mounted_mixed
writers=4
```
```bash
SW_BLOCK_ARTIFACT_DIR=/mnt/smb/work/share/g15d-k8s/20260801T074011Z-phase173-d2-close \
SW_BLOCK_PHASE173_STORE_DIR=/data/nvme/block/20260801T074011Z-phase173-d2-close-stores \
bash scripts/run-phase173-shipped-path-attribution-gate.sh \
/tmp/seaweed-block-phase173-d2-f780cc4
```
The source directory was a `git archive` of exactly `f780cc4`. The gate used
one preconditioned persistent store, then reopened it for independent plain,
CPU/memory-profile, exact-strace, and exact-perf runs.
## Terminal Evidence
```text
phase173_shipped_path_attribution_status=ok
scope=walstore_engine_checkpoint_path
fixed_work_runs_reconciled=4
product_counter_reconciliation=true
cpu_profile_scope_exact=true
memory_delta_scope_exact=true
heap_profile_scope=post_window_after_gc
allocs_profile_scope=process_cumulative_reference
strace_scope_exact=true
strace_product_counter_reconciliation=true
perf_scope_exact=true
perf_required_events_present=true
iostat_device_observed=true
checkpoint_frontiers_equal=true
complete_drain=true
architecture_candidate_selected=false
optimization_code_present=false
store_residue_count=0
```
The CPU profile covers foreground through final drain. Exact memory deltas use
`runtime.MemStats` over that same window. The heap profile is post-window and
post-GC. Go's allocs profile is process-cumulative and is retained only as a
function-level reference; it is not mislabeled as exact-window evidence.
## Fixed Work And Foreground
```text
logical_operations=2560
logical_blocks=16000
logical_bytes=65536000
foreground_ns=254058894
foreground_mib_per_second=246.006
final_sync_ns=8011919
final_drain_ns=41494323
measured_alloc_bytes=223983976
measured_mallocs=49196
measured_frees=49036
measured_heap_alloc_start=2515616
measured_heap_alloc_end=3764560
```
The three non-strace runs were 235.174-246.006 MiB/s. Exact per-syscall tracing
reduced its own run to 121.445 MiB/s, so the trace is used for operation-count
reconciliation, not throughput admission.
Foreground stage counters from the plain run:
```text
stage operations/bytes cumulative ns
copy 16000 / 65536000 7173141
encode 16000 / 66144000 26635621
checksum 16000 / 66016000 12190529
WAL physical append 2561 / 66145642 26779673
WAL append lock wait 2561 calls implied 275727
volume commit lock wait 2560 203396679
dirty-map update 16000 6492432
```
Encode includes its nested copy and checksum work, so those values must not be
added as independent wall time. Commit-lock wait is accumulated across four
concurrent writers and overlaps elapsed wall time; D2 does not call it a wall
share or select an owner/queue redesign from that number alone.
## Flusher And Checkpoint
```text
stage operations/bytes cumulative ns
complete cycles 3 241180476
snapshot 16000 entries 3229490
opportunity analysis 3 cycles plus written sets 7858511
WAL header pread 16000 / 608000 22757747
WAL record pread 16000 / 66144000 32655078
WAL decode and CRC 16000 / 66144000 40527294
extent pwrite 16000 / 65536000 50519084
extent fsync 3 53255381
checkpoint pwrite 3 46548
checkpoint fsync 3 3456795
unattributed remainder 26874548
```
All 16,000 records were validated and written, with zero decode/validation
failure, superseded entry, dirty entry, or incomplete checkpoint frontier.
## Independent OS Evidence
The controlled test blocked after warmup. `strace` attached before foreground
work and detached after final Sync, complete drain, and ten correctness reads,
but before `Close` metadata I/O.
```text
pread64=32010 = 16000 header + 16000 record + 10 correctness
pwrite64=18564 = 2561 WAL + 16000 extent + 3 checkpoint
sync=7 = 3 extent + 3 checkpoint + 1 final Sync
```
Perf stat ran over the same controlled window with sudo because
`perf_event_paranoid=4`:
```text
task_clock=495298674
cycles=1147474971
instructions=1275404137
cache_misses=7667121
context_switches=4650
cpu_migrations=89
page_faults=2379
```
The exact CPU profile had syscall execution at 36.59% flat,
`flusher.flushOnceInternal` at 46.34% cumulative, WALStore foreground writes at
about 14.6% cumulative, and `readDirtyRecord` at 26.83% cumulative. No single
CPU function establishes an architecture boundary by itself.
## D2 Decision
D2 closes the local shipped WALStore engine/checkpoint attribution. It proves
the complete logical-to-physical I/O accounting and names three facts for D3:
- four-writer commit-lock wait is large but concurrent/overlapping;
- same-file pread/pwrite/fsync and syscall CPU are material;
- the measured window allocates about 224 MB for 62.5 MiB logical data while
retaining only about 3.8 MB at the endpoint.
These are control hypotheses, not selected optimizations. D3 must compare a
no-contention writer, deferred-writeback foreground ceiling, prefilled
flusher-only drain, same-device split-file scratch path, and the engine versus
frontend/RF1/RF3 boundaries before selecting at most one direction.
## Artifact And Cleanup
```text
/mnt/smb/work/share/g15d-k8s/20260801T074011Z-phase173-d2-close.tar.gz
sha256=7647cf7f075afaf1d06a48c1b9ef3256ff864626b70633b000ff40246b6e4e9a
source_dirs_remaining=0
store_files_remaining=0
processes_remaining=0
```
This gate is engine/filesystem-only and does not require Kubernetes.
@@ -0,0 +1,85 @@
# Phase 173 D2 Shipped-Path Attribution QA
Source: use the commit that adds this assignment and
`scripts/run-phase173-shipped-path-attribution-gate.sh`.
## Purpose
Measure the shipped WALStore foreground and checkpoint path with fixed work,
then reconcile product counters against independent operating-system evidence.
This gate adds diagnostic instrumentation only. It does not implement, select,
or admit an architecture candidate.
The current gate covers the local WALStore engine/checkpoint path. Frontend and
replication comparisons remain D3 diagnostic controls and must not be inferred
from this engine result.
## Run
Run on the Linux storage host. The store directory must resolve to the local
block device being evaluated, not the OS root filesystem or a network share:
```bash
cd /path/to/seaweed_block
export SW_BLOCK_ARTIFACT_DIR=/path/to/results/phase173-d2
export SW_BLOCK_PHASE173_STORE_DIR=/path/on/evaluated/filesystem/phase173-d2-stores
bash scripts/run-phase173-shipped-path-attribution-gate.sh "$PWD"
```
The account must have non-interactive sudo for `strace`, `perf stat`, and
signals sent to those root-owned tools. The gate does not need Kubernetes.
## Required Evidence
- `phase173_shipped_path_attribution_status=ok`
- `scope=walstore_engine_checkpoint_path`
- `fixed_work_runs_reconciled=4`
- `product_counter_reconciliation=true`
- `strace_scope_exact=true`
- `strace_product_counter_reconciliation=true`
- `perf_scope_exact=true`
- `perf_required_events_present=true`
- `cpu_profile_scope_exact=true`
- `memory_delta_scope_exact=true`
- `heap_profile_scope=post_window_after_gc`
- `allocs_profile_scope=process_cumulative_reference`
- `iostat_device_observed=true`
- `checkpoint_frontiers_equal=true`
- `complete_drain=true`
- `store_residue_count=0`
- `architecture_candidate_selected=false`
- `optimization_code_present=false`
Inspect the summary's operation, byte, and nanosecond values. Do not report
percentages alone. `wal_encode_ns` contains its nested copy and checksum work;
do not add those three values as if they were independent stages.
The exact strace run must show:
```text
pread64 = flusher header reads + flusher record reads + correctness reads
pwrite64 = WAL WriteAt calls + extent writes + checkpoint writes
fsync/fdatasync = extent syncs + checkpoint syncs + the one final Sync
```
The test blocks immediately after warmup. The gate attaches `strace` or `perf`,
starts the measured foreground work, waits through final Sync, complete drain,
and correctness reads, detaches the tool, and only then permits `Close`. Store
create/recover/warmup and final-close metadata I/O are therefore outside the
exact attribution window.
The CPU profile and memory counter deltas cover foreground work through final
drain. The heap profile is taken after that window and a forced GC. Go's allocs
profile is process-cumulative, so it is retained only as a function-level
reference and is not labeled exact; the `measured_alloc_*` JSON and summary
fields are the exact-window allocation evidence.
## Verdict
- `PASS`: all product counters reconcile across the four independent runs,
exact strace counts match the traced run, required perf events and profiles
are present, iostat names the evaluated device, and cleanup is complete.
- `FAIL`: logical work, bytes, syscall counts, frontiers, profiles, perf, or
cleanup do not reconcile.
- `HOLD`: required Linux tools, sudo access, or a dedicated local block-device
store are unavailable. Do not substitute inferred or whole-process evidence.
@@ -0,0 +1,145 @@
# Phase 173 D3 Architecture Decision QA Sign-Off
Verdict: **PASS / NO BACKEND CHANGE**. Local diagnostic controls ran at
`c4bb1991d750`; the mounted NVMe/TCP close control ran at
`8ba98af72f360` after the teardown gate was hardened.
## Decision
Phase 173 selected no storage-backend candidate. This is an intended terminal
outcome, not an incomplete implementation:
```text
local_architecture_direction=no_backend_change_unstable_counterfactuals
shipped_control_stability_gate=pass
counterfactual_control_stability_gate=inconclusive
diagnostic_controls_candidate_eligible=false
architecture_candidate_selected=false
product_mutation_present=false
```
The authoritative D1 fixed-work baseline remained stable. The smaller D3
counterfactual controls were retained as attribution evidence, but two exceeded
their predeclared `1.25x` range. None of the three predeclared `1.30x` direction
signals fired:
```text
owner_queue_signal=false
writeback_interference_signal=false
media_separation_signal=false
deferred_four_vs_shipped_four_ratio=0.256
deferred_one_vs_deferred_four_ratio=0.557
split_vs_shared_scratch_ratio=0.993
```
Therefore an owner/queue rewrite, WAL/extent media split, or another local
WALStore implementation would not be evidence-selected. D4-D8 are not
applicable under the Phase 173 stop rules.
## Local Controls
The exact Linux run used `/dev/nvme0n1p1`, ext4, CPU set `0,2,4,6`, and
`GOMAXPROCS=4`. Each control had five isolated process runs and used
preconditioned persistent stores.
```text
control median MiB/s max/min
shipped concurrent, 4 writers 255.743 1.203
deferred foreground, 1 writer 36.528 1.010
deferred foreground, 4 writers 65.538 1.539
prefilled flusher 366.112 1.585
shared-file scratch 424.485 1.252
split-file scratch 421.580 1.196
```
All correctness and counter checks passed, the shipped diagnostic stayed
inside its range, no diagnostic was presented as product throughput, and
`store_residue_count=0`.
Earlier control runs that exposed allocation, CPU-placement, process-isolation,
preconditioning, and noisy-benchmark parsing defects remain in the evidence
share. They were not relabeled as passes:
```text
20260801T075555Z-phase173-d3-local
20260801T080104Z-phase173-d3-local
20260801T080352Z-phase173-d3-local
20260801T080623Z-phase173-d3-local
20260801T080904Z-phase173-d3-local
20260801T081147Z-phase173-d3-local
20260801T081426Z-phase173-d3-local
20260801T081634Z-phase173-d3-local
```
## Adapter And Replication Attribution
The fixed-iteration component controls completed without fallback:
```text
RF1 durable adapter: 61.28 MiB/s, 66,845 ns/op
RF3 TCP, 1 writer: 91.56 MiB/s, 28,683 ns/op ACK wait
RF3 TCP, 4 writers: 14.69 MiB/s, 1,068,505 ns/op ACK wait
rf3_queue_saturation_observed=true
rf1_rf3_component_attribution=complete
```
These are component diagnostics with different contracts from the D1 engine
baseline. They do not justify a direct throughput ratio or a backend change.
They do justify measuring the adapter/frontend/replication boundary next.
## Mounted NVMe/TCP Close Control
The final independent run used matching images built from `8ba98af72f360` on
all three schedulable nodes. The application ran on m02, the volume target ran
on m01, and the publish target used the 100 GbE data network rather than the
management LAN:
```text
phase122_nvme_tcp_100gbe_baseline_status=ok
publish_target=10.0.0.1:4420
publish_target_route_dev=enp1s0np0
internal_ip_not_reused_as_performance_target=true
managed_volume_status=ready
managed_volume_reason=first_volume_verified
marker_verified=true
seq_write_mibps=127.49
seq_read_mibps=262.30
small_write_iops=737.75
final_data_verified=true
pv_deleted_before_csi_uninstall=true
cleanup_status=ok
```
Cleanup evidence was zero across Kubernetes resources, NVMe targets, iSCSI,
processes, multipath, and host paths.
## Gate Findings
The first mounted attempt exposed stale image distribution when blockmaster
landed on tp01. The final run imported both exact images to m01, m02, and tp01.
An interrupted attempt also exposed an unsafe gate order: CSI was uninstalled
before the external provisioner had deleted the PV. Commit `8ba98af` now waits
for the exact PV to disappear while CSI is still available and records
`pv_deleted_before_csi_uninstall=true`. A stale VolumeAttachment from the
interrupted run was removed only after its PV was absent and both nodes proved
there was no mount, NVMe connection, target subsystem, or process for its NQN.
The final run began from and returned to a verifier-proven clean baseline.
The live run also produced repeated launcher Deployment/ReplicaSet churn while
the deleted PVC was converging out of master inventory. It did not prevent
safe detach, PV deletion, uninstall, or zero-residue cleanup. It is retained as
future lifecycle-noise evidence, not treated as a Phase 173 backend finding.
## Artifacts
```text
/mnt/smb/work/share/g15d-k8s/20260801T081908Z-phase173-d3-local.tar.gz
sha256=a025832f484a06958c90e7c0049363df0a7f7a0607e65c06fc4f9aeda8231e51
/mnt/smb/work/share/g15d-k8s/20260801T081908Z-phase173-d3-mounted-rerun4.tar.gz
sha256=bc716ea6590091cf730de8710d4a9de8a6abb34395e2424c46b2ac0807b7548b
```
Phase 173 closes with WALStore and all shipped defaults unchanged. README and
user capability claims do not change.
@@ -0,0 +1,99 @@
# Phase 173 D3 Local Architecture Controls QA
Source: use the commit that adds this assignment and
`scripts/run-phase173-architecture-controls-gate.sh`.
## Purpose
Run test-only controls that distinguish writer ownership/lock effects,
foreground-versus-writeback interference, flusher-only capacity, and same-file
versus split-file I/O on one device. Also record fixed-iteration RF1 durable
adapter and RF3 real-TCP acknowledgement costs.
This is not a product candidate or performance promotion. The deferred
writeback control eventually performs a real Sync and complete real flusher
drain, but its foreground rate is a non-product ceiling because sustained
checkpoint/recycle is excluded from that timed window. The split-file control
has no WALStore format or recovery contract.
## Run
```bash
cd /path/to/seaweed_block
export SW_BLOCK_ARTIFACT_DIR=/path/to/results/phase173-d3-local
export SW_BLOCK_PHASE173_STORE_DIR=/path/on/evaluated/filesystem/phase173-d3-stores
export SW_BLOCK_PHASE173_CONTROL_CPUSET=0,2,4,6
bash scripts/run-phase173-architecture-controls-gate.sh "$PWD"
```
The store directory must resolve to the dedicated local block device. Do not
run the formal gate on a network share, tmpfs, overlay, or OS-root filesystem.
The CPU set must contain at least four comparable physical cores. Do not mix
performance and efficiency cores or sibling SMT threads; the gate records the
set and constrains both process affinity and `GOMAXPROCS`.
Each sample runs in a fresh process after `sync` and a 250 ms settle interval,
matching the Phase 173 D1 baseline's sample-isolation policy.
## Fixed Controls
The WALStore controls use 14,500 logical 4 KiB blocks (56.64 MiB). The scratch
comparison repeats the same 14,500-block layout three times per run so a single
filesystem sync does not dominate its variance. All controls use five runs,
persistent preconditioned files, and a predeclared max/min limit of `1.25x`:
- shipped 4-writer foreground with the normal 100 ms flusher;
- 1- and 4-writer foreground while writeback is deferred;
- real flusher drain of the 4-writer prefilled dirty set with no writers;
- shared-file and same-device split-file scratch with identical 87,000 preads,
43,501 pwrites, two syncs, decode/CRC, and correctness samples.
The fixed work stays below the default 64 MiB WAL's 90% hard watermark while
running long enough on the admission host to cross normal flusher periods.
## Required Evidence
- `phase173_architecture_controls_status=ok`
- the expected `control_cpuset` and `control_gomaxprocs`
- all shipped and counterfactual stability outcomes are reported without
suppressing a failed range; D1 remains the authoritative admission baseline
- every `*_max_min_ratio` remains recorded against `1.25`; an unstable
counterfactual must report `counterfactual_control_stability_gate=inconclusive`
and, while the shipped diagnostic remains stable, force
`local_architecture_direction=no_backend_change_unstable_counterfactuals`
- any unstable shipped diagnostic control must instead force
`local_architecture_direction=no_backend_change_unstable_diagnostic_controls`
- `diagnostic_controls_candidate_eligible=false` whenever any diagnostic
group is unstable
- `d1_fixed_work_baseline_authoritative=true`
- `rf1_rf3_component_attribution=complete`
- RF3 queue saturation is reported for one and four writers; any non-zero
result is component backpressure evidence and cannot justify a backend
candidate
- `architecture_candidate_selected=false`
- `product_mutation_present=false`
- `deferred_foreground_product_claim_allowed=false`
- `split_file_scratch_product_claim_allowed=false`
- `mounted_nvme_tcp_control=pending_same_session_live_gate`
- `d3_close_allowed=false`
- `store_residue_count=0`
The local direction uses predeclared `1.30x` signals. It remains provisional
until the same-session mounted NVMe/TCP control runs:
- owner/queue signal: one deferred writer is at least `1.30x` four deferred
writers;
- media signal: split-file scratch is at least `1.30x` shared-file scratch;
- writeback signal: four deferred writers are at least `1.30x` shipped
concurrent writers.
## Verdict
- `PASS`: fixed work, correctness, RF1/RF3 diagnostics, and residue checks pass.
Only fully stable diagnostics may nominate one direction. Any unstable group
forces an honest no-change decision, while D1 remains the performance
admission baseline. This advances D3 but does not close it.
- `FAIL`: correctness, counter, queue, or residue evidence fails.
- `HOLD`: the dedicated-device condition is unavailable. A diagnostic range
above `1.25x` is not promoted or tuned into a candidate; it is recorded as
ineligible and selects no backend change, as required by the Phase 173 stop
rules. D1, not this smaller attribution workload, gates baseline stability.
@@ -0,0 +1,85 @@
# Phase 174 D1 Fixed-Work Pipeline QA
Source: use the commit that adds this assignment,
`core/replication/phase174_fixed_work_test.go`, and
`scripts/run-phase174-fixed-work-pipeline-gate.sh`.
## Purpose
Establish one fixed logical workload above WALStore before selecting another
performance implementation. The local gate compares only the two layers that
share the same `local_durable` ACK profile:
- direct WALStore;
- RF1 durable adapter over that WALStore.
It also runs current RF3 `sync_quorum` through real localhost TCP into two
durable WALStore replicas. That path is diagnostic, not admission: three
durable stores share one host/device and `sync_quorum` is allowed to return
after one peer ACK. Throughput ratios across `local_durable` and
`sync_quorum_rf3` are forbidden.
## Run
```bash
cd /path/to/seaweed_block
export SW_BLOCK_ARTIFACT_DIR=/path/to/results/phase174-d1-local
export SW_BLOCK_PHASE174_STORE_DIR=/path/on/dedicated/nvme/phase174-d1-stores
export SW_BLOCK_PHASE174_CPUSET=0,2,4,6
bash scripts/run-phase174-fixed-work-pipeline-gate.sh "$PWD"
```
The store directory must be on a dedicated local filesystem, not `/`, tmpfs,
overlay, or a network share.
## Fixed Contract
- 16,384 measured 4 KiB full-block writes per run;
- deterministic unique scattered LBAs in a 32K-block region;
- 1,024 warmup writes in a disjoint region;
- 1, 4, and 8 writers;
- one final Sync, close, reopen, Recover, frontier, and byte checks;
- a build-tag-only `swblock_testtools` flusher reset after warmup, with no
control method present in shipped binaries;
- two independent sets of five measured runs, with the second set reversing
layer and writer order to expose time/device-order bias;
- exact primary WAL and replication operation counts;
- explicit `local_durable` versus `sync_quorum_rf3` ACK profiles.
For RF3, each sample uses new stores. A lagging non-quorum replica from one
sample is never reused as though it were healthy in the next sample.
## Required Evidence
- `phase174_fixed_work_pipeline_status=ok`
- `contract=phase174-fixed-work-v1`
- `cross_ack_profile_throughput_ratio_allowed=false`
- all 90 measured rows reconcile 16,384 writes and 64 MiB logical data
- recovered primary stable/head frontiers agree
- every row reports `flusher_phase_reset=true`
- RF3 has exactly two configured replicas and at least one durable replica
- direct and adapter four-writer combined max/min ranges are at most `1.25x`
- `rf1_local_stability_gate=pass`
- `rf3_same_host_admission_eligible=false`
- `rf3_distinct_node_gate_required=true`
- `d1_close_allowed=false`
- `architecture_candidate_selected=false`
- `product_mutation_present=false`
- `store_residue_count=0`
Record, do not suppress, `rf3_queue_saturation_row_count` and
`rf3_same_host_healthy_baseline`. A saturated or lagging same-host replica is
evidence for the next distinct-node gate, not permission to call a degraded
RF3 run healthy.
## Verdict
- `PASS`: the local RF1 comparable contract is stable and all RF3 diagnostic
facts are honest. D1 advances but does not close.
- `HOLD`: direct or adapter four-writer range exceeds `1.25x`; do not tune the
threshold after results are visible.
- `FAIL`: counters, durability, recovery, byte correctness, ACK profile, or
cleanup do not reconcile.
D1 closes only after a separate distinct-node RF3 and frontend/mounted gate
uses matching logical work and independent media.
@@ -0,0 +1,66 @@
# Phase 174 D1 Local Fixed-Work QA Sign-Off
Verdict: **HOLD** at `ed270f3` on the dedicated m02 NVMe filesystem.
## Contract And Correctness
The gate completed all 90 fixed-work rows: direct WALStore and durable-adapter
RF1 used `local_durable`; RF3 used `sync_quorum_rf3` over real localhost TCP
and remained diagnostic-only. Every row reconciled 16,384 writes and 64 MiB,
reported `flusher_phase_reset=true`, recovered the primary frontier, and
passed sampled byte checks. Store residue was zero.
The final run corrected two harness confounders without changing product code,
work, ACK semantics, or the `1.25x` threshold:
- GC/settling happens before the flusher start handshake, so it cannot consume
the first measurement interval;
- set 2 reverses layer and writer order, exposing device/time-order bias.
## Terminal Evidence
```text
commit=ed270f3
artifact=20260801T093246Z-phase174-d1-local-reversed
store_source=/dev/nvme0n1p1
store_filesystem=ext4
control_cpuset=0,2,4,6
control_gomaxprocs=4
second_set_order=reversed
direct_walstore_writers_4_set1_max_min_ratio=1.159
direct_walstore_writers_4_set2_max_min_ratio=1.054
adapter_rf1_writers_4_set1_max_min_ratio=1.227
adapter_rf1_writers_4_set2_max_min_ratio=1.347
direct_walstore_writers_4_max_min_ratio=1.159
adapter_rf1_writers_4_max_min_ratio=1.443
rf1_direct_adapter_four_writer_ratio=0.912
rf1_local_stability_gate=hold
rf3_same_host_healthy_baseline=false
rf3_queue_saturation_row_count=10
rf3_same_host_admission_eligible=false
architecture_candidate_selected=false
product_mutation_present=false
phase174_fixed_work_pipeline_status=hold
store_residue_count=0
```
Direct WALStore is stable in both independent sets. Durable adapter RF1 is not:
set 2 ranges from 284.094 to 382.759 MiB/s at four writers. This remains above
the unchanged `1.25x` limit after the direct control is stable, so it is a real
adapter-or-above attribution target rather than permission to tune the gate.
## Decision
D1 does not advance to a performance candidate. Phase 174 may continue into
D2 attribution because that adds evidence rather than product behavior. No D4
or D5 implementation is allowed unless D2/D3 later establish a stable,
semantically comparable cause and candidate.
Artifact:
```text
/mnt/smb/work/share/g15d-k8s/20260801T093246Z-phase174-d1-local-reversed.tar.gz
sha256=d9a96068a693adeb852787678283981a4f7f0b99bd450a927186cca3ddadabc4
```
m02 k3s remained inactive, matching its pre-run state.
@@ -0,0 +1,68 @@
# Phase 174 D2 Distinct-Node RF3 QA Sign-Off
Verdict: **PASS for distinct-node RF3 correctness and attribution; no
architecture candidate selected.**
## Formal Run
- source: `7d75a47542a949963fd196b3635e99291011cd56`
- primary: m02, `/data/nvme/block` on `/dev/nvme0n1p1`
- replicas: m01 and tp01
- transport: real TCP over the `192.168.1.x` management LAN
- artifact:
`/mnt/smb/work/share/g15d-k8s/20260801T102712Z-phase174-d2-rf3-distinct.tar.gz`
- SHA256:
`fc2a220e0183fcb77ea21473ec63cef9ecf4b17ce776f43db3d39389dba48bfb`
The fixed work was 16,384 deterministic 4 KiB writes per measured run. The
foreground ACK profile remained `sync_quorum_rf3`. Probe, recovery, and the
final SyncAll were outside the measured foreground interval.
| Writers | Median MiB/s | Max/min | Queue-terminal rows | Rebuilds |
|---:|---:|---:|---:|---:|
| 1 | 57.819 | 1.598 | 5/5 | 5 |
| 4 | 13.054 | 1.010 | 0/5 | 2 |
| 8 | 15.023 | 1.127 | 0/5 | 1 |
Required evidence passed:
- 15/15 primary rows and 6/6 independently reopened remote WALStores;
- 30 live probes, two per row;
- 8 full rebuilds selected by the existing `R < S` rule;
- every remote store recovered `stable_lsn=head_lsn=104448` and verified
final bytes;
- foreground sync-quorum, post-measurement recovery, and final SyncAll all
passed;
- remote process/store residue count was zero.
## Findings
The first real run exposed a product defect: queue saturation cancelled old
work but immediately installed a fresh steady queue before recovery closed the
LSN gap. `deebcf9` now permits queue replacement only while the peer is
positively `Healthy`; saturation remains terminal until the recovery handoff.
The queue/recovery race tests passed 20 iterations under the Linux race
detector.
An intermediate run correctly returned typed `WALRecycled`: the replica was at
R=1024 while the primary tail/checkpoint had reached S=17408. The final gate
uses the engine's existing classification (`R < S` means rebuild, otherwise
catch up) instead of treating SyncAll as recovery.
No catch-up occurred because this WALStore configuration reports retention
zero and every observed lag was outside the retained window. Distinct-node
catch-up with an explicit retained window remains a D6 recovery gate; this D2
run does not claim it.
The one-writer shape is unstable (`1.598x`, above `1.25x`), and the transport is
the management LAN rather than 100 GbE. The four/eight-writer results are
attribution data only. No throughput ratio can authorize D4/D5 implementation.
## Attempt Record
- `d1ef486`: failed before workload due stale helper listeners from an earlier
failed gate; failure cleanup now stops scoped helper PIDs before removing
their directories.
- `d1ef486`: reached recovery and failed honestly with typed `WALRecycled`
because the test helper fixed every lag to catch-up.
- `7d75a47`: PASS after using the existing R/S/H recovery classification.
@@ -0,0 +1,52 @@
# Phase 174 D2 Distinct-Node RF3 QA
Run this gate from Windows Git Bash. It cross-compiles one test-only binary,
uses m02 as primary, and runs persistent replica listeners on m01 and tp01.
Each replica writes to its own host's NVMe filesystem. The transport is the
shared `192.168.1.x` management LAN because tp01 has no RoCE interface; this is
not a 100 GbE performance claim.
```bash
cd /c/work/seaweed_block
SW_BLOCK_PHASE174_SSH_KEY=/c/work/dev_server/testdev_key \
bash scripts/run-phase174-distinct-node-rf3-gate.sh "$PWD"
```
If the workstation Go toolchain is older than the module requirement, build
the exact assignment commit's Linux test binary on a Go 1.25 host and pass it
as `SW_BLOCK_PHASE174_PREBUILT_BINARY`. The gate copies but never modifies the
provided binary.
## Contract
- 16,384 deterministic 4 KiB writes and 64 MiB per measured run;
- 1, 4, and 8 writers, five runs each, after a persistent precondition run;
- foreground ACK remains `sync_quorum_rf3`;
- after the measured Sync, an explicitly excluded recovery phase probes each
external replica, catches any lagging replica up from its durable `R+1`,
or rebuilds it when `R < S` proves the WAL window has moved past it,
completes the production-equivalent live-session handoff, and only then
requires SyncAll;
- each remote process stops, reopens WALStore, recovers the exact expected
frontier, and verifies final payload bytes independently;
- the primary also closes, reopens, recovers, and verifies bytes every run.
## Required Evidence
- `phase174_distinct_node_rf3_status=ok`;
- 15 primary result rows and six independently recovered remote results;
- `foreground_sync_quorum_preserved=true`;
- `post_measurement_recovery_verified=true`;
- `post_measurement_sync_all_verified=true`;
- `remote_replica_frontiers_and_bytes_equal=true`;
- `rf3_distinct_node_healthy=true`;
- peer queue saturation is reported, not hidden;
- every primary row reports two live probes; catch-up/rebuild counts and
maximum LSN lag are preserved as evidence rather than inferred from the
final barrier;
- no cross-ACK-profile throughput ratio, candidate selection, or product
mutation;
- remote process/store cleanup leaves no gate residue.
This is D2 attribution/correctness evidence. It does not override the D1 local
HOLD and cannot authorize D4/D5 implementation.
@@ -0,0 +1,80 @@
# Phase 174 D2 Mounted NVMe Phase Profile QA Sign-off
Verdict: **PASS.** The shipped Linux kernel mounted path uses inline NVMe Write
capsules for this workload, not the synthetic gate's R2T shape. No frontend
architecture candidate is selected.
## Source And Evidence
```text
source_commit=415942e2796590304c255dd8b8950f4aa3c327fc
host=m02
initiator=linux_kernel_nvme_tcp
workload=mounted_ext4_sequential_write
frontend_network_class=100gbe_tcp
artifact=/mnt/smb/work/share/g15d-k8s/20260801T113154Z-phase174-mounted-nvme.tar.gz
sha256=b4ff3807416a3405e055df702d96cc67f2364be2e280909a051075754a84f9d3
```
The gate installed the normal external NVMe/TCP path, mounted an ext4 PVC from
the Linux kernel initiator, measured a 256 MiB sequential write, verified the
read data, deleted the PV before CSI teardown, and returned the lab to zero
residue.
## Counter Reconciliation
The `/status/nvme` snapshots before and after the measured write reported:
```text
mounted_nvme_write_ops=8200
mounted_nvme_inline_write_ops=8200
mounted_nvme_r2t_write_ops=0
mounted_nvme_write_bytes=268509184
mounted_nvme_phase_counter_reconciliation=true
synthetic_fixed_work_write_shape=r2t
mounted_write_shape=inline
synthetic_fixed_work_write_shape_matches_mounted=false
```
Capsule receive/parse, dispatch, handler, completion queue, and completion-send
counts each equal all 8,200 writes. R2T collection equals the zero R2T writes,
and no H2C data was reported. This is a valid inline shape, not missing work.
## Mounted Attribution
```text
seq_write_mibps=156.00
seq_read_mibps=478.50
capsule_receive_parse=57.553 us/op
r2t_collection=0.000 us/op
dispatch_wait=43.502 us/op
handler=3037.612 us/op
completion_queue_wait=26.420 us/op
completion_send=40.316 us/op
server_phase_total=3205.404 us/op
mounted_nvme_dominant_phase=handler
```
These are accumulated concurrent durations and must not be compared directly
with wall-clock latency. The mounted workload also differs from the synthetic
fixed-work operation shape, so no cross-workload throughput ratio is allowed.
## Decision
- The synthetic loopback test client's R2T collection cost is not representative
of this shipped mounted kernel path. An R2T optimization is rejected as a
Phase 174 product candidate.
- The mounted handler bucket dominates, but it includes the durable backend
call and does not isolate a new frontend ownership problem. Existing adapter
and backend evidence does not provide a stable qualifying candidate.
- `mounted_shape_comparable=false`,
`fixed_work_throughput_ratio_allowed=false`, and
`architecture_candidate_selected=false` remain required.
- `final_data_verified=true`, `pv_deleted_before_csi_uninstall=true`, and
`cleanup_status=ok` passed. Independent post-run checks found no Helm,
pod/PVC/PV, SwBlock CRD, or NVMe subsystem residue.
The failed predecessor run at `d111454` is retained as harness evidence: the
product path and cleanup passed, but the wrapper incorrectly required a
positive R2T count. Commit `415942e` fixed only that gate assumption and the
exact-commit rerun passed.
@@ -0,0 +1,52 @@
# Phase 174 D2 Mounted NVMe Phase Profile QA
## Purpose
Cross-check the Phase 174 loopback test-client attribution with the shipped
path: Linux kernel NVMe/TCP initiator, ext4, mounted file write, durable target,
and normal PVC/PV teardown. This is a shape diagnostic, not a throughput ratio
against the synthetic fixed-work gate.
## Command
Run from an exact source commit on m02 with the Phase120 external-NVMe lab
settings used by the existing mounted baseline:
```bash
SW_BLOCK_ARTIFACT_DIR=/mnt/smb/work/share/g15d-k8s/<run-id>-phase174-mounted-nvme \
SW_BLOCK_PHASE174_SOURCE_COMMIT=<full-source-commit> \
SW_BLOCK_FRONTEND_IP_MAP=m01=10.0.0.1,m02=10.0.0.3 \
SW_BLOCK_PHASE174_MOUNTED_FRONTEND_NETWORK_CLASS=100gbe_tcp \
SW_BLOCK_EXPECTED_FRONTEND_ROUTE_DEV=enp1s0np0 \
SW_BLOCK_IMPORT_K3S_SSH_KEY=/opt/work/testdev_key \
bash scripts/run-phase174-mounted-nvme-phase-profile-gate.sh "$PWD"
```
## Required Checks
1. The kernel initiator connects to the external NVMe/TCP target and the
mounted writer/reader checks pass.
2. `/status/nvme` is read before and after only the measured sequential write.
3. Write operations equal capsule receive/parse, dispatch, handler, completion
queue, and completion-send operations. R2T collection operations equal R2T
Write commands; H2C bytes equal R2T bytes. Classify the observed kernel
write shape as `inline`, `r2t`, or `mixed`; no individual shape is required
for PASS.
4. Each phase has an accumulated duration and the dominant mounted phase is
recorded. Do not compare accumulated concurrent phase time to wall time.
5. Keep `mounted_shape_comparable=false`,
`fixed_work_throughput_ratio_allowed=false`, and
`architecture_candidate_selected=false`. A candidate requires compatible
same-session controls, not a ratio across different workloads. Record
whether the synthetic fixed-work R2T shape matches the mounted kernel shape.
6. Writer/read data verification, exact PVC/PV teardown, NVMe disconnect, Helm
uninstall, and `cleanup_status=ok` all pass.
## Verdict
- PASS: all counters reconcile for the observed write shape, mounted data is
correct, and cleanup is zero.
- FAIL: missing/contradictory counters, data failure, endpoint identity error,
or residue.
- The result may nominate a same-session control for D3, but cannot select an
architecture implementation by itself.
@@ -0,0 +1,182 @@
# Phase 174 D2 NVMe/TCP Fixed-Work QA Sign-off
Verdict: **PASS for detailed NVMe/TCP RF1 attribution; cross-run stability
remains HOLD.** No architecture candidate is selected.
## Detailed Phase Re-validation
The read-only phase counters were run from the exact instrumentation commit:
```text
source_commit=c588800ba5760e25b2be937de3c146db88005a96
host=m02
store_source=/dev/nvme0n1p1
store_filesystem=ext4
artifact=/mnt/smb/work/share/g15d-k8s/20260801T110640Z-phase174-d2-nvme-detailed.tar.gz
sha256=631646794af6dd2edb2201c78155a0302dfcd4210126a9cf41850da35e7a2608
result_rows=30
linux_race_test=pass
store_residue_count=0
```
Every row reported exactly 16,384 operations for capsule receive/parse, R2T
data collection, dispatch wait, handler, completion queue wait, and completion
send. The six accumulated phase durations never exceeded accumulated client
latency, and the exact difference was recorded as client/wire residual. Protocol,
adapter, WAL, byte, Flush, close/reopen, `R == H`, and recovered-data checks also
passed for all rows.
The current run was stable:
| IO queues | Median MiB/s | Overall max/min | Set 1 | Set 2 |
| ---: | ---: | ---: | ---: | ---: |
| 1 | 102.495 | 1.019 | 1.010 | 1.019 |
| 4 | 258.718 | 1.037 | 1.029 | 1.037 |
| 8 | 300.370 | 1.121 | 1.120 | 1.091 |
The four-queue median accumulated time per operation is now split as follows:
```text
client write round trip 59.763 us/op
capsule receive/parse 0.185 us/op
R2T data collection 30.096 us/op
dispatch wait 0.818 us/op
handler 8.204 us/op
completion queue wait 0.690 us/op
completion send 3.710 us/op
remaining client/wire residual 15.922 us/op
target backend call 7.178 us/op
adapter write 6.809 us/op
```
R2T collection is the largest measured detailed phase, but it includes target
R2T publication, initiator response, loopback wire time, and H2CData receive.
The remaining residual also includes initiator and uninstrumented wire work.
This test-client loopback result is therefore not sufficient to select a target
protocol rewrite. The next bounded check is the same target counters under a
mounted Linux kernel NVMe initiator.
The current gate reports `nvme_tcp_rf1_all_shapes_stability_gate=pass`, but D1
remains cross-run HOLD: the prior semantically identical run below contained a
`1.530x` one-queue set. An instrumentation-only commit does not invalidate that
evidence or prove a stability fix.
## Source And Evidence
```text
source_commit=706b17381b6d57cbaa7d6823b0f8bc726dd0f3ae
host=m02
store_source=/dev/nvme0n1p1
store_filesystem=ext4
control_cpuset=0,2,4,6
control_gomaxprocs=4
artifact=/mnt/smb/work/share/g15d-k8s/20260801T104958Z-phase174-d2-nvme-fixed.tar.gz
sha256=93cefd739f39d91ed0b9a8f54df44dd3fe6c13051fccbf3ad97be0d63024a4be
```
The bundle contains 30 measured JSON rows, per-run logs, five merged
four-queue CPU/block/mutex profiles, environment evidence, and the summary.
## Contract And Correctness
Each row used the same Phase 174 logical work:
```text
16,384 writes x 4 KiB = 67,108,864 bytes
writers/IO queues=1,4,8
sets=2
runs per set=5
ack_profile=local_durable
transport=real loopback NVMe/TCP R2T/H2C
```
All 30 rows reconciled exactly:
```text
nvme_write_commands=16384
nvme_r2t_write_commands=16384
nvme_h2c_data_pdus=16384
target_write_ops=16384
adapter_request_ops=16384
adapter_write_ops=16384
adapter_storage_write_calls=16384
adapter_storage_write_blocks=16384
primary_wal_write_ops=16384
all byte counters=67108864
```
Final NVMe Flush, close/reopen, WAL recovery, `R == H`, and five recovered
data samples passed for every row. Store cleanup also passed:
```text
nvme_tcp_rf1_counter_reconciliation=true
nvme_tcp_rf1_close_recover_verified=true
store_residue_count=0
```
## Performance And Stability
| IO queues | Median MiB/s | Overall max/min | Set 1 | Set 2 |
| ---: | ---: | ---: | ---: | ---: |
| 1 | 103.243 | 1.551 | 1.018 | 1.530 |
| 4 | 260.787 | 1.035 | 1.035 | 1.018 |
| 8 | 298.731 | 1.038 | 1.029 | 1.038 |
The four-writer admission shape is stable, but all-shapes stability is HOLD.
The one-queue set-2 slow rows were `81.25`, `74.57`, and `67.73 MiB/s`.
Their foreground flusher-cycle time rose to `434-690 ms`, versus roughly
`152-165 ms` in the stable set-1 rows. The one-queue foreground/flusher
correlation is `0.995`. This is strong evidence that the instability moved
with background checkpoint work, not with a deterministic target CPU cost.
```text
nvme_tcp_rf1_four_writer_stability_gate=pass
nvme_tcp_rf1_all_shapes_stability_gate=hold
```
## Boundary Attribution
The stable four-queue median accumulated time per operation was:
```text
client write round trip 59.564 us/op
NVMe/TCP round-trip non-backend 52.255 us/op
target backend call 7.357 us/op
adapter write 6.995 us/op
write commit-lock wait 2.836 us/op
WAL encode 0.731 us/op
WAL append 1.492 us/op
dirty-map update 0.273 us/op
```
About 88% of accumulated client-visible latency is outside the target's
backend call. This aggregate includes the test initiator, loopback TCP,
R2T/H2C receive, dispatch/scheduling, and completion. It is not yet evidence
that any one target function dominates.
Merged CPU profiles likewise do not identify a product Go hotspot:
```text
internal/runtime/syscall.Syscall6=54.76% flat
runtime.memmove=3.67% flat
```
The profile covers the whole test process, including payload generation and
recovery, so it is supporting evidence rather than a foreground-only CPU
breakdown.
## Decision
- D2's NVMe/TCP RF1 operation/byte/recovery attribution slice passes.
- D1 remains HOLD because not every required shape is stable across the
broader Phase 174 evidence.
- No architecture candidate is selected. The dominant measured bucket is too
broad to justify changing queue, completion, or protocol ownership.
- The next bounded step is to split NVMe receive/data collection,
dispatch/queue, and completion publication inside the target while retaining
the same fixed-work contract.
- Historical mounted fio/dd results remain diagnostic:
`mounted_shape_comparable=false` and
`mounted_throughput_ratio_allowed=false`.
No shipped product code or default changed in this slice.
@@ -0,0 +1,88 @@
# 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/<run-id> \
SW_BLOCK_PHASE174_NVME_STORE_DIR=/data/nvme/block/<run-id>-stores \
SW_BLOCK_PHASE174_SOURCE_COMMIT=<full-source-commit> \
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. The detailed target counters each report 16,384 operations and split the
server path into capsule receive/parse, R2T data collection, dispatch wait,
handler, completion queue wait, and completion send. Capsule receive/parse
includes inbound socket wait; R2T collection includes target/initiator/wire
exchange time. Their sum must not exceed accumulated client request latency;
the exact difference is the remaining client/wire residual.
7. Final NVMe Flush succeeds, close/reopen/recovery reaches `R == H`, and at
least five measured LBAs retain the expected bytes.
8. Capture merged CPU, block, and mutex profiles for five four-queue diagnostic
runs.
9. Record the four-writer admission stability and all-shapes stability
separately. A range above `1.25x` is HOLD evidence, not a reason to delete
a slow run or select an architecture candidate. Correlate four/eight-writer
foreground time with the existing WAL flusher counters.
10. 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.
@@ -0,0 +1,70 @@
# Phase 174 D2 RF1 Boundary Attribution QA Sign-Off
Verdict: **PASS for the RF1 attribution slice** at `4034f37`. D1 remains
**HOLD**, and no implementation candidate is authorized.
## Counter Closure
The exact D1 matrix completed 90 rows on m02's dedicated NVMe filesystem. All
ten adapter four-writer rows reconciled 16,384 requests, successful writes,
storage calls, and storage blocks plus 64 MiB at both adapter byte boundaries.
```text
rf1_attribution_counter_reconciliation=true
rf1_attribution_status=ok
direct_walstore_writers_4_max_min_ratio=1.211
adapter_rf1_writers_4_max_min_ratio=1.344
rf1_local_stability_gate=hold
architecture_candidate_selected=false
product_mutation_present=false
```
## Attribution
Four-writer adapter medians and their correlation with foreground wall time:
```text
boundary ns/op correlation
adapter envelope 42,912.380 0.994
storage accounted 16,167.086 0.165
global commit-lock wait 13,154.722 0.192
WAL encode 1,329.172 0.042
WAL append 1,324.057 0.021
dirty map 221.377 -0.153
adapter envelope unaccounted 27,561.795 0.960
foreground flusher 7,887.893 0.952
```
The envelope-unaccounted value is not asserted to be adapter CPU. It includes
off-CPU scheduling and storage work not represented by the non-overlapping
phase counters. Merged profiles from five runs per layer show:
- adapter CPU has no new dominant function; `StorageBackend.Write` is 16.57%
cumulative and immediately enters `writeBytes`/`WALStore.Write`;
- block delay attributed to `StorageBackend.writeBytes` occurs at the
`storage.Write` call, not its 256-stripe LBA lock;
- direct and adapter foreground time correlate with flusher cycle time at
`0.825` and `0.952`, respectively.
The short 64 MiB sample sits near the periodic flusher boundary. Background
WAL-to-extent work therefore changes scheduler/device overlap and affects the
adapter envelope, while the accounted commit/encode/append phases do not
explain the variance. Phase 173 already rejected flusher controls that did not
produce a stable `1.30x` gain. This evidence does not reopen that backend
decision or justify a new product change.
## Decision
RF1 D2 attribution is complete. Continue only with diagnostic distinct-node
RF3 and frontend/mounted attribution. D4/D5 remain ineligible while D1 is HOLD
and D3 has no stable candidate.
Artifact:
```text
/mnt/smb/work/share/g15d-k8s/20260801T094609Z-phase174-d2-rf1-attribution.tar.gz
sha256=97ed6f8584822eac7a023a5203704add12349b56a1a5fbc744f86da9e8fbad2d
store_residue_count=0
```
m02 k3s remained inactive, matching its pre-run state.
@@ -0,0 +1,57 @@
# Phase 174 D2 RF1 Boundary Attribution QA
Run the Phase 174 fixed-work pipeline gate from the assignment commit. D2
extends the D1 matrix with existing WALStore, flusher, and durable-adapter
counter deltas; it does not add hot-path instrumentation or change product
behavior.
## Purpose
Explain the unstable `adapter_rf1` four-writer baseline before any architecture
candidate is allowed. The same 16,384-operation, 64 MiB, `local_durable` work
must reconcile through:
- durable adapter requests, successful writes, bytes, storage calls, and
blocks;
- WAL encode, append, dirty-map, and global commit-lock wait;
- foreground flusher cycles, extent writes, and extent syncs;
- merged CPU, block, and mutex profiles from five direct and five adapter
diagnostic repeats.
Durations are accumulated concurrent work, not wall time. The gate reports
per-operation medians and correlation with foreground wall time; it must not
sum overlapping measurements into a throughput claim.
## Run
```bash
export SW_BLOCK_ARTIFACT_DIR=/path/to/results/phase174-d2-rf1-attribution
export SW_BLOCK_PHASE174_STORE_DIR=/path/on/dedicated/nvme/phase174-d2-stores
export SW_BLOCK_PHASE174_CPUSET=0,2,4,6
bash scripts/run-phase174-fixed-work-pipeline-gate.sh /path/to/seaweed_block
```
## Required Evidence
- all 90 D1 rows retain their ACK, recovery, correctness, and cleanup checks;
- every adapter four-writer row has exactly 16,384 requests, writes, storage
calls, and blocks, plus 64 MiB at both adapter byte counters;
- `rf1_attribution_counter_reconciliation=true`;
- `rf1_attribution_status=ok` even if the unchanged D1 stability verdict is
`hold`;
- per-operation medians and foreground correlations exist for adapter total,
accounted storage, commit wait, encode, append, dirty map, unattributed
adapter work, and foreground flusher work;
- merged CPU, block, and mutex tops exist for direct and adapter;
- `architecture_candidate_selected=false` and no product mutation is present;
- store residue is zero.
## Verdict
- `PASS`: attribution counters reconcile and identify the measured boundary;
this does not override a D1 HOLD or authorize implementation.
- `FAIL`: any operation/byte count, profile, correctness, or cleanup evidence
is missing.
D2 remains open for RF3 distinct-node and frontend attribution after this RF1
slice.
@@ -160,6 +160,138 @@ raise SystemExit(1)
PY
}
collect_nvme_stats_snapshot() {
local out="$1"
python3 - \
"${ARTIFACT_DIR}/status/cluster-evidence.json" \
"${ARTIFACT_DIR}/status/inventory/volume-inventory.json" \
"${out}" <<'PY'
import json
import sys
import urllib.request
cluster_path, inventory_path, out = sys.argv[1:]
def field(obj, *names, default=None):
for name in names:
if isinstance(obj, dict) and name in obj:
return obj[name]
return default
doc = json.load(open(cluster_path))
managed = field(doc, "managed_volumes", "managedVolumes", default=[]) or []
if len(managed) != 1:
raise SystemExit(f"managed_volume_count={len(managed)}, want 1")
volume = managed[0]
volume_id = field(volume, "volume_id", "volumeID")
replicas = field(volume, "replicas", default=[]) or []
if not replicas:
inventory = json.load(open(inventory_path))
for item in field(inventory, "volumes", default=[]) or []:
if field(item, "volume_id", "volumeID") == volume_id:
replicas = field(item, "replicas", default=[]) or []
break
chosen = next((r for r in replicas if field(r, "frontend_primary_ready", "frontendPrimaryReady", default=False)), None)
if chosen is None:
chosen = next((r for r in replicas if field(r, "healthy", default=False)), None)
if chosen is None and replicas:
chosen = replicas[0]
status_addr = field(chosen or {}, "status_addr", "statusAddr", "status_address", "statusAddress")
if not volume_id or not status_addr:
raise SystemExit("volume_id or status_addr unavailable")
with urllib.request.urlopen(f"http://{status_addr}/status/nvme?volume={volume_id}", timeout=10) as resp:
raw = resp.read()
body = json.loads(raw)
if body.get("volumeID") != volume_id or not isinstance(body.get("stats"), dict):
raise SystemExit(f"invalid NVMe status response: {body}")
open(out, "wb").write(raw)
PY
}
collect_nvme_phase_profile() {
python3 - \
"${ARTIFACT_DIR}/status/status-nvme-before-seq-write.json" \
"${ARTIFACT_DIR}/status/status-nvme-after-seq-write.json" \
"${SEQ_BYTES}" \
"${ARTIFACT_DIR}/status/nvme-phase-profile-summary.txt" <<'PY'
import json
import sys
before_path, after_path, seq_bytes_raw, summary_path = sys.argv[1:]
before = json.load(open(before_path))["stats"]
after = json.load(open(after_path))["stats"]
seq_bytes = int(seq_bytes_raw)
def delta(name):
old = int(before.get(name, 0) or 0)
new = int(after.get(name, 0) or 0)
if new < old:
raise SystemExit(f"NVMe counter regressed: {name} before={old} after={new}")
return new - old
write_ops = delta("write_commands")
inline_ops = delta("inline_write_commands")
inline_bytes = delta("inline_write_bytes")
r2t_ops = delta("r2t_write_commands")
r2t_bytes = delta("r2t_write_bytes")
h2c_pdus = delta("h2c_data_pdus")
h2c_bytes = delta("h2c_data_bytes")
if write_ops <= 0:
raise SystemExit("mounted sequence write produced no NVMe Write commands")
if inline_ops + r2t_ops != write_ops:
raise SystemExit(f"write shape mismatch: writes={write_ops} inline={inline_ops} r2t={r2t_ops}")
if inline_bytes + r2t_bytes < seq_bytes:
raise SystemExit(f"NVMe write bytes={inline_bytes + r2t_bytes}, want >= {seq_bytes}")
if h2c_bytes != r2t_bytes:
raise SystemExit(f"H2C bytes={h2c_bytes}, want R2T bytes {r2t_bytes}")
phase_ops = {
"capsule_receive_parse": delta("write_capsule_receive_parse_ops"),
"r2t_collection": delta("r2t_data_collection_ops"),
"dispatch_wait": delta("write_dispatch_wait_ops"),
"handler": delta("write_handler_ops"),
"completion_queue_wait": delta("write_completion_queue_wait_ops"),
"completion_send": delta("write_completion_send_ops"),
}
for name in ("capsule_receive_parse", "dispatch_wait", "handler", "completion_queue_wait", "completion_send"):
if phase_ops[name] != write_ops:
raise SystemExit(f"{name}_ops={phase_ops[name]}, want writes {write_ops}")
if phase_ops["r2t_collection"] != r2t_ops:
raise SystemExit(f"r2t_collection_ops={phase_ops['r2t_collection']}, want R2T writes {r2t_ops}")
phase_fields = {
"capsule_receive_parse": "write_capsule_receive_parse_ns",
"r2t_collection": "r2t_data_collection_ns",
"dispatch_wait": "write_dispatch_wait_ns",
"handler": "write_handler_ns",
"completion_queue_wait": "write_completion_queue_wait_ns",
"completion_send": "write_completion_send_ns",
}
phase_ns = {name: delta(field) for name, field in phase_fields.items()}
server_phase_ns = sum(phase_ns.values())
dominant = max(phase_ns, key=phase_ns.get)
with open(summary_path, "w") as out:
out.write("phase120_nvme_phase_profile_status=ok\n")
out.write(f"mounted_nvme_write_ops={write_ops}\n")
out.write(f"mounted_nvme_inline_write_ops={inline_ops}\n")
out.write(f"mounted_nvme_r2t_write_ops={r2t_ops}\n")
out.write(f"mounted_nvme_write_bytes={inline_bytes + r2t_bytes}\n")
out.write(f"mounted_nvme_h2c_data_pdus={h2c_pdus}\n")
for name in phase_ops:
out.write(f"mounted_nvme_{name}_ops={phase_ops[name]}\n")
out.write(f"mounted_nvme_{name}_ns={phase_ns[name]}\n")
out.write(f"mounted_nvme_{name}_ns_per_op={phase_ns[name] / write_ops:.3f}\n")
out.write(f"mounted_nvme_server_phase_ns={server_phase_ns}\n")
out.write(f"mounted_nvme_server_phase_ns_per_op={server_phase_ns / write_ops:.3f}\n")
out.write(f"mounted_nvme_dominant_phase={dominant}\n")
out.write("mounted_nvme_phase_counter_reconciliation=true\n")
out.write("mounted_client_latency_reconciliation_available=false\n")
out.write("mounted_shape_comparable=false\n")
PY
cat "${ARTIFACT_DIR}/status/nvme-phase-profile-summary.txt" >>"${SUMMARY}"
}
wait_managed_volume_ready_after_restart() {
for _ in $(seq 1 90); do
if with_master_port_forward "${ARTIFACT_DIR}/status/blockmaster-port-forward-after-restart.log" collect_cluster_evidence_after_restart; then
@@ -683,6 +815,12 @@ kubectl apply -f "${ARTIFACT_DIR}/pvc/perf-pvc.yaml" >"${ARTIFACT_DIR}/pvc/apply
kubectl -n "${APP_NAMESPACE}" wait --for=jsonpath='{.status.phase}'=Bound "pvc/${PVC_NAME}" --timeout=180s \
>"${ARTIFACT_DIR}/pvc/wait-pvc-bound.log" 2>&1
kubectl -n "${APP_NAMESPACE}" get pvc "${PVC_NAME}" -o wide >"${ARTIFACT_DIR}/pvc/pvc.after-bound.txt" 2>&1
PV_NAME="$(kubectl -n "${APP_NAMESPACE}" get pvc "${PVC_NAME}" -o jsonpath='{.spec.volumeName}')"
if [[ -z "${PV_NAME}" ]]; then
echo "bound PVC ${APP_NAMESPACE}/${PVC_NAME} has no volumeName" >&2
exit 1
fi
write_summary "pv_name=${PV_NAME}"
write_summary "pvc_bound=true"
cat >"${ARTIFACT_DIR}/perf/perf-pod.yaml" <<YAML
@@ -786,6 +924,9 @@ write_summary "marker_verify_ms=${MARKER_MS}"
write_summary "marker_verified=true"
SEQ_BYTES=$((SEQ_MIB * 1024 * 1024))
if [[ "${PROFILE_WRITE}" == "true" ]]; then
collect_nvme_stats_snapshot "${ARTIFACT_DIR}/status/status-nvme-before-seq-write.json"
fi
SEQ_WRITE_MS="$(measure_profiled_exec_ms "${ARTIFACT_DIR}/perf/seq-write.log" "${ARTIFACT_DIR}/profile/seq-write-samples.txt" \
kubectl -n "${APP_NAMESPACE}" exec "${PERF_POD}" -- sh -c \
"set -eu; dd if=/dev/zero of=/data/phase120-seq.bin bs=1M count=${SEQ_MIB} conv=fsync; sync")"
@@ -800,6 +941,8 @@ write_summary "seq_write_mibps=${SEQ_WRITE_MIBPS}"
write_summary "seq_read_duration_ms=${SEQ_READ_MS}"
write_summary "seq_read_mibps=${SEQ_READ_MIBPS}"
if [[ "${PROFILE_WRITE}" == "true" ]]; then
collect_nvme_stats_snapshot "${ARTIFACT_DIR}/status/status-nvme-after-seq-write.json"
collect_nvme_phase_profile
collect_durable_write_profile
fi
if [[ "${RESTART_BLOCKVOLUME_AFTER_WRITE_PROFILE}" == "true" ]]; then
@@ -829,6 +972,20 @@ kubectl -n "${APP_NAMESPACE}" delete pod "${PERF_POD}" --ignore-not-found=true -
>"${ARTIFACT_DIR}/cleanup/delete-perf-pod.txt" 2>&1
kubectl -n "${APP_NAMESPACE}" delete pvc "${PVC_NAME}" --ignore-not-found=true --wait=true --timeout=120s \
>"${ARTIFACT_DIR}/cleanup/delete-pvc.txt" 2>&1
pv_deleted=false
for _ in $(seq 1 180); do
if ! kubectl get pv "${PV_NAME}" >/dev/null 2>&1; then
pv_deleted=true
break
fi
sleep 1
done
if [[ "${pv_deleted}" != "true" ]]; then
kubectl get pv "${PV_NAME}" -o yaml >"${ARTIFACT_DIR}/cleanup/pv-delete-timeout.yaml" 2>&1 || true
echo "PV ${PV_NAME} remained after PVC deletion while CSI was running" >&2
exit 1
fi
write_summary "pv_deleted_before_csi_uninstall=true"
kubectl delete storageclass "${SC_NAME}" --ignore-not-found=true --wait=true --timeout=120s \
>"${ARTIFACT_DIR}/cleanup/delete-storageclass.txt" 2>&1
sudo -n nvme disconnect-all >/dev/null 2>&1 || true
@@ -0,0 +1,347 @@
#!/usr/bin/env bash
set -euo pipefail
ROOT="${1:-$(pwd)}"
ARTIFACT_DIR="${SW_BLOCK_ARTIFACT_DIR:-${ROOT}/results/phase173-architecture-controls-gate}"
STORE_DIR="${SW_BLOCK_PHASE173_STORE_DIR:-${ARTIFACT_DIR}/stores}"
SUMMARY="${ARTIFACT_DIR}/phase173-architecture-controls-summary.txt"
RESULTS="${ARTIFACT_DIR}/phase173-architecture-control-results.jsonl"
TEST_BINARY="${ARTIFACT_DIR}/storage.test"
MAX_RANGE="1.25"
MATERIAL_RATIO="1.30"
RUNS=5
CONTROL_CPUSET="${SW_BLOCK_PHASE173_CONTROL_CPUSET:-}"
mkdir -p "${ARTIFACT_DIR}" "${STORE_DIR}" "${ARTIFACT_DIR}/environment" "${ARTIFACT_DIR}/logs"
: >"${SUMMARY}"
: >"${RESULTS}"
cleanup() {
rm -f "${STORE_DIR}"/phase173-control-* "${STORE_DIR}"/*.scratch
find "${STORE_DIR}" -mindepth 1 -maxdepth 1 -type d -name 'go-build*' -empty -delete 2>/dev/null || true
}
trap cleanup EXIT
write_summary() {
echo "$*" | tee -a "${SUMMARY}" >/dev/null
}
capture() {
local name="$1"
shift
"$@" >"${ARTIFACT_DIR}/environment/${name}.txt" 2>&1 || true
}
for tool in go python3 findmnt taskset nproc; do
command -v "${tool}" >/dev/null 2>&1 || {
echo "required tool ${tool} is unavailable" >&2
exit 1
}
done
if [[ -z "${CONTROL_CPUSET}" ]]; then
echo "SW_BLOCK_PHASE173_CONTROL_CPUSET must name at least four comparable CPUs" >&2
exit 1
fi
CONTROL_GOMAXPROCS="$(taskset -c "${CONTROL_CPUSET}" nproc)"
if (( CONTROL_GOMAXPROCS < 4 )); then
echo "control cpuset ${CONTROL_CPUSET} exposes ${CONTROL_GOMAXPROCS} CPUs; need at least four" >&2
exit 1
fi
store_source="$(findmnt -n -T "${STORE_DIR}" -o SOURCE)"
store_filesystem="$(findmnt -n -T "${STORE_DIR}" -o FSTYPE)"
root_source="$(findmnt -n -T / -o SOURCE)"
if [[ "${store_source}" != /dev/* ]]; then
echo "store source ${store_source} is not a local block device" >&2
exit 1
fi
if [[ "${store_source}" == "${root_source}" ]]; then
echo "store source ${store_source} is the OS root filesystem" >&2
exit 1
fi
write_summary "phase173_architecture_controls_status=running"
write_summary "contract=phase173-architecture-controls-v1"
write_summary "scope=test_only_diagnostic_controls"
write_summary "runs_per_control=${RUNS}"
write_summary "max_min_limit=${MAX_RANGE}"
write_summary "material_direction_ratio=${MATERIAL_RATIO}"
write_summary "store_source=${store_source}"
write_summary "store_filesystem=${store_filesystem}"
write_summary "root_source=${root_source}"
write_summary "dedicated_store_source=true"
write_summary "control_cpuset=${CONTROL_CPUSET}"
write_summary "control_gomaxprocs=${CONTROL_GOMAXPROCS}"
write_summary "architecture_candidate_selected=false"
write_summary "product_mutation_present=false"
write_summary "deferred_foreground_product_claim_allowed=false"
write_summary "split_file_scratch_product_claim_allowed=false"
write_summary "d1_fixed_work_baseline_authoritative=true"
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 ./core/storage -run '^TestPhase173ArchitectureControlContract$' -count=1 \
>"${ARTIFACT_DIR}/control-contract-test.log" 2>&1
go test -c -o "${TEST_BINARY}" ./core/storage
for control in \
shipped_concurrent_writers_4 \
deferred_foreground_writers_1 \
deferred_foreground_writers_4 \
shared_file_scratch \
split_file_scratch; do
if [[ "${control}" != *_scratch ]]; then
precondition_log="${ARTIFACT_DIR}/logs/${control}-precondition.log"
SW_BLOCK_PHASE173_ARCH_CONTROL_STORE_DIR="${STORE_DIR}" \
SW_BLOCK_PHASE173_ARCH_CONTROL="${control}" \
SW_BLOCK_PHASE173_ARCH_CONTROL_RUN="0" \
GOMAXPROCS="${CONTROL_GOMAXPROCS}" taskset -c "${CONTROL_CPUSET}" \
"${TEST_BINARY}" -test.run '^TestPhase173ArchitectureControls$' -test.v -test.count=1 \
>"${precondition_log}" 2>&1
sync
sleep 0.25
fi
for run in $(seq 1 "${RUNS}"); do
sync
sleep 0.25
control_log="${ARTIFACT_DIR}/logs/${control}-run${run}.log"
SW_BLOCK_PHASE173_ARCH_CONTROL_STORE_DIR="${STORE_DIR}" \
SW_BLOCK_PHASE173_ARCH_CONTROL="${control}" \
SW_BLOCK_PHASE173_ARCH_CONTROL_RUN="${run}" \
GOMAXPROCS="${CONTROL_GOMAXPROCS}" taskset -c "${CONTROL_CPUSET}" \
"${TEST_BINARY}" -test.run '^TestPhase173ArchitectureControls$' -test.v -test.count=1 \
>"${control_log}" 2>&1
sed -n 's/^phase173_architecture_control_result=//p' "${control_log}" >>"${RESULTS}"
done
done
mkdir -p "${STORE_DIR}/tmp"
TMPDIR="${STORE_DIR}/tmp" GOMAXPROCS="${CONTROL_GOMAXPROCS}" taskset -c "${CONTROL_CPUSET}" go test ./core/frontend/durable \
-run '^$' -bench '^BenchmarkT3c_DurablePerf$/^walstore$' \
-benchtime=8000x -count=1 \
>"${ARTIFACT_DIR}/rf1-durable-adapter-benchmark.txt" 2>&1
TMPDIR="${STORE_DIR}/tmp" GOMAXPROCS="${CONTROL_GOMAXPROCS}" taskset -c "${CONTROL_CPUSET}" go test ./core/replication \
-run '^$' -bench '^BenchmarkPhase167RF3SyncQuorumContention/(writers_1|writers_4)$' \
-benchtime=2048x -count=1 \
>"${ARTIFACT_DIR}/rf3-real-tcp-benchmark.txt" 2>&1
rm -rf "${STORE_DIR}/tmp"
python3 - "${RESULTS}" "${SUMMARY}" "${RUNS}" "${MAX_RANGE}" "${MATERIAL_RATIO}" <<'PY'
import json
import math
import statistics
import sys
from collections import defaultdict
results_path, summary_path, runs_text, max_range_text, material_text = sys.argv[1:]
runs = int(runs_text)
max_range = float(max_range_text)
material = float(material_text)
rows = [json.loads(line) for line in open(results_path, encoding="utf-8") if line.strip()]
if len(rows) != 30:
raise SystemExit(f"control rows={len(rows)} want 30")
groups = defaultdict(list)
for row in rows:
if row["contract"] != "phase173-architecture-controls-v1":
raise SystemExit(f"bad contract: {row}")
key = (row["control"], int(row["writers"]))
groups[key].append(row)
scratch = row["control"] in ("shared_file_scratch", "split_file_scratch")
expected_blocks = 14500 * 3 if scratch else 14500
if row["logical_blocks"] != expected_blocks or row["logical_bytes"] != expected_blocks * 4096:
raise SystemExit(f"bad fixed work: {row}")
if row["duration_ns"] <= 0 or row["mib_per_second"] <= 0 or row["correctness_samples"] < 3:
raise SystemExit(f"empty duration/rate/correctness: {row}")
if row["control"] in ("shipped_concurrent", "deferred_foreground"):
if row["commit_lock_wait_ops"] != 2320:
raise SystemExit(f"bad lock work: {row}")
if row["flush_record_reads"] != 14500 or row["flush_decode_ops"] != 14500 or row["extent_write_ops"] != 14500:
raise SystemExit(f"bad real flusher work: {row}")
if row["extent_sync_ops"] != row["checkpoint_sync_ops"] or row["extent_sync_ops"] <= 0:
raise SystemExit(f"bad flusher sync work: {row}")
elif row["control"] == "prefilled_flusher":
if row["writers"] != 0 or row["flush_record_reads"] != 14500 or row["extent_write_ops"] != 14500:
raise SystemExit(f"bad prefilled flusher work: {row}")
else:
if row["scratch_pread_ops"] != 87000 or row["scratch_pwrite_ops"] != 43501 or row["scratch_sync_ops"] != 2:
raise SystemExit(f"bad scratch I/O shape: {row}")
expected = {
("shipped_concurrent", 4),
("deferred_foreground", 1),
("deferred_foreground", 4),
("prefilled_flusher", 0),
("shared_file_scratch", 0),
("split_file_scratch", 0),
}
if set(groups) != expected:
raise SystemExit(f"control groups={set(groups)} want {expected}")
summary = []
shipped_stable = True
counterfactual_stable = True
medians = {}
for key in sorted(expected):
group = groups[key]
if len(group) != runs:
raise SystemExit(f"group={key} rows={len(group)} want {runs}")
values = [float(row["mib_per_second"]) for row in group]
ratio = max(values) / min(values)
median = statistics.median(values)
medians[key] = median
prefix = f"{key[0]}_writers_{key[1]}"
summary.append(f"{prefix}_median_mibps={median:.3f}")
summary.append(f"{prefix}_max_min_ratio={ratio:.3f}")
group_stable = math.isfinite(ratio) and ratio <= max_range
if key == ("shipped_concurrent", 4):
shipped_stable = group_stable
elif not group_stable:
counterfactual_stable = False
if key[0] in ("shipped_concurrent", "deferred_foreground"):
waits = [row["commit_lock_wait_ns"] / row["commit_lock_wait_ops"] for row in group]
p99 = [row["p99_ns"] for row in group]
gc_cycles = [row.get("measured_gc_cycles", 0) for row in group]
gc_pause = [row.get("measured_gc_pause_ns", 0) for row in group]
alloc_bytes = [row.get("measured_alloc_bytes", 0) for row in group]
summary.append(f"{prefix}_median_commit_lock_wait_ns_per_op={statistics.median(waits):.0f}")
summary.append(f"{prefix}_median_p99_ns={statistics.median(p99):.0f}")
summary.append(f"{prefix}_median_measured_gc_cycles={statistics.median(gc_cycles):.0f}")
summary.append(f"{prefix}_median_measured_gc_pause_ns={statistics.median(gc_pause):.0f}")
summary.append(f"{prefix}_median_measured_alloc_bytes={statistics.median(alloc_bytes):.0f}")
shipped = medians[("shipped_concurrent", 4)]
deferred_one = medians[("deferred_foreground", 1)]
deferred_four = medians[("deferred_foreground", 4)]
shared = medians[("shared_file_scratch", 0)]
split = medians[("split_file_scratch", 0)]
deferred_vs_shipped = deferred_four / shipped
single_vs_four = deferred_one / deferred_four
split_vs_shared = split / shared
owner_signal = single_vs_four >= material
writeback_signal = deferred_vs_shipped >= material
media_signal = split_vs_shared >= material
if not shipped_stable:
direction = "no_backend_change_unstable_diagnostic_controls"
elif not counterfactual_stable:
direction = "no_backend_change_unstable_counterfactuals"
elif media_signal and not owner_signal:
direction = "wal_extent_media_separation"
elif owner_signal and not media_signal:
direction = "owner_queue_redesign"
elif not owner_signal and not media_signal:
direction = "no_backend_change_local_controls"
else:
direction = "ambiguous_stop_before_candidate"
summary.extend([
f"deferred_four_vs_shipped_four_ratio={deferred_vs_shipped:.3f}",
f"deferred_one_vs_deferred_four_ratio={single_vs_four:.3f}",
f"split_vs_shared_scratch_ratio={split_vs_shared:.3f}",
f"owner_queue_signal={'true' if owner_signal else 'false'}",
f"writeback_interference_signal={'true' if writeback_signal else 'false'}",
f"media_separation_signal={'true' if media_signal else 'false'}",
f"local_architecture_direction={direction}",
f"shipped_control_stability_gate={'pass' if shipped_stable else 'fail'}",
f"counterfactual_control_stability_gate={'pass' if counterfactual_stable else 'inconclusive'}",
f"diagnostic_controls_candidate_eligible={'true' if shipped_stable and counterfactual_stable else 'false'}",
"architecture_candidate_selected=false",
])
with open(summary_path, "a", encoding="utf-8") as out:
for line in summary:
out.write(line + "\n")
PY
benchmark_metric() {
local file="$1"
local prefix="$2"
local metric="$3"
awk -v prefix="${prefix}" -v metric="${metric}" '
index($1, prefix) == 1 {
for (i = 2; i <= NF; i++) {
if ($(i + 1) == metric) {
print $i
exit
}
}
}
' "${file}"
}
require_metric() {
local file="$1"
local prefix="$2"
local metric="$3"
local value
value="$(benchmark_metric "${file}" "${prefix}" "${metric}")"
if [[ -z "${value}" ]]; then
echo "missing ${prefix} ${metric} in ${file}" >&2
exit 1
fi
printf '%s' "${value}"
}
require_iteration_metric() {
local file="$1"
local iterations="$2"
local metric="$3"
local values
values="$(awk -v iterations="${iterations}" -v metric="${metric}" '
$1 == iterations {
for (i = 2; i <= NF; i++) {
if ($(i + 1) == metric) {
print $i
}
}
}
' "${file}")"
if [[ -z "${values}" || "${values}" == *$'\n'* ]]; then
echo "expected one ${iterations}-iteration ${metric} result in ${file}" >&2
exit 1
fi
printf '%s' "${values}"
}
rf1_mibps="$(require_iteration_metric "${ARTIFACT_DIR}/rf1-durable-adapter-benchmark.txt" 8000 MB/s)"
rf1_ns="$(require_iteration_metric "${ARTIFACT_DIR}/rf1-durable-adapter-benchmark.txt" 8000 ns/op)"
write_summary "rf1_durable_adapter_fixed_iterations=8000"
write_summary "rf1_durable_adapter_mibps=${rf1_mibps}"
write_summary "rf1_durable_adapter_ns_per_op=${rf1_ns}"
rf3_queue_saturation_observed=false
for writers in 1 4; do
prefix="BenchmarkPhase167RF3SyncQuorumContention/writers_${writers}-"
write_summary "rf3_writers_${writers}_fixed_iterations=2048"
write_summary "rf3_writers_${writers}_mibps=$(require_metric "${ARTIFACT_DIR}/rf3-real-tcp-benchmark.txt" "${prefix}" MB/s)"
write_summary "rf3_writers_${writers}_ns_per_op=$(require_metric "${ARTIFACT_DIR}/rf3-real-tcp-benchmark.txt" "${prefix}" ns/op)"
write_summary "rf3_writers_${writers}_fanout_ns_per_op=$(require_metric "${ARTIFACT_DIR}/rf3-real-tcp-benchmark.txt" "${prefix}" repl_fanout_ns/op)"
write_summary "rf3_writers_${writers}_ack_wait_ns_per_op=$(require_metric "${ARTIFACT_DIR}/rf3-real-tcp-benchmark.txt" "${prefix}" repl_ack_wait_ns/op)"
write_summary "rf3_writers_${writers}_queue_max_depth=$(require_metric "${ARTIFACT_DIR}/rf3-real-tcp-benchmark.txt" "${prefix}" peer_queue_max_depth)"
queue_saturated="$(require_metric "${ARTIFACT_DIR}/rf3-real-tcp-benchmark.txt" "${prefix}" peer_queue_saturated)"
if [[ "${queue_saturated}" != "0" ]]; then
rf3_queue_saturation_observed=true
fi
write_summary "rf3_writers_${writers}_queue_saturated=${queue_saturated}"
done
write_summary "rf3_queue_saturation_observed=${rf3_queue_saturation_observed}"
write_summary "rf1_rf3_component_attribution=complete"
write_summary "mounted_nvme_tcp_control=pending_same_session_live_gate"
write_summary "d3_close_allowed=false"
write_summary "architecture_candidate_selected=false"
write_summary "phase173_architecture_controls_status=ok"
cleanup
find "${STORE_DIR}" -maxdepth 1 -type f \( -name 'phase173-control-*' -o -name '*.scratch' \) -print -quit | grep -q . && {
echo "phase173 control residue remains under ${STORE_DIR}" >&2
exit 1
}
write_summary "store_residue_count=0"
cat "${SUMMARY}"
@@ -0,0 +1,243 @@
#!/usr/bin/env bash
set -euo pipefail
ROOT="${1:-$(pwd)}"
ARTIFACT_DIR="${SW_BLOCK_ARTIFACT_DIR:-${ROOT}/results/phase173-fixed-work-baseline-gate}"
STORE_DIR="${SW_BLOCK_PHASE173_STORE_DIR:-${ARTIFACT_DIR}/stores}"
SUMMARY="${ARTIFACT_DIR}/phase173-fixed-work-baseline-summary.txt"
RESULTS="${ARTIFACT_DIR}/phase173-fixed-work-results.jsonl"
TEST_BINARY="${ARTIFACT_DIR}/storage.test"
SHAPES_FORWARD=(sequential_4k scattered_4k batch_16 mounted_mixed)
SHAPES_REVERSE=(mounted_mixed batch_16 scattered_4k sequential_4k)
WRITERS_FORWARD=(1 2 4 8)
WRITERS_REVERSE=(8 4 2 1)
SETS=2
RUNS=5
DIAGNOSTIC_RUNS=1
MAX_RANGE="1.25"
mkdir -p "${ARTIFACT_DIR}" "${STORE_DIR}" "${ARTIFACT_DIR}/environment" "${ARTIFACT_DIR}/logs"
: >"${SUMMARY}"
: >"${RESULTS}"
cleanup() {
rm -f "${STORE_DIR}"/phase173-*.store
}
trap cleanup EXIT
write_summary() {
echo "$*" | tee -a "${SUMMARY}" >/dev/null
}
capture() {
local name="$1"
shift
"$@" >"${ARTIFACT_DIR}/environment/${name}.txt" 2>&1 || true
}
write_summary "phase173_fixed_work_baseline_status=running"
write_summary "contract=phase173-fixed-work-v1"
write_summary "sets=${SETS}"
write_summary "four_writer_runs_per_set=${RUNS}"
write_summary "diagnostic_runs_per_set=${DIAGNOSTIC_RUNS}"
write_summary "four_writer_max_min_limit=${MAX_RANGE}"
write_summary "flusher_interval_ms=100"
write_summary "flusher_phase_policy=restart_after_warmup_with_start_signal"
write_summary "page_cache_policy=warm_process_and_filesystem_no_drop_caches"
write_summary "go_benchmark_autocalibration_allowed=false"
write_summary "architecture_candidate_admission_allowed=false"
write_summary "precondition_runs=32"
write_summary "measured_store_reuse_required=true"
store_source="$(findmnt -n -T "${STORE_DIR}" -o SOURCE)"
store_filesystem="$(findmnt -n -T "${STORE_DIR}" -o FSTYPE)"
if [[ "${store_source}" != /dev/* ]]; then
echo "store source ${store_source} is not a local block device" >&2
exit 1
fi
write_summary "store_source=${store_source}"
write_summary "store_filesystem=${store_filesystem}"
capture kernel uname -a
capture go-version go version
capture cpu lscpu
capture affinity taskset -pc "$$"
capture scheduler chrt -p "$$"
capture filesystem findmnt -T "${STORE_DIR}" -o TARGET,SOURCE,FSTYPE,OPTIONS
capture free-space df -hT "${STORE_DIR}"
capture block-devices lsblk -o NAME,TYPE,SIZE,ROTA,MODEL,FSTYPE,MOUNTPOINTS
capture load uptime
capture processes ps -eo pid,psr,ni,stat,comm,%cpu,%mem --sort=-%cpu
if command -v iostat >/dev/null 2>&1; then
capture iostat iostat -xz 1 2
fi
if compgen -G '/sys/class/thermal/thermal_zone*/temp' >/dev/null; then
for temp in /sys/class/thermal/thermal_zone*/temp; do
printf '%s=' "${temp}" >>"${ARTIFACT_DIR}/environment/thermal.txt"
cat "${temp}" >>"${ARTIFACT_DIR}/environment/thermal.txt" || true
done
else
echo "thermal_evidence=unavailable" >"${ARTIFACT_DIR}/environment/thermal.txt"
fi
cd "${ROOT}"
go test ./core/storage -run '^TestPhase173FixedWorkContract$' -count=1 \
>"${ARTIFACT_DIR}/contract-test.log" 2>&1
go test -c -o "${TEST_BINARY}" ./core/storage
for set_id in $(seq 1 "${SETS}"); do
sync
sleep 5
capture "set-${set_id}-start-iostat" iostat -xz 1 2
capture "set-${set_id}-start-load" uptime
if [[ "${set_id}" == "1" ]]; then
shapes=("${SHAPES_FORWARD[@]}")
writers_values=("${WRITERS_FORWARD[@]}")
else
shapes=("${SHAPES_REVERSE[@]}")
writers_values=("${WRITERS_REVERSE[@]}")
fi
for shape in "${shapes[@]}"; do
for writers in "${writers_values[@]}"; do
point_runs="${DIAGNOSTIC_RUNS}"
if [[ "${writers}" == "4" ]]; then
point_runs="${RUNS}"
fi
store_id="set${set_id}-${shape}-writers${writers}"
precondition_id="${store_id}-precondition"
precondition_log="${ARTIFACT_DIR}/logs/${precondition_id}.log"
SW_BLOCK_PHASE173_SHAPE="${shape}" \
SW_BLOCK_PHASE173_WRITERS="${writers}" \
SW_BLOCK_PHASE173_RUN_ID="${precondition_id}" \
SW_BLOCK_PHASE173_STORE_ID="${store_id}" \
SW_BLOCK_PHASE173_REUSE_STORE="true" \
SW_BLOCK_PHASE173_STORE_DIR="${STORE_DIR}" \
"${TEST_BINARY}" -test.run '^TestPhase173WALStoreFixedWork$' -test.v -test.count=1 \
>"${precondition_log}" 2>&1
grep -q '^phase173_fixed_work_result=' "${precondition_log}"
sync
sleep 0.25
for run_id in $(seq 1 "${point_runs}"); do
id="set${set_id}-${shape}-writers${writers}-run${run_id}"
log="${ARTIFACT_DIR}/logs/${id}.log"
SW_BLOCK_PHASE173_SHAPE="${shape}" \
SW_BLOCK_PHASE173_WRITERS="${writers}" \
SW_BLOCK_PHASE173_RUN_ID="${id}" \
SW_BLOCK_PHASE173_STORE_ID="${store_id}" \
SW_BLOCK_PHASE173_REUSE_STORE="true" \
SW_BLOCK_PHASE173_STORE_DIR="${STORE_DIR}" \
"${TEST_BINARY}" -test.run '^TestPhase173WALStoreFixedWork$' -test.v -test.count=1 \
>"${log}" 2>&1
result="$(sed -n 's/^phase173_fixed_work_result=//p' "${log}")"
if [[ -z "${result}" ]]; then
echo "missing fixed-work result in ${log}" >&2
exit 1
fi
printf '%s\n' "${result}" >>"${RESULTS}"
sync
sleep 0.25
done
done
done
done
python3 - "${RESULTS}" "${SUMMARY}" "${SETS}" "${RUNS}" "${MAX_RANGE}" <<'PY'
import json
import math
import statistics
import sys
from collections import defaultdict
results_path, summary_path, sets_text, runs_text, max_range_text = sys.argv[1:]
sets = int(sets_text)
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()]
shapes = ("sequential_4k", "scattered_4k", "batch_16", "mounted_mixed")
writers_values = (1, 2, 4, 8)
expected = sets * len(shapes) * (runs + len(writers_values) - 1)
if len(rows) != expected:
raise SystemExit(f"fixed-work rows={len(rows)} want {expected}")
grouped = defaultdict(list)
for row in rows:
key = (row["shape"], int(row["writers"]))
grouped[key].append(row)
if row["contract"] != "phase173-fixed-work-v1":
raise SystemExit(f"bad contract: {row}")
if not row["store_reused"]:
raise SystemExit(f"measured sample did not reuse its preconditioned store: {row}")
if row["final_sync_calls"] != 1:
raise SystemExit(f"final_sync_calls != 1: {row}")
if row["dirty_entries"] != 0 or row["checkpoint_lsn"] != row["head_lsn"] or row["head_lsn"] != row["synced_lsn"]:
raise SystemExit(f"incomplete drain: {row}")
if row["wal_encode_ops"] != row["logical_blocks"]:
raise SystemExit(f"logical/WAL record mismatch: {row}")
if row["commit_lock_wait_ops"] != row["api_operations"]:
raise SystemExit(f"API/commit operation mismatch: {row}")
if row["wal_append_ops"] < row["api_operations"]:
raise SystemExit(f"API/WAL physical append mismatch: {row}")
extra_writeats = row["wal_writeat_calls"] - row["wal_append_ops"]
if extra_writeats < 0 or extra_writeats > row["wal_wraps"]:
raise SystemExit(f"WAL padding/writeat mismatch: {row}")
if row["validation_failures"] != 0 or row["correctness_samples"] < 3:
raise SystemExit(f"correctness evidence failed: {row}")
if row["flusher_interval_ms"] != 100:
raise SystemExit(f"unexpected flusher interval: {row}")
if not row["flusher_phase_reset"]:
raise SystemExit(f"flusher phase was not reset after warmup: {row}")
summary = []
gate_ok = True
for shape in shapes:
for writers in writers_values:
group = grouped[(shape, writers)]
expected_group = sets * (runs if writers == 4 else 1)
if len(group) != expected_group:
raise SystemExit(f"shape={shape} writers={writers} rows={len(group)} want {expected_group}")
values = [float(row["foreground_mib_per_second"]) for row in group]
summary.append(f"{shape}_writers_{writers}_median_mibps={statistics.median(values):.3f}")
summary.append(f"{shape}_writers_{writers}_median_p99_ns={statistics.median(row['p99_ns'] for row in group):.0f}")
four_rows = grouped[(shape, 4)]
all_values = [float(row["foreground_mib_per_second"]) for row in four_rows]
overall_range = max(all_values) / min(all_values)
summary.append(f"{shape}_writers_4_combined_max_min_ratio={overall_range:.3f}")
if not math.isfinite(overall_range) or overall_range > max_range:
gate_ok = False
for set_id in range(1, sets + 1):
prefix = f"set{set_id}-{shape}-writers4-"
set_values = [
float(row["foreground_mib_per_second"])
for row in four_rows
if row["run_id"].startswith(prefix)
]
if len(set_values) != runs:
raise SystemExit(f"shape={shape} set={set_id} four-writer rows={len(set_values)}")
set_range = max(set_values) / min(set_values)
summary.append(f"{shape}_writers_4_set_{set_id}_max_min_ratio={set_range:.3f}")
if not math.isfinite(set_range) or set_range > max_range:
gate_ok = False
with open(summary_path, "a", encoding="utf-8") as out:
for line in summary:
out.write(line + "\n")
out.write(f"fixed_work_result_count={len(rows)}\n")
out.write("fixed_work_counter_reconciliation=true\n")
out.write("fixed_work_complete_drain=true\n")
out.write("fixed_work_correctness_samples=true\n")
out.write(f"four_writer_stability_gate={'pass' if gate_ok else 'fail'}\n")
out.write(f"architecture_candidate_admission_allowed={'true' if gate_ok else 'false'}\n")
out.write(f"phase173_fixed_work_baseline_status={'ok' if gate_ok else 'unstable'}\n")
if not gate_ok:
raise SystemExit("four-writer stability exceeded the predeclared 1.25x range")
PY
cleanup
sync
find "${STORE_DIR}" -maxdepth 1 -type f -name 'phase173-*.store' -print -quit | grep -q . && {
echo "fixed-work store residue remains under ${STORE_DIR}" >&2
exit 1
}
cat "${SUMMARY}"
@@ -0,0 +1,445 @@
#!/usr/bin/env bash
set -euo pipefail
ROOT="${1:-$(pwd)}"
ARTIFACT_DIR="${SW_BLOCK_ARTIFACT_DIR:-${ROOT}/results/phase173-shipped-path-attribution-gate}"
STORE_DIR="${SW_BLOCK_PHASE173_STORE_DIR:-${ARTIFACT_DIR}/stores}"
SUMMARY="${ARTIFACT_DIR}/phase173-shipped-path-attribution-summary.txt"
TEST_BINARY="${ARTIFACT_DIR}/storage.test"
SHAPE="mounted_mixed"
WRITERS=4
STORE_ID="d2-mounted-mixed-writers4"
TOOL_PID=""
TEST_PID=""
mkdir -p "${ARTIFACT_DIR}" "${STORE_DIR}" \
"${ARTIFACT_DIR}/environment" "${ARTIFACT_DIR}/logs" \
"${ARTIFACT_DIR}/profiles" "${ARTIFACT_DIR}/control"
: >"${SUMMARY}"
cleanup() {
if [[ -n "${TOOL_PID}" ]]; then
sudo -n kill -INT "${TOOL_PID}" >/dev/null 2>&1 || true
wait "${TOOL_PID}" >/dev/null 2>&1 || true
fi
if [[ -n "${TEST_PID}" ]]; then
kill "${TEST_PID}" >/dev/null 2>&1 || true
wait "${TEST_PID}" >/dev/null 2>&1 || true
fi
rm -rf "${ARTIFACT_DIR}/control/strace" "${ARTIFACT_DIR}/control/perf"
rm -f "${STORE_DIR}"/phase173-*.store
}
trap cleanup EXIT
write_summary() {
echo "$*" | tee -a "${SUMMARY}" >/dev/null
}
capture() {
local name="$1"
shift
"$@" >"${ARTIFACT_DIR}/environment/${name}.txt" 2>&1 || true
}
wait_for_file() {
local path="$1"
local pid="$2"
local attempts=300
while (( attempts > 0 )); do
if [[ -f "${path}" ]]; then
return 0
fi
if ! kill -0 "${pid}" >/dev/null 2>&1; then
echo "process ${pid} exited before ${path} appeared" >&2
return 1
fi
sleep 0.1
attempts=$((attempts - 1))
done
echo "timed out waiting for ${path}" >&2
return 1
}
extract_result() {
local log="$1"
local output="$2"
local result
result="$(sed -n 's/^phase173_fixed_work_result=//p' "${log}")"
if [[ -z "${result}" ]]; then
echo "missing fixed-work result in ${log}" >&2
return 1
fi
printf '%s\n' "${result}" >"${output}"
}
run_fixed_work() {
local run_id="$1"
local log="$2"
shift 2
env \
SW_BLOCK_PHASE173_SHAPE="${SHAPE}" \
SW_BLOCK_PHASE173_WRITERS="${WRITERS}" \
SW_BLOCK_PHASE173_RUN_ID="${run_id}" \
SW_BLOCK_PHASE173_STORE_ID="${STORE_ID}" \
SW_BLOCK_PHASE173_REUSE_STORE="true" \
SW_BLOCK_PHASE173_STORE_DIR="${STORE_DIR}" \
"$@" \
"${TEST_BINARY}" -test.run '^TestPhase173WALStoreFixedWork$' -test.v -test.count=1 \
>"${log}" 2>&1
}
start_controlled_test() {
local run_id="$1"
local control_dir="$2"
local log="$3"
rm -rf "${control_dir}"
mkdir -p "${control_dir}"
env \
SW_BLOCK_PHASE173_SHAPE="${SHAPE}" \
SW_BLOCK_PHASE173_WRITERS="${WRITERS}" \
SW_BLOCK_PHASE173_RUN_ID="${run_id}" \
SW_BLOCK_PHASE173_STORE_ID="${STORE_ID}" \
SW_BLOCK_PHASE173_REUSE_STORE="true" \
SW_BLOCK_PHASE173_STORE_DIR="${STORE_DIR}" \
SW_BLOCK_PHASE173_CONTROL_DIR="${control_dir}" \
"${TEST_BINARY}" -test.run '^TestPhase173WALStoreFixedWork$' -test.v -test.count=1 \
>"${log}" 2>&1 &
TEST_PID=$!
wait_for_file "${control_dir}/ready" "${TEST_PID}"
local reported_pid
reported_pid="$(cat "${control_dir}/ready")"
if [[ "${reported_pid}" != "${TEST_PID}" ]]; then
echo "control PID ${reported_pid} != test PID ${TEST_PID}" >&2
return 1
fi
}
finish_controlled_test() {
local control_dir="$1"
local log="$2"
local result="$3"
wait_for_file "${control_dir}/done" "${TEST_PID}"
sudo -n kill -INT "${TOOL_PID}"
wait "${TOOL_PID}" || true
TOOL_PID=""
: >"${control_dir}/detached"
wait "${TEST_PID}"
TEST_PID=""
extract_result "${log}" "${result}"
}
for tool in go python3 findmnt lsblk iostat strace perf; do
command -v "${tool}" >/dev/null 2>&1 || {
echo "required tool ${tool} is unavailable" >&2
exit 1
}
done
sudo -n true
write_summary "phase173_shipped_path_attribution_status=running"
write_summary "contract=phase173-fixed-work-v1"
write_summary "scope=walstore_engine_checkpoint_path"
write_summary "shape=${SHAPE}"
write_summary "writers=${WRITERS}"
write_summary "counter_window=post_warmup_foreground_through_final_drain"
write_summary "trace_window=post_warmup_foreground_through_final_drain_and_correctness"
write_summary "architecture_candidate_selected=false"
write_summary "optimization_code_present=false"
store_source="$(findmnt -n -T "${STORE_DIR}" -o SOURCE)"
store_filesystem="$(findmnt -n -T "${STORE_DIR}" -o FSTYPE)"
if [[ "${store_source}" != /dev/* ]]; then
echo "store source ${store_source} is not a local block device" >&2
exit 1
fi
store_device="$(lsblk -ndo PKNAME "${store_source}" | head -n1)"
if [[ -z "${store_device}" ]]; then
store_device="$(basename "${store_source}")"
fi
write_summary "store_source=${store_source}"
write_summary "store_device=${store_device}"
write_summary "store_filesystem=${store_filesystem}"
capture kernel uname -a
capture go-version go version
capture cpu lscpu
capture affinity taskset -pc "$$"
capture scheduler chrt -p "$$"
capture filesystem findmnt -T "${STORE_DIR}" -o TARGET,SOURCE,FSTYPE,OPTIONS
capture block-devices lsblk -o NAME,TYPE,SIZE,ROTA,MODEL,FSTYPE,MOUNTPOINTS
capture free-space df -hT "${STORE_DIR}"
capture load uptime
capture strace-version strace -V
capture perf-version perf --version
capture perf-policy sh -c 'cat /proc/sys/kernel/perf_event_paranoid'
cd "${ROOT}"
go test ./core/storage -run '^(TestFlusherInstrumentation|TestPhase173)' -count=1 \
>"${ARTIFACT_DIR}/local-tests.log" 2>&1
go vet ./core/storage >"${ARTIFACT_DIR}/go-vet.log" 2>&1
go test -c -o "${TEST_BINARY}" ./core/storage
precondition_log="${ARTIFACT_DIR}/logs/precondition.log"
run_fixed_work "d2-precondition" "${precondition_log}"
extract_result "${precondition_log}" "${ARTIFACT_DIR}/precondition-result.json"
sync
iostat -xyz 1 3 >"${ARTIFACT_DIR}/iostat.txt" 2>&1 &
iostat_pid=$!
sleep 0.2
plain_log="${ARTIFACT_DIR}/logs/plain.log"
run_fixed_work "d2-plain" "${plain_log}"
extract_result "${plain_log}" "${ARTIFACT_DIR}/plain-result.json"
wait "${iostat_pid}"
grep -Eq "(^|[[:space:]])${store_device}([[:space:]]|$)" "${ARTIFACT_DIR}/iostat.txt"
write_summary "iostat_device_observed=true"
write_summary "iostat_evidence=iostat.txt"
profile_log="${ARTIFACT_DIR}/logs/profile.log"
profile_dir="${ARTIFACT_DIR}/profiles/measured"
rm -rf "${profile_dir}"
run_fixed_work "d2-profile" "${profile_log}" \
SW_BLOCK_PHASE173_PROFILE_DIR="${profile_dir}"
extract_result "${profile_log}" "${ARTIFACT_DIR}/profile-result.json"
for profile in cpu heap allocs; do
test -s "${profile_dir}/${profile}.pprof"
go tool pprof -top -nodecount=40 "${TEST_BINARY}" \
"${profile_dir}/${profile}.pprof" \
>"${ARTIFACT_DIR}/profiles/${profile}-top.txt"
done
write_summary "cpu_profile=profiles/measured/cpu.pprof"
write_summary "heap_profile=profiles/measured/heap.pprof"
write_summary "allocs_profile=profiles/measured/allocs.pprof"
write_summary "cpu_profile_scope_exact=true"
write_summary "memory_delta_scope_exact=true"
write_summary "heap_profile_scope=post_window_after_gc"
write_summary "allocs_profile_scope=process_cumulative_reference"
strace_control="${ARTIFACT_DIR}/control/strace"
strace_log="${ARTIFACT_DIR}/logs/strace.log"
strace_output="${ARTIFACT_DIR}/strace.txt"
start_controlled_test "d2-strace" "${strace_control}" "${strace_log}"
sudo -n strace -f -qq -tt -T \
-e trace=pread64,pwrite64,fsync,fdatasync \
-p "${TEST_PID}" -o "${strace_output}" \
2>"${ARTIFACT_DIR}/strace.stderr.txt" &
TOOL_PID=$!
sleep 0.5
sudo -n kill -0 "${TOOL_PID}"
: >"${strace_control}/go"
finish_controlled_test "${strace_control}" "${strace_log}" \
"${ARTIFACT_DIR}/strace-result.json"
test -s "${strace_output}"
write_summary "strace_scope_exact=true"
write_summary "strace_evidence=strace.txt"
perf_control="${ARTIFACT_DIR}/control/perf"
perf_log="${ARTIFACT_DIR}/logs/perf.log"
perf_output="${ARTIFACT_DIR}/perf-stat.csv"
start_controlled_test "d2-perf" "${perf_control}" "${perf_log}"
sudo -n perf stat -x, \
-e task-clock,cycles,instructions,cache-misses,context-switches,cpu-migrations,page-faults \
-p "${TEST_PID}" -o "${perf_output}" \
2>"${ARTIFACT_DIR}/perf.stderr.txt" &
TOOL_PID=$!
sleep 0.5
sudo -n kill -0 "${TOOL_PID}"
: >"${perf_control}/go"
finish_controlled_test "${perf_control}" "${perf_log}" \
"${ARTIFACT_DIR}/perf-result.json"
test -s "${perf_output}"
write_summary "perf_scope_exact=true"
write_summary "perf_requires_sudo=true"
write_summary "perf_evidence=perf-stat.csv"
python3 - \
"${ARTIFACT_DIR}/plain-result.json" \
"${ARTIFACT_DIR}/profile-result.json" \
"${ARTIFACT_DIR}/strace-result.json" \
"${ARTIFACT_DIR}/perf-result.json" \
"${strace_output}" "${perf_output}" "${SUMMARY}" <<'PY'
import json
import re
import sys
plain_path, profile_path, strace_path, perf_path, trace_path, perf_csv, summary_path = sys.argv[1:]
paths = (plain_path, profile_path, strace_path, perf_path)
rows = [json.load(open(path, encoding="utf-8")) for path in paths]
for row in rows:
if row["contract"] != "phase173-fixed-work-v1":
raise SystemExit(f"bad contract: {row}")
if not row["store_reused"] or row["shape"] != "mounted_mixed" or row["writers"] != 4:
raise SystemExit(f"bad fixed-work identity: {row}")
logical_blocks = row["logical_blocks"]
logical_bytes = row["logical_bytes"]
if logical_blocks != 16000 or logical_bytes != logical_blocks * row["block_size"]:
raise SystemExit(f"bad logical work: {row}")
exact = {
"wal_copy_ops": logical_blocks,
"wal_copy_bytes": logical_bytes,
"wal_encode_ops": logical_blocks,
"wal_checksum_ops": logical_blocks,
"commit_lock_wait_ops": row["api_operations"],
"dirty_map_update_ops": logical_blocks,
"flush_snapshot_entries": logical_blocks,
"flush_header_reads": logical_blocks,
"flush_record_reads": logical_blocks,
"flush_record_decode_ops": logical_blocks,
"validated_records": logical_blocks,
"extent_write_ops": logical_blocks,
"extent_write_bytes": logical_bytes,
"final_sync_calls": 1,
"dirty_entries": 0,
"flush_record_decode_failures": 0,
"validation_failures": 0,
"superseded_entries": 0,
}
for key, want in exact.items():
if row[key] != want:
raise SystemExit(f"{row['run_id']} {key}={row[key]} want {want}")
if row["wal_encode_bytes"] != row["flush_record_read_bytes"]:
raise SystemExit(f"WAL encoded/read bytes disagree: {row}")
if row["flush_record_decode_bytes"] != row["flush_record_read_bytes"]:
raise SystemExit(f"WAL read/decode bytes disagree: {row}")
if row["checkpoint_lsn"] != row["head_lsn"] or row["head_lsn"] != row["synced_lsn"]:
raise SystemExit(f"incomplete checkpoint: {row}")
if row["wal_writeat_calls"] < row["wal_append_ops"]:
raise SystemExit(f"WAL WriteAt accounting failed: {row}")
if row["checkpoint_write_ops"] != row["checkpoint_sync_ops"]:
raise SystemExit(f"checkpoint write/sync accounting failed: {row}")
if row["extent_sync_ops"] != row["flush_cycles"]:
raise SystemExit(f"extent sync/cycle accounting failed: {row}")
if row["measured_alloc_bytes"] <= 0 or row["measured_mallocs"] <= 0:
raise SystemExit(f"measured allocation evidence is empty: {row}")
trace = open(trace_path, encoding="utf-8", errors="replace").read()
counts = {name: len(re.findall(rf"\b{name}\(", trace)) for name in ("pread64", "pwrite64", "fsync", "fdatasync")}
traced = rows[2]
expected_pread = traced["flush_header_reads"] + traced["flush_record_reads"] + traced["correctness_samples"]
expected_pwrite = traced["wal_writeat_calls"] + traced["extent_write_ops"] + traced["checkpoint_write_ops"]
expected_sync = traced["extent_sync_ops"] + traced["checkpoint_sync_ops"] + traced["final_sync_calls"]
if counts["pread64"] != expected_pread:
raise SystemExit(f"strace pread64={counts['pread64']} want {expected_pread}")
if counts["pwrite64"] != expected_pwrite:
raise SystemExit(f"strace pwrite64={counts['pwrite64']} want {expected_pwrite}")
if counts["fsync"] + counts["fdatasync"] != expected_sync:
raise SystemExit(f"strace sync={counts['fsync'] + counts['fdatasync']} want {expected_sync}")
perf_text = open(perf_csv, encoding="utf-8", errors="replace").read()
perf_values = {}
for event in ("task-clock", "cycles", "instructions", "cache-misses", "context-switches", "cpu-migrations", "page-faults"):
matching = [line for line in perf_text.splitlines() if event in line]
if not matching or any("<not" in line for line in matching):
raise SystemExit(f"perf event unavailable: {event}")
values = []
for line in matching:
value = line.split(",", 1)[0].strip()
try:
values.append(float(value))
except ValueError as error:
raise SystemExit(f"bad perf value for {event}: {line}") from error
perf_values[event] = sum(values)
plain = rows[0]
known_flush = sum(plain[key] for key in (
"flush_snapshot_ns",
"flush_opportunity_ns",
"flush_header_read_ns",
"flush_record_read_ns",
"flush_record_decode_ns",
"extent_write_ns",
"extent_sync_ns",
"checkpoint_write_ns",
"checkpoint_sync_ns",
))
flush_remainder = max(0, plain["flush_cycle_ns"] - known_flush)
summary = [
"fixed_work_runs_reconciled=4",
"product_counter_reconciliation=true",
f"logical_operations={plain['api_operations']}",
f"logical_blocks={plain['logical_blocks']}",
f"logical_bytes={plain['logical_bytes']}",
f"foreground_ns={plain['foreground_ns']}",
f"foreground_mib_per_second={plain['foreground_mib_per_second']:.3f}",
f"final_sync_ns={plain['final_sync_ns']}",
f"final_drain_ns={plain['final_drain_ns']}",
f"measured_alloc_bytes={plain['measured_alloc_bytes']}",
f"measured_mallocs={plain['measured_mallocs']}",
f"measured_frees={plain['measured_frees']}",
f"measured_heap_alloc_start={plain['measured_heap_alloc_start']}",
f"measured_heap_alloc_end={plain['measured_heap_alloc_end']}",
f"wal_copy_ops={plain['wal_copy_ops']}",
f"wal_copy_bytes={plain['wal_copy_bytes']}",
f"wal_copy_ns={plain['wal_copy_ns']}",
f"wal_encode_ops={plain['wal_encode_ops']}",
f"wal_encode_bytes={plain['wal_encode_bytes']}",
f"wal_encode_ns={plain['wal_encode_ns']}",
f"wal_checksum_ops={plain['wal_checksum_ops']}",
f"wal_checksum_bytes={plain['wal_checksum_bytes']}",
f"wal_checksum_ns={plain['wal_checksum_ns']}",
f"wal_writeat_calls={plain['wal_writeat_calls']}",
f"wal_writeat_bytes={plain['wal_writeat_bytes']}",
f"wal_append_ops={plain['wal_append_ops']}",
f"wal_append_ns={plain['wal_append_ns']}",
f"wal_append_lock_wait_ns={plain['wal_append_lock_wait_ns']}",
f"commit_lock_wait_ops={plain['commit_lock_wait_ops']}",
f"commit_lock_wait_ns={plain['commit_lock_wait_ns']}",
f"dirty_map_update_ops={plain['dirty_map_update_ops']}",
f"dirty_map_update_ns={plain['dirty_map_update_ns']}",
f"flush_cycles={plain['flush_cycles']}",
f"flush_cycle_ns={plain['flush_cycle_ns']}",
f"flush_snapshot_entries={plain['flush_snapshot_entries']}",
f"flush_snapshot_ns={plain['flush_snapshot_ns']}",
f"flush_opportunity_ns={plain['flush_opportunity_ns']}",
f"flush_header_reads={plain['flush_header_reads']}",
f"flush_header_read_bytes={plain['flush_header_read_bytes']}",
f"flush_header_read_ns={plain['flush_header_read_ns']}",
f"flush_record_reads={plain['flush_record_reads']}",
f"flush_record_read_bytes={plain['flush_record_read_bytes']}",
f"flush_record_read_ns={plain['flush_record_read_ns']}",
f"flush_record_decode_ops={plain['flush_record_decode_ops']}",
f"flush_record_decode_bytes={plain['flush_record_decode_bytes']}",
f"flush_record_decode_ns={plain['flush_record_decode_ns']}",
f"extent_write_ops={plain['extent_write_ops']}",
f"extent_write_bytes={plain['extent_write_bytes']}",
f"extent_write_ns={plain['extent_write_ns']}",
f"extent_sync_ops={plain['extent_sync_ops']}",
f"extent_sync_ns={plain['extent_sync_ns']}",
f"checkpoint_write_ops={plain['checkpoint_write_ops']}",
f"checkpoint_write_ns={plain['checkpoint_write_ns']}",
f"checkpoint_sync_ops={plain['checkpoint_sync_ops']}",
f"checkpoint_sync_ns={plain['checkpoint_sync_ns']}",
f"flush_unattributed_remainder_ns={flush_remainder}",
f"strace_pread64_calls={counts['pread64']}",
f"strace_pwrite64_calls={counts['pwrite64']}",
f"strace_sync_calls={counts['fsync'] + counts['fdatasync']}",
"strace_product_counter_reconciliation=true",
f"perf_task_clock={perf_values['task-clock']:.0f}",
f"perf_cycles={perf_values['cycles']:.0f}",
f"perf_instructions={perf_values['instructions']:.0f}",
f"perf_cache_misses={perf_values['cache-misses']:.0f}",
f"perf_context_switches={perf_values['context-switches']:.0f}",
f"perf_cpu_migrations={perf_values['cpu-migrations']:.0f}",
f"perf_page_faults={perf_values['page-faults']:.0f}",
"perf_required_events_present=true",
"checkpoint_frontiers_equal=true",
"complete_drain=true",
"architecture_candidate_selected=false",
"phase173_shipped_path_attribution_status=ok",
]
with open(summary_path, "a", encoding="utf-8") as out:
for line in summary:
out.write(line + "\n")
PY
cleanup
TOOL_PID=""
TEST_PID=""
sync
find "${STORE_DIR}" -maxdepth 1 -type f -name 'phase173-*.store' -print -quit | grep -q . && {
echo "phase173 attribution store residue remains under ${STORE_DIR}" >&2
exit 1
}
write_summary "store_residue_count=0"
cat "${SUMMARY}"
@@ -0,0 +1,279 @@
#!/usr/bin/env bash
set -euo pipefail
ROOT="${1:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)}"
M01_HOST="${SW_BLOCK_PHASE174_M01_HOST:-testdev@192.168.1.181}"
M02_HOST="${SW_BLOCK_PHASE174_M02_HOST:-testdev@192.168.1.184}"
TP01_HOST="${SW_BLOCK_PHASE174_TP01_HOST:-testdev@192.168.1.188}"
M01_DATA_IP="${SW_BLOCK_PHASE174_M01_DATA_IP:-192.168.1.181}"
TP01_DATA_IP="${SW_BLOCK_PHASE174_TP01_DATA_IP:-192.168.1.188}"
SSH_KEY="${SW_BLOCK_PHASE174_SSH_KEY:-/c/work/dev_server/testdev_key}"
PUBLISH_ROOT="${SW_BLOCK_PHASE174_PUBLISH_ROOT:-/mnt/smb/work/share/g15d-k8s}"
RUN_ID="${SW_BLOCK_PHASE174_RUN_ID:-$(date -u +%Y%m%dT%H%M%SZ)-phase174-d2-rf3-distinct}"
ARTIFACT_DIR="${SW_BLOCK_ARTIFACT_DIR:-/tmp/${RUN_ID}}"
LOCAL_BINARY="/tmp/${RUN_ID}-replication.test"
PREBUILT_BINARY="${SW_BLOCK_PHASE174_PREBUILT_BINARY:-}"
REMOTE_ROOT="/tmp/${RUN_ID}"
REMOTE_BINARY="${REMOTE_ROOT}/replication.test"
M02_STORE_ROOT="/data/nvme/block/${RUN_ID}-stores"
RESULTS="${ARTIFACT_DIR}/phase174-distinct-node-rf3-results.jsonl"
SUMMARY="${ARTIFACT_DIR}/phase174-distinct-node-rf3-summary.txt"
M01_ADDR="${M01_DATA_IP}:17411"
TP01_ADDR="${TP01_DATA_IP}:17412"
RUNS=5
WRITERS=(1 4 8)
GATE_COMPLETE=false
SSH=(ssh -T -i "${SSH_KEY}" -o ConnectTimeout=10 -o StrictHostKeyChecking=no -o BatchMode=yes)
SCP=(scp -q -i "${SSH_KEY}" -o ConnectTimeout=10 -o StrictHostKeyChecking=no -o BatchMode=yes)
remote() {
local host="$1"
shift
"${SSH[@]}" "${host}" "$@"
}
write_summary() {
echo "$*" | tee -a "${SUMMARY}" >/dev/null
}
cleanup() {
local exit_status=$?
if [[ "${GATE_COMPLETE}" != "true" ]]; then
mkdir -p "${ARTIFACT_DIR}/remote"
for spec in "${M01_HOST}:m01" "${TP01_HOST}:tp01"; do
local host="${spec%:*}" node="${spec##*:}"
remote "${host}" "for pidfile in '${REMOTE_ROOT}'/w*-'${node}'/pid; do
test -f \"\${pidfile}\" || continue
touch \"\$(dirname \"\${pidfile}\")/stop\"
done
for pidfile in '${REMOTE_ROOT}'/w*-'${node}'/pid; do
test -f \"\${pidfile}\" || continue
pid=\$(cat \"\${pidfile}\")
for _ in \$(seq 1 50); do kill -0 \"\${pid}\" 2>/dev/null || break; sleep 0.1; done
if kill -0 \"\${pid}\" 2>/dev/null && tr '\\0' ' ' <\"/proc/\${pid}/cmdline\" | grep -Fq '${REMOTE_BINARY}'; then
kill \"\${pid}\"
fi
done" >/dev/null 2>&1 || true
for writers in "${WRITERS[@]}"; do
local dir="${REMOTE_ROOT}/w${writers}-${node}"
"${SCP[@]}" "${host}:${dir}/replica.log" "${ARTIFACT_DIR}/remote/w${writers}-${node}-failure.log" >/dev/null 2>&1 || true
"${SCP[@]}" "${host}:${dir}/result.json" "${ARTIFACT_DIR}/remote/w${writers}-${node}-failure-result.json" >/dev/null 2>&1 || true
done
done
write_summary "phase174_distinct_node_rf3_status=failed"
write_summary "failure_artifact=${PUBLISH_ROOT}/${RUN_ID}.tar.gz"
tar -C "$(dirname "${ARTIFACT_DIR}")" -czf "${ARTIFACT_DIR}.tar.gz" "$(basename "${ARTIFACT_DIR}")" >/dev/null 2>&1 || true
sha256sum "${ARTIFACT_DIR}.tar.gz" >"${ARTIFACT_DIR}.tar.gz.sha256" 2>/dev/null || true
"${SCP[@]}" "${ARTIFACT_DIR}.tar.gz" "${M02_HOST}:${PUBLISH_ROOT}/${RUN_ID}.tar.gz" >/dev/null 2>&1 || true
fi
rm -f "${LOCAL_BINARY}"
for host in "${M01_HOST}" "${TP01_HOST}"; do
remote "${host}" "test '${REMOTE_ROOT}' = '/tmp/${RUN_ID}'; rm -rf -- '${REMOTE_ROOT}'" >/dev/null 2>&1 || true
done
remote "${M02_HOST}" "test '${REMOTE_ROOT}' = '/tmp/${RUN_ID}'; test '${M02_STORE_ROOT}' = '/data/nvme/block/${RUN_ID}-stores'; rm -rf -- '${REMOTE_ROOT}' '${M02_STORE_ROOT}'" >/dev/null 2>&1 || true
return "${exit_status}"
}
trap cleanup EXIT
wait_remote_file() {
local host="$1" path="$2" label="$3"
for _ in $(seq 1 150); do
if remote "${host}" "test -s '${path}'"; then
return 0
fi
sleep 0.2
done
echo "timed out waiting for ${label}: ${host}:${path}" >&2
return 1
}
start_replica() {
local host="$1" address="$2" writers="$3" node="$4"
local dir="${REMOTE_ROOT}/w${writers}-${node}"
remote "${host}" "set -e; mkdir -p '${dir}'; setsid nohup env \
SW_BLOCK_PHASE174_REPLICA_STORE='${dir}/replica.store' \
SW_BLOCK_PHASE174_REPLICA_LISTEN='${address}' \
SW_BLOCK_PHASE174_REPLICA_READY_FILE='${dir}/ready' \
SW_BLOCK_PHASE174_REPLICA_STOP_FILE='${dir}/stop' \
SW_BLOCK_PHASE174_REPLICA_RESULT_FILE='${dir}/result.json' \
SW_BLOCK_PHASE174_REPLICA_FINAL_SET=1 \
SW_BLOCK_PHASE174_REPLICA_FINAL_RUN=${RUNS} \
'${REMOTE_BINARY}' -test.run '^TestPhase174RemoteReplicaProcess$' -test.v -test.timeout=20m \
>'${dir}/replica.log' 2>&1 </dev/null & echo \$! >'${dir}/pid'"
wait_remote_file "${host}" "${dir}/ready" "${node} replica readiness"
}
stop_replica() {
local host="$1" writers="$2" node="$3"
local dir="${REMOTE_ROOT}/w${writers}-${node}"
remote "${host}" "touch '${dir}/stop'"
wait_remote_file "${host}" "${dir}/result.json" "${node} replica result"
"${SCP[@]}" "${host}:${dir}/result.json" "${ARTIFACT_DIR}/remote/w${writers}-${node}-result.json"
"${SCP[@]}" "${host}:${dir}/replica.log" "${ARTIFACT_DIR}/remote/w${writers}-${node}.log"
}
mkdir -p "${ARTIFACT_DIR}/environment" "${ARTIFACT_DIR}/logs" "${ARTIFACT_DIR}/remote"
: >"${SUMMARY}"
: >"${RESULTS}"
required_commands=(ssh scp python3 tar)
if [[ -z "${PREBUILT_BINARY}" ]]; then
required_commands+=(go)
fi
for command in "${required_commands[@]}"; do
command -v "${command}" >/dev/null 2>&1 || {
echo "missing required command: ${command}" >&2
exit 2
}
done
write_summary "phase174_distinct_node_rf3_status=running"
write_summary "contract=phase174-distinct-node-rf3-v1"
write_summary "source_commit=$(git -C "${ROOT}" rev-parse HEAD)"
write_summary "foreground_ack_profile=sync_quorum_rf3"
write_summary "post_measurement_drain=probe_catchup_then_sync_all"
write_summary "transport=tcp"
write_summary "network_class=management_lan"
write_summary "primary_node=m02"
write_summary "replica_nodes=m01,tp01"
write_summary "primary_management_ip=192.168.1.184"
write_summary "replica_addresses=${M01_ADDR},${TP01_ADDR}"
write_summary "tp01_roce_capable=false"
write_summary "cross_ack_profile_throughput_ratio_allowed=false"
for spec in "m01:${M01_HOST}" "m02:${M02_HOST}" "tp01:${TP01_HOST}"; do
name="${spec%%:*}"
host="${spec#*:}"
remote "${host}" 'hostname; uname -a; uptime; lsblk -o NAME,TYPE,SIZE,ROTA,MODEL,FSTYPE,MOUNTPOINTS; ip -brief address' \
>"${ARTIFACT_DIR}/environment/${name}.txt"
done
remote "${M02_HOST}" "test \"\$(findmnt -n -T /data/nvme/block -o SOURCE)\" = /dev/nvme0n1p1"
remote "${M01_HOST}" "findmnt -n -T /tmp -o SOURCE,FSTYPE" >"${ARTIFACT_DIR}/environment/m01-store.txt"
remote "${TP01_HOST}" "findmnt -n -T /tmp -o SOURCE,FSTYPE" >"${ARTIFACT_DIR}/environment/tp01-store.txt"
remote "${M01_HOST}" "! ss -ltnH | grep -q ':17411 '"
remote "${TP01_HOST}" "! ss -ltnH | grep -q ':17412 '"
cd "${ROOT}"
if [[ -n "${PREBUILT_BINARY}" ]]; then
cp "${PREBUILT_BINARY}" "${LOCAL_BINARY}"
else
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go test -tags swblock_testtools -c \
-o "${LOCAL_BINARY}" ./core/replication
fi
for host in "${M01_HOST}" "${M02_HOST}" "${TP01_HOST}"; do
remote "${host}" "test '${REMOTE_ROOT}' = '/tmp/${RUN_ID}'; rm -rf -- '${REMOTE_ROOT}'; mkdir -p '${REMOTE_ROOT}'"
"${SCP[@]}" "${LOCAL_BINARY}" "${host}:${REMOTE_BINARY}"
remote "${host}" "chmod 0755 '${REMOTE_BINARY}'"
done
remote "${M02_HOST}" "test '${M02_STORE_ROOT}' = '/data/nvme/block/${RUN_ID}-stores'; rm -rf -- '${M02_STORE_ROOT}'; mkdir -p '${M02_STORE_ROOT}'"
for writers in "${WRITERS[@]}"; do
start_replica "${M01_HOST}" "${M01_ADDR}" "${writers}" m01
start_replica "${TP01_HOST}" "${TP01_ADDR}" "${writers}" tp01
for run in $(seq 0 "${RUNS}"); do
log="${ARTIFACT_DIR}/logs/w${writers}-run${run}.log"
remote "${M02_HOST}" "env \
SW_BLOCK_PHASE174_STORE_DIR='${M02_STORE_ROOT}/w${writers}' \
SW_BLOCK_PHASE174_LAYER=rf3_tcp \
SW_BLOCK_PHASE174_WRITERS=${writers} \
SW_BLOCK_PHASE174_SET=1 \
SW_BLOCK_PHASE174_RUN=${run} \
SW_BLOCK_PHASE174_REMOTE_REPLICAS='${M01_ADDR},${TP01_ADDR}' \
GOMAXPROCS=4 taskset -c 0,2,4,6 \
'${REMOTE_BINARY}' -test.run '^TestPhase174FixedWorkPipeline$' -test.v -test.count=1 -test.timeout=10m" \
>"${log}" 2>&1
if [[ "${run}" != "0" ]]; then
sed -n 's/^phase174_fixed_work_result=//p' "${log}" >>"${RESULTS}"
fi
done
stop_replica "${M01_HOST}" "${writers}" m01
stop_replica "${TP01_HOST}" "${writers}" tp01
done
python3 - "${RESULTS}" "${ARTIFACT_DIR}/remote" "${SUMMARY}" "${RUNS}" <<'PY'
import glob
import json
import statistics
import sys
results_path, remote_dir, summary_path, runs_text = sys.argv[1:]
runs = int(runs_text)
rows = [json.loads(line) for line in open(results_path, encoding="utf-8") if line.strip()]
if len(rows) != 3 * runs:
raise SystemExit(f"primary rows={len(rows)} want {3 * runs}")
queue_saturation_rows = 0
replica_probe_count = 0
replica_catchup_count = 0
replica_rebuild_count = 0
max_replica_lag_lsn = 0
for row in rows:
if row["contract"] != "phase174-fixed-work-v1" or row["ack_profile"] != "sync_quorum_rf3":
raise SystemExit(f"bad primary contract: {row}")
if row["replica_count"] != 2 or not row["remote_replica_evidence_required"]:
raise SystemExit(f"bad external replica contract: {row}")
if not row["post_measurement_sync_all"] or row["post_measurement_sync_all_ns"] <= 0:
raise SystemExit(f"missing post-measurement drain: {row}")
if not row["post_measurement_recovery"] or row.get("replica_probe_count") != 2:
raise SystemExit(f"missing post-measurement recovery evidence: {row}")
if row["api_operations"] != 16384 or row["logical_bytes"] != 67108864:
raise SystemExit(f"bad fixed work: {row}")
if row["primary_wal_write_ops"] != 16384 or row["replication_write_ops"] != 16384:
raise SystemExit(f"write counter mismatch: {row}")
if not row["close_recover_complete"] or row["primary_stable_lsn"] != row["primary_head_lsn"]:
raise SystemExit(f"primary recovery mismatch: {row}")
if row.get("peer_queue_saturated", 0) > 0:
queue_saturation_rows += 1
replica_probe_count += row["replica_probe_count"]
replica_catchup_count += row.get("replica_catchup_count", 0)
replica_rebuild_count += row.get("replica_rebuild_count", 0)
max_replica_lag_lsn = max(max_replica_lag_lsn, row.get("max_replica_lag_lsn", 0))
remote_paths = sorted(glob.glob(f"{remote_dir}/w*-*-result.json"))
if len(remote_paths) != 6:
raise SystemExit(f"remote results={len(remote_paths)} want 6")
for path in remote_paths:
row = json.load(open(path, encoding="utf-8"))
if row["status"] != "ok" or row["stable_lsn"] != row["head_lsn"]:
raise SystemExit(f"bad remote recovery {path}: {row}")
if row["head_lsn"] != row["expected_head_lsn"] or row["correctness_samples"] < 5:
raise SystemExit(f"bad remote frontier/data {path}: {row}")
with open(summary_path, "a", encoding="utf-8") as out:
for writers in (1, 4, 8):
rates = [row["mib_per_second"] for row in rows if int(row["writers"]) == writers]
out.write(f"writers_{writers}_median_mibps={statistics.median(rates):.3f}\n")
out.write(f"writers_{writers}_max_min_ratio={max(rates) / min(rates):.3f}\n")
out.write(f"primary_result_count={len(rows)}\n")
out.write(f"remote_recovered_replica_count={len(remote_paths)}\n")
out.write(f"peer_queue_saturation_row_count={queue_saturation_rows}\n")
out.write(f"replica_probe_count={replica_probe_count}\n")
out.write(f"replica_catchup_count={replica_catchup_count}\n")
out.write(f"replica_rebuild_count={replica_rebuild_count}\n")
out.write(f"max_replica_lag_lsn={max_replica_lag_lsn}\n")
out.write("remote_replica_frontiers_and_bytes_equal=true\n")
out.write("foreground_sync_quorum_preserved=true\n")
out.write("post_measurement_recovery_verified=true\n")
out.write("post_measurement_sync_all_verified=true\n")
out.write("rf3_distinct_node_healthy=true\n")
out.write("architecture_candidate_selected=false\n")
out.write("product_mutation_present=false\n")
out.write("phase174_distinct_node_rf3_status=ok\n")
PY
GATE_COMPLETE=true
cleanup
trap - EXIT
for host in "${M01_HOST}" "${M02_HOST}" "${TP01_HOST}"; do
remote "${host}" "test ! -e '${REMOTE_ROOT}'"
done
remote "${M02_HOST}" "test ! -e '${M02_STORE_ROOT}'"
write_summary "remote_process_and_store_residue_count=0"
write_summary "published_artifact=${PUBLISH_ROOT}/${RUN_ID}.tar.gz"
tar -C "$(dirname "${ARTIFACT_DIR}")" -czf "${ARTIFACT_DIR}.tar.gz" "$(basename "${ARTIFACT_DIR}")"
"${SCP[@]}" "${ARTIFACT_DIR}.tar.gz" "${M02_HOST}:${PUBLISH_ROOT}/${RUN_ID}.tar.gz"
sha256sum "${ARTIFACT_DIR}.tar.gz" | tee "${ARTIFACT_DIR}.tar.gz.sha256"
cat "${SUMMARY}"
@@ -0,0 +1,321 @@
#!/usr/bin/env bash
set -euo pipefail
ROOT="${1:-$(pwd)}"
ARTIFACT_DIR="${SW_BLOCK_ARTIFACT_DIR:-${ROOT}/results/phase174-fixed-work-pipeline-gate}"
STORE_DIR="${SW_BLOCK_PHASE174_STORE_DIR:-${ARTIFACT_DIR}/stores}"
SUMMARY="${ARTIFACT_DIR}/phase174-fixed-work-pipeline-summary.txt"
RESULTS="${ARTIFACT_DIR}/phase174-fixed-work-results.jsonl"
TEST_BINARY="${ARTIFACT_DIR}/phase174-replication.test"
RUNS=5
MAX_RANGE="1.25"
CPUSET="${SW_BLOCK_PHASE174_CPUSET:-0,2,4,6}"
GOMAXPROCS_VALUE="${SW_BLOCK_PHASE174_GOMAXPROCS:-4}"
LAYERS_FORWARD=(direct_walstore adapter_rf1 rf3_tcp)
LAYERS_REVERSE=(rf3_tcp adapter_rf1 direct_walstore)
WRITERS_FORWARD=(1 4 8)
WRITERS_REVERSE=(8 4 1)
mkdir -p "${ARTIFACT_DIR}/logs" "${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 store must use a dedicated filesystem: store=${store_source:-missing} root=${root_source}" >&2
exit 1
fi
write_summary "phase174_fixed_work_pipeline_status=running"
write_summary "contract=phase174-fixed-work-v1"
write_summary "runs_per_set=${RUNS}"
write_summary "sets=2"
write_summary "writers=1,4,8"
write_summary "logical_block_bytes=4096"
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 "rf1_ack_profile=local_durable"
write_summary "rf3_ack_profile=sync_quorum_rf3"
write_summary "cross_ack_profile_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/replication -run '^TestPhase174FixedWorkContract$' -count=1 \
>"${ARTIFACT_DIR}/contract-test.log" 2>&1
go test -tags swblock_testtools -c -o "${TEST_BINARY}" ./core/replication
for set_id in 1 2; do
sync
sleep 5
capture "set-${set_id}-start-load" uptime
if [[ "${set_id}" == "1" ]]; then
layers=("${LAYERS_FORWARD[@]}")
writers_values=("${WRITERS_FORWARD[@]}")
else
layers=("${LAYERS_REVERSE[@]}")
writers_values=("${WRITERS_REVERSE[@]}")
fi
for layer in "${layers[@]}"; do
for writers in "${writers_values[@]}"; do
if [[ "${layer}" != "rf3_tcp" ]]; then
precondition_log="${ARTIFACT_DIR}/logs/set${set_id}-${layer}-writers${writers}-precondition.log"
SW_BLOCK_PHASE174_STORE_DIR="${STORE_DIR}" \
SW_BLOCK_PHASE174_LAYER="${layer}" \
SW_BLOCK_PHASE174_WRITERS="${writers}" \
SW_BLOCK_PHASE174_SET="${set_id}" \
SW_BLOCK_PHASE174_RUN=0 \
GOMAXPROCS="${GOMAXPROCS_VALUE}" taskset -c "${CPUSET}" \
"${TEST_BINARY}" -test.run '^TestPhase174FixedWorkPipeline$' -test.v -test.count=1 \
>"${precondition_log}" 2>&1
fi
for run in $(seq 1 "${RUNS}"); do
sync
sleep 0.25
run_log="${ARTIFACT_DIR}/logs/set${set_id}-${layer}-writers${writers}-run${run}.log"
SW_BLOCK_PHASE174_STORE_DIR="${STORE_DIR}" \
SW_BLOCK_PHASE174_LAYER="${layer}" \
SW_BLOCK_PHASE174_WRITERS="${writers}" \
SW_BLOCK_PHASE174_SET="${set_id}" \
SW_BLOCK_PHASE174_RUN="${run}" \
GOMAXPROCS="${GOMAXPROCS_VALUE}" taskset -c "${CPUSET}" \
"${TEST_BINARY}" -test.run '^TestPhase174FixedWorkPipeline$' -test.v -test.count=1 \
>"${run_log}" 2>&1
sed -n 's/^phase174_fixed_work_result=//p' "${run_log}" >>"${RESULTS}"
done
done
done
done
for layer in direct_walstore adapter_rf1; do
cpu_profiles=()
block_profiles=()
mutex_profiles=()
for profile_run in $(seq 1 "${RUNS}"); do
prefix="${ARTIFACT_DIR}/profiles/${layer}-run${profile_run}"
mkdir -p "${ARTIFACT_DIR}/profiles"
SW_BLOCK_PHASE174_STORE_DIR="${STORE_DIR}" \
SW_BLOCK_PHASE174_LAYER="${layer}" \
SW_BLOCK_PHASE174_WRITERS=4 \
SW_BLOCK_PHASE174_SET=1 \
SW_BLOCK_PHASE174_RUN="${profile_run}" \
GOMAXPROCS="${GOMAXPROCS_VALUE}" taskset -c "${CPUSET}" \
"${TEST_BINARY}" -test.run '^TestPhase174FixedWorkPipeline$' -test.count=1 \
-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=30 "${TEST_BINARY}" "${cpu_profiles[@]}" \
>"${ARTIFACT_DIR}/profiles/${layer}-cpu-top.txt" 2>&1
go tool pprof -top -nodecount=30 "${TEST_BINARY}" "${block_profiles[@]}" \
>"${ARTIFACT_DIR}/profiles/${layer}-block-top.txt" 2>&1
go tool pprof -top -nodecount=30 "${TEST_BINARY}" "${mutex_profiles[@]}" \
>"${ARTIFACT_DIR}/profiles/${layer}-mutex-top.txt" 2>&1
done
python3 - "${RESULTS}" "${SUMMARY}" "${RUNS}" "${MAX_RANGE}" <<'PY'
import json
import math
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) != 90:
raise SystemExit(f"fixed-work rows={len(rows)} want 90")
groups = defaultdict(list)
for row in rows:
if row["contract"] != "phase174-fixed-work-v1":
raise SystemExit(f"bad contract: {row}")
if row["api_operations"] != 16384 or row["logical_bytes"] != 16384 * 4096:
raise SystemExit(f"bad fixed work: {row}")
if row["primary_wal_write_ops"] != 16384:
raise SystemExit(f"bad primary write count: {row}")
if row["primary_stable_lsn"] != row["primary_head_lsn"]:
raise SystemExit(f"primary frontier mismatch: {row}")
if not row["flusher_phase_reset"]:
raise SystemExit(f"flusher phase was not reset: {row}")
if not row["close_recover_complete"] or row["correctness_samples"] < 5:
raise SystemExit(f"close/recover correctness failed: {row}")
if row["foreground_ns"] <= 0 or row["final_sync_ns"] <= 0 or row["p99_ns"] <= 0:
raise SystemExit(f"missing timing evidence: {row}")
if row["layer"] == "rf3_tcp":
if row["ack_profile"] != "sync_quorum_rf3" or row["replication_write_ops"] != 16384:
raise SystemExit(f"bad RF3 contract: {row}")
if row["replica_count"] != 2 or row["replica_durable_count"] < 1:
raise SystemExit(f"RF3 did not satisfy quorum durability: {row}")
elif row["ack_profile"] != "local_durable" or row["replica_count"] != 0:
raise SystemExit(f"bad RF1 contract: {row}")
groups[(row["layer"], int(row["writers"]))].append(row)
for key, values in groups.items():
if len(values) != 2 * runs:
raise SystemExit(f"group {key} rows={len(values)} want {2 * runs}")
def median_rate(layer, writers):
return statistics.median(row["mib_per_second"] for row in groups[(layer, writers)])
def rate_range(layer, writers):
values = [row["mib_per_second"] for row in groups[(layer, writers)]]
return max(values) / min(values)
def set_rate_range(layer, writers, set_id):
values = [
row["mib_per_second"]
for row in groups[(layer, writers)]
if int(row["set"]) == set_id
]
if len(values) != runs:
raise SystemExit(f"group {(layer, writers)} set={set_id} rows={len(values)} want {runs}")
return max(values) / min(values)
def median_per_op(rows, field):
return statistics.median(row[field] / row["api_operations"] for row in rows)
def correlation(rows, field):
xs = [float(row["foreground_ns"]) for row in rows]
ys = [float(row[field]) for row in rows]
x_mean = statistics.mean(xs)
y_mean = statistics.mean(ys)
numerator = sum((x - x_mean) * (y - y_mean) for x, y in zip(xs, ys))
x_norm = math.sqrt(sum((x - x_mean) ** 2 for x in xs))
y_norm = math.sqrt(sum((y - y_mean) ** 2 for y in ys))
if x_norm == 0 or y_norm == 0:
return 0.0
return numerator / (x_norm * y_norm)
with open(summary_path, "a", encoding="utf-8") as out:
for layer in ("direct_walstore", "adapter_rf1", "rf3_tcp"):
for writers in (1, 4, 8):
out.write(f"{layer}_writers_{writers}_median_mibps={median_rate(layer, writers):.3f}\n")
out.write(f"{layer}_writers_{writers}_max_min_ratio={rate_range(layer, writers):.3f}\n")
direct_four = median_rate("direct_walstore", 4)
adapter_four = median_rate("adapter_rf1", 4)
direct_set_ranges = [set_rate_range("direct_walstore", 4, set_id) for set_id in (1, 2)]
adapter_set_ranges = [set_rate_range("adapter_rf1", 4, set_id) for set_id in (1, 2)]
rf1_stable = (
all(value <= max_range for value in direct_set_ranges)
and all(value <= max_range for value in adapter_set_ranges)
and rate_range("direct_walstore", 4) <= max_range
and rate_range("adapter_rf1", 4) <= max_range
)
rf3_rows = [row for row in rows if row["layer"] == "rf3_tcp"]
rf3_healthy = all(
row["replica_durable_count"] == 2
and row["replica_frontiers_equal"]
and row.get("peer_queue_saturated", 0) == 0
for row in rf3_rows
)
queue_saturation_rows = sum(row.get("peer_queue_saturated", 0) > 0 for row in rf3_rows)
adapter_rows = groups[("adapter_rf1", 4)]
for row in adapter_rows:
if row["adapter_request_ops"] != row["api_operations"]:
raise SystemExit(f"adapter request count mismatch: {row}")
if row["adapter_write_ops"] != row["api_operations"]:
raise SystemExit(f"adapter write count mismatch: {row}")
if row["adapter_request_bytes"] != row["logical_bytes"] or row["adapter_write_bytes"] != row["logical_bytes"]:
raise SystemExit(f"adapter byte count mismatch: {row}")
if row["adapter_storage_write_calls"] != row["api_operations"]:
raise SystemExit(f"adapter storage call count mismatch: {row}")
if row["adapter_storage_write_blocks"] != row["api_operations"]:
raise SystemExit(f"adapter storage block count mismatch: {row}")
row["storage_attributed_ns"] = (
row["primary_commit_lock_wait_ns"]
+ row["primary_wal_encode_ns"]
+ row["primary_wal_append_lock_wait_ns"]
+ row["primary_wal_append_ns"]
+ row["primary_dirty_map_ns"]
)
row["adapter_unattributed_ns"] = max(0, row["adapter_write_ns"] - row["storage_attributed_ns"])
attribution_fields = (
"adapter_write_ns",
"storage_attributed_ns",
"primary_commit_lock_wait_ns",
"primary_wal_encode_ns",
"primary_wal_append_ns",
"primary_dirty_map_ns",
"adapter_unattributed_ns",
"foreground_flusher_cycle_ns",
)
dominant = max(
("storage_attributed", "adapter_unattributed"),
key=lambda name: median_per_op(adapter_rows, f"{name}_ns"),
)
out.write(f"direct_walstore_writers_4_set1_max_min_ratio={direct_set_ranges[0]:.3f}\n")
out.write(f"direct_walstore_writers_4_set2_max_min_ratio={direct_set_ranges[1]:.3f}\n")
out.write(f"adapter_rf1_writers_4_set1_max_min_ratio={adapter_set_ranges[0]:.3f}\n")
out.write(f"adapter_rf1_writers_4_set2_max_min_ratio={adapter_set_ranges[1]:.3f}\n")
out.write(f"rf1_direct_adapter_four_writer_ratio={adapter_four / direct_four:.3f}\n")
for field in attribution_fields:
out.write(f"adapter_rf1_writers_4_{field}_per_op={median_per_op(adapter_rows, field):.3f}\n")
out.write(f"adapter_rf1_writers_4_{field}_foreground_correlation={correlation(adapter_rows, field):.3f}\n")
out.write(f"adapter_rf1_dominant_accounted_boundary={dominant}\n")
out.write("rf1_attribution_counter_reconciliation=true\n")
out.write("rf1_attribution_status=ok\n")
out.write(f"rf1_local_stability_gate={'pass' if rf1_stable else 'hold'}\n")
out.write(f"rf3_same_host_healthy_baseline={str(rf3_healthy).lower()}\n")
out.write(f"rf3_queue_saturation_row_count={queue_saturation_rows}\n")
out.write("rf3_same_host_admission_eligible=false\n")
out.write("rf3_distinct_node_gate_required=true\n")
out.write("d1_close_allowed=false\n")
out.write("architecture_candidate_selected=false\n")
out.write("product_mutation_present=false\n")
if not rf1_stable:
out.write("phase174_fixed_work_pipeline_status=hold\n")
raise SystemExit("RF1 fixed-work admission shape is unstable")
out.write("phase174_fixed_work_pipeline_status=ok\n")
PY
cleanup
find "${STORE_DIR}" -type f -name '*.store' -print -quit 2>/dev/null | grep -q . && {
echo "phase174 store residue remains under ${STORE_DIR}" >&2
exit 1
}
write_summary "store_residue_count=0"
cat "${SUMMARY}"
@@ -0,0 +1,130 @@
#!/usr/bin/env bash
set -euo pipefail
ROOT="${1:-$(pwd)}"
ARTIFACT_DIR="${SW_BLOCK_ARTIFACT_DIR:-${ROOT}/results/phase174-mounted-nvme-phase-profile-gate}"
BASELINE_DIR="${ARTIFACT_DIR}/phase120-mounted-profile"
SUMMARY="${ARTIFACT_DIR}/phase174-mounted-nvme-phase-profile-summary.txt"
SEQ_MIB="${SW_BLOCK_PHASE174_MOUNTED_SEQ_MIB:-256}"
PVC_SIZE="${SW_BLOCK_PHASE174_MOUNTED_PVC_SIZE:-1Gi}"
FRONTEND_NETWORK_CLASS="${SW_BLOCK_PHASE174_MOUNTED_FRONTEND_NETWORK_CLASS:-100gbe_tcp}"
SOURCE_COMMIT="${SW_BLOCK_PHASE174_SOURCE_COMMIT:-$(git -C "${ROOT}" rev-parse HEAD 2>/dev/null || true)}"
mkdir -p "${ARTIFACT_DIR}" "${BASELINE_DIR}"
: >"${SUMMARY}"
write_summary() {
echo "$*" | tee -a "${SUMMARY}" >/dev/null
}
summary_value() {
local file="$1"
local key="$2"
awk -F= -v key="${key}" '$1 == key {value = substr($0, length(key) + 2)} END {if (value != "") print value}' "${file}"
}
require_value() {
local file="$1"
local key="$2"
local value
value="$(summary_value "${file}" "${key}")"
if [[ -z "${value}" ]]; then
echo "missing ${key} in ${file}" >&2
exit 1
fi
printf '%s' "${value}"
}
assert_equal() {
local actual="$1"
local expected="$2"
local label="$3"
if [[ "${actual}" != "${expected}" ]]; then
echo "${label}=${actual}, want ${expected}" >&2
exit 1
fi
}
write_summary "phase174_mounted_nvme_phase_profile_status=running"
write_summary "source_commit=${SOURCE_COMMIT}"
write_summary "initiator=linux_kernel_nvme_tcp"
write_summary "workload=mounted_ext4_sequential_write"
write_summary "seq_size_mib=${SEQ_MIB}"
write_summary "frontend_network_class=${FRONTEND_NETWORK_CLASS}"
write_summary "status_surface=/status/nvme"
write_summary "mounted_shape_comparable=false"
write_summary "fixed_work_throughput_ratio_allowed=false"
SW_BLOCK_ARTIFACT_DIR="${BASELINE_DIR}" \
SW_BLOCK_PHASE120_PROFILE_WRITE=true \
SW_BLOCK_PHASE120_SEQ_MIB="${SEQ_MIB}" \
SW_BLOCK_PHASE120_PVC_SIZE="${PVC_SIZE}" \
SW_BLOCK_FRONTEND_NETWORK_CLASS="${FRONTEND_NETWORK_CLASS}" \
bash "${ROOT}/scripts/run-phase120-nvme-tcp-performance-baseline-gate.sh" "${ROOT}" \
>"${ARTIFACT_DIR}/phase120.stdout.txt" \
2>"${ARTIFACT_DIR}/phase120.stderr.txt"
BASELINE_SUMMARY="${BASELINE_DIR}/phase120-nvme-tcp-performance-baseline-summary.txt"
assert_equal "$(require_value "${BASELINE_SUMMARY}" phase120_nvme_tcp_performance_baseline_status)" "ok" "phase120 status"
assert_equal "$(require_value "${BASELINE_SUMMARY}" phase120_nvme_phase_profile_status)" "ok" "NVMe phase profile status"
assert_equal "$(require_value "${BASELINE_SUMMARY}" mounted_nvme_phase_counter_reconciliation)" "true" "phase counter reconciliation"
assert_equal "$(require_value "${BASELINE_SUMMARY}" mounted_client_latency_reconciliation_available)" "false" "mounted client latency boundary"
assert_equal "$(require_value "${BASELINE_SUMMARY}" mounted_shape_comparable)" "false" "mounted shape boundary"
assert_equal "$(require_value "${BASELINE_SUMMARY}" cleanup_status)" "ok" "cleanup status"
WRITE_OPS="$(require_value "${BASELINE_SUMMARY}" mounted_nvme_write_ops)"
INLINE_OPS="$(require_value "${BASELINE_SUMMARY}" mounted_nvme_inline_write_ops)"
R2T_OPS="$(require_value "${BASELINE_SUMMARY}" mounted_nvme_r2t_write_ops)"
R2T_PHASE_OPS="$(require_value "${BASELINE_SUMMARY}" mounted_nvme_r2t_collection_ops)"
HANDLER_OPS="$(require_value "${BASELINE_SUMMARY}" mounted_nvme_handler_ops)"
COMPLETION_OPS="$(require_value "${BASELINE_SUMMARY}" mounted_nvme_completion_send_ops)"
assert_equal "${R2T_PHASE_OPS}" "${R2T_OPS}" "R2T phase operations"
assert_equal "${HANDLER_OPS}" "${WRITE_OPS}" "handler operations"
assert_equal "${COMPLETION_OPS}" "${WRITE_OPS}" "completion operations"
MOUNTED_WRITE_SHAPE="$(python3 - "${WRITE_OPS}" "${INLINE_OPS}" "${R2T_OPS}" "$(require_value "${BASELINE_SUMMARY}" mounted_nvme_server_phase_ns)" <<'PY'
import sys
write_ops, inline_ops, r2t_ops, phase_ns = map(int, sys.argv[1:])
if write_ops <= 0 or phase_ns <= 0:
raise SystemExit(f"missing mounted NVMe work: writes={write_ops} phase_ns={phase_ns}")
if inline_ops + r2t_ops != write_ops:
raise SystemExit(f"write shape mismatch: writes={write_ops} inline={inline_ops} r2t={r2t_ops}")
if inline_ops == write_ops:
print("inline")
elif r2t_ops == write_ops:
print("r2t")
else:
print("mixed")
PY
)"
for key in \
seq_write_mibps \
seq_read_mibps \
mounted_nvme_write_ops \
mounted_nvme_inline_write_ops \
mounted_nvme_r2t_write_ops \
mounted_nvme_write_bytes \
mounted_nvme_capsule_receive_parse_ns_per_op \
mounted_nvme_r2t_collection_ns_per_op \
mounted_nvme_dispatch_wait_ns_per_op \
mounted_nvme_handler_ns_per_op \
mounted_nvme_completion_queue_wait_ns_per_op \
mounted_nvme_completion_send_ns_per_op \
mounted_nvme_server_phase_ns_per_op \
mounted_nvme_dominant_phase; do
write_summary "${key}=$(require_value "${BASELINE_SUMMARY}" "${key}")"
done
write_summary "synthetic_fixed_work_write_shape=r2t"
write_summary "mounted_write_shape=${MOUNTED_WRITE_SHAPE}"
if [[ "${MOUNTED_WRITE_SHAPE}" == "r2t" ]]; then
write_summary "synthetic_fixed_work_write_shape_matches_mounted=true"
else
write_summary "synthetic_fixed_work_write_shape_matches_mounted=false"
fi
write_summary "mounted_nvme_phase_counter_reconciliation=true"
write_summary "mounted_client_latency_reconciliation_available=false"
write_summary "architecture_candidate_selected=false"
write_summary "cleanup_status=ok"
write_summary "phase174_mounted_nvme_phase_profile_status=ok"
@@ -0,0 +1,312 @@
#!/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}"
SOURCE_COMMIT="${SW_BLOCK_PHASE174_SOURCE_COMMIT:-$(git -C "${ROOT}" rev-parse HEAD 2>/dev/null || true)}"
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
if [[ -z "${SOURCE_COMMIT}" ]]; then
echo "phase174 source commit is required" >&2
exit 2
fi
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 "source_commit=${SOURCE_COMMIT}"
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 math
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",
"nvme_capsule_receive_parse_ops", "nvme_r2t_collection_ops", "nvme_dispatch_wait_ops",
"nvme_handler_ops", "nvme_completion_queue_wait_ops", "nvme_completion_send_ops",
"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["nvme_server_phase_ns"] > row["client_write_latency_ns"]:
raise SystemExit(f"server phase duration exceeds client duration: {row}")
if row["nvme_client_residual_ns"] != row["client_write_latency_ns"] - row["nvme_server_phase_ns"]:
raise SystemExit(f"client residual 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)
def correlation(rows, field):
xs = [float(row["foreground_ns"]) for row in rows]
ys = [float(row[field]) for row in rows]
x_mean = statistics.mean(xs)
y_mean = statistics.mean(ys)
numerator = sum((x - x_mean) * (y - y_mean) for x, y in zip(xs, ys))
x_norm = math.sqrt(sum((x - x_mean) ** 2 for x in xs))
y_norm = math.sqrt(sum((y - y_mean) ** 2 for y in ys))
if x_norm == 0 or y_norm == 0:
return 0.0
return numerator / (x_norm * y_norm)
four = all_rows(4)
eight = all_rows(8)
four_stable = all(rate_range(4, set_id) <= max_range for set_id in (1, 2)) and rate_range(4) <= max_range
all_shapes_stable = all(
rate_range(writers, set_id) <= max_range
for writers in (1, 4, 8)
for set_id in (1, 2)
) and all(rate_range(writers) <= max_range for writers in (1, 4, 8))
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"
phase_fields = {
"capsule_receive_parse": "nvme_capsule_receive_parse_ns",
"r2t_collection": "nvme_r2t_collection_ns",
"dispatch_wait": "nvme_dispatch_wait_ns",
"handler": "nvme_handler_ns",
"completion_queue_wait": "nvme_completion_queue_wait_ns",
"completion_send": "nvme_completion_send_ns",
"client_residual": "nvme_client_residual_ns",
}
dominant_phase = max(phase_fields, key=lambda name: median_per_op(four, phase_fields[name]))
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",
"nvme_capsule_receive_parse_ns", "nvme_r2t_collection_ns", "nvme_dispatch_wait_ns",
"nvme_handler_ns", "nvme_completion_queue_wait_ns", "nvme_completion_send_ns",
"nvme_server_phase_ns", "nvme_client_residual_ns",
"adapter_write_ns", "primary_write_commit_lock_wait_ns", "primary_wal_encode_ns",
"primary_wal_append_ns", "primary_dirty_map_ns", "foreground_flusher_cycle_ns",
"foreground_flusher_extent_write_ns", "foreground_flusher_extent_sync_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_writers_4_flusher_foreground_correlation={correlation(four, 'foreground_flusher_cycle_ns'):.3f}\n")
out.write(f"nvme_tcp_rf1_writers_8_flusher_cycle_ns_per_op={median_per_op(eight, 'foreground_flusher_cycle_ns'):.3f}\n")
out.write(f"nvme_tcp_rf1_writers_8_flusher_foreground_correlation={correlation(eight, 'foreground_flusher_cycle_ns'):.3f}\n")
out.write(f"nvme_tcp_rf1_dominant_accumulated_boundary={dominant}\n")
out.write(f"nvme_tcp_rf1_dominant_detailed_phase={dominant_phase}\n")
out.write("nvme_tcp_rf1_counter_reconciliation=true\n")
out.write("nvme_tcp_rf1_phase_counter_reconciliation=true\n")
out.write("nvme_tcp_rf1_close_recover_verified=true\n")
out.write(f"nvme_tcp_rf1_four_writer_stability_gate={'pass' if four_stable else 'hold'}\n")
out.write(f"nvme_tcp_rf1_all_shapes_stability_gate={'pass' if all_shapes_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}"