From bb7bd66fa1f1c072b39b73354c5787fcc8a3f1b3 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 31 Jul 2026 23:41:19 -0700 Subject: [PATCH] storage: add deterministic fixed-work baseline gate --- .../core/storage/walstore_fixed_work_test.go | 475 ++++++++++++++++++ .../phase173-d1-fixed-work-baseline-qa.md | 56 +++ .../run-phase173-fixed-work-baseline-gate.sh | 179 +++++++ 3 files changed, 710 insertions(+) create mode 100644 seaweed-block/core/storage/walstore_fixed_work_test.go create mode 100644 seaweed-block/internal/docs/qa-assignments/phase173-d1-fixed-work-baseline-qa.md create mode 100755 seaweed-block/scripts/run-phase173-fixed-work-baseline-gate.sh diff --git a/seaweed-block/core/storage/walstore_fixed_work_test.go b/seaweed-block/core/storage/walstore_fixed_work_test.go new file mode 100644 index 0000000000..7f41874470 --- /dev/null +++ b/seaweed-block/core/storage/walstore_fixed_work_test.go @@ -0,0 +1,475 @@ +package storage + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "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" + + phase173FixedWorkBlockSize = 4096 + phase173FixedWorkNumBlocks = 32768 + 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"` + 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"` + 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"` + 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"` + WALEncodeOps uint64 `json:"wal_encode_ops"` + WALChecksumOps uint64 `json:"wal_checksum_ops"` + WALAppendOps uint64 `json:"wal_append_ops"` + WALWriteAtCalls uint64 `json:"wal_writeat_calls"` + WALWriteAtBytes uint64 `json:"wal_writeat_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"` + DirtyMapUpdateNanos uint64 `json:"dirty_map_update_ns"` + FlushCycles uint64 `json:"flush_cycles"` + FlushRecordReads uint64 `json:"flush_record_reads"` + FlushRecordReadBytes uint64 `json:"flush_record_read_bytes"` + ExtentWriteOps uint64 `json:"extent_write_ops"` + ExtentWriteBytes uint64 `json:"extent_write_bytes"` + ExtentSyncOps uint64 `json:"extent_sync_ops"` + CheckpointWriteOps uint64 `json:"checkpoint_write_ops"` + CheckpointSyncOps uint64 `json:"checkpoint_sync_ops"` + ValidationFailures uint64 `json:"validation_failures"` + CorrectnessSamples int `json:"correctness_samples"` +} + +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() < 8000 || cfg.APILogicalBlocks() > 8192 { + t.Fatalf("shape=%s logical blocks=%d want [8000,8192]", shape, cfg.APILogicalBlocks()) + } + if cfg.WarmupLogicalBlocks() < 500 || cfg.WarmupLogicalBlocks() > 512 { + t.Fatalf("shape=%s warmup logical blocks=%d want [500,512]", 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(phase173FixedWorkStoreEnv)) + 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 = 8192 + cfg.WarmupAPIOps = 512 + case "batch_16": + cfg.APIOperations = 512 + cfg.WarmupAPIOps = 32 + case "mounted_mixed": + // 320 fixed cycles of 4K, 16K, 64K, and 16K requests. + cfg.APIOperations = 1280 + cfg.WarmupAPIOps = 80 + 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, storeDir string) (phase173FixedWorkResult, error) { + t.Helper() + if storeDir == "" { + storeDir = t.TempDir() + } + 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, runID)) + if err := os.Remove(storePath); err != nil && !os.IsNotExist(err) { + return phase173FixedWorkResult{}, err + } + s, err := CreateWALStore(storePath, phase173FixedWorkNumBlocks, phase173FixedWorkBlockSize) + if err != nil { + return phase173FixedWorkResult{}, err + } + closed := false + defer func() { + if !closed { + _ = s.Close() + } + _ = 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) + } + s.flusher.Notify() + if err := waitPhase173Drained(s, warmupLSN, 5*time.Second); err != nil { + return phase173FixedWorkResult{}, fmt.Errorf("phase173 warmup drain: %w", err) + } + + writeBefore := s.WriteInstrumentation() + flushBefore := s.FlusherInstrumentation() + syncBefore := s.syncs.Load() + 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) + + 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) + } + if writeAtCalls := writeAfter.WALAppendWriteAtCalls - writeBefore.WALAppendWriteAtCalls; writeAtCalls != appendOps { + return phase173FixedWorkResult{}, fmt.Errorf("phase173 WAL writeat calls=%d want append ops=%d", writeAtCalls, appendOps) + } + 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 err := s.Close(); err != nil { + return phase173FixedWorkResult{}, err + } + closed = true + 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, + 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(), + 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, + SyncedLSN: syncedLSN, + CheckpointLSN: checkpointLSN, + HeadLSN: headLSN, + DirtyEntries: dirtyEntries, + WALCopyOps: writeAfter.WALCopyOps - writeBefore.WALCopyOps, + WALEncodeOps: writeAfter.WALEncodeOps - writeBefore.WALEncodeOps, + WALChecksumOps: writeAfter.WALChecksumOps - writeBefore.WALChecksumOps, + WALAppendOps: writeAfter.WALAppendOps - writeBefore.WALAppendOps, + WALWriteAtCalls: writeAfter.WALAppendWriteAtCalls - writeBefore.WALAppendWriteAtCalls, + WALWriteAtBytes: writeAfter.WALAppendWriteAtBytes - writeBefore.WALAppendWriteAtBytes, + WALAppendNanos: writeAfter.WALAppendDurationNanos - writeBefore.WALAppendDurationNanos, + WALAppendLockWaitNanos: writeAfter.WALAppendLockWaitNanos - writeBefore.WALAppendLockWaitNanos, + CommitLockWaitOps: writeAfter.WriteCommitLockWaitOps - writeBefore.WriteCommitLockWaitOps, + CommitLockWaitNanos: writeAfter.WriteCommitLockWaitNanos - writeBefore.WriteCommitLockWaitNanos, + DirtyMapUpdateNanos: writeAfter.DirtyMapUpdateDurationNanos - writeBefore.DirtyMapUpdateDurationNanos, + FlushCycles: flushAfter.CyclesStarted - flushBefore.CyclesStarted, + FlushRecordReads: flushAfter.WALRecordReadOps - flushBefore.WALRecordReadOps, + FlushRecordReadBytes: flushAfter.WALRecordReadBytes - flushBefore.WALRecordReadBytes, + ExtentWriteOps: flushAfter.ExtentWriteOps - flushBefore.ExtentWriteOps, + ExtentWriteBytes: flushAfter.ExtentWriteBytes - flushBefore.ExtentWriteBytes, + ExtentSyncOps: flushAfter.ExtentSyncOps - flushBefore.ExtentSyncOps, + CheckpointWriteOps: flushAfter.CheckpointMetadataWriteOps - flushBefore.CheckpointMetadataWriteOps, + CheckpointSyncOps: flushAfter.CheckpointMetadataSyncOps - flushBefore.CheckpointMetadataSyncOps, + ValidationFailures: flushAfter.ValidationFailures - flushBefore.ValidationFailures, + CorrectnessSamples: correctnessSamples, + } + return result, 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 waitPhase173Drained(s *WALStore, syncedLSN uint64, timeout time.Duration) error { + deadline := time.Now().Add(timeout) + for time.Now().Before(deadline) { + _, _, headLSN := s.Boundaries() + if s.dm.len() == 0 && s.CheckpointLSN() == syncedLSN && headLSN == syncedLSN { + return nil + } + time.Sleep(10 * time.Millisecond) + } + _, _, headLSN := s.Boundaries() + return fmt.Errorf("timeout dirty=%d checkpoint=%d head=%d synced=%d", s.dm.len(), s.CheckpointLSN(), headLSN, syncedLSN) +} + +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) +} diff --git a/seaweed-block/internal/docs/qa-assignments/phase173-d1-fixed-work-baseline-qa.md b/seaweed-block/internal/docs/qa-assignments/phase173-d1-fixed-work-baseline-qa.md new file mode 100644 index 0000000000..e08373d0eb --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase173-d1-fixed-work-baseline-qa.md @@ -0,0 +1,56 @@ +# 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=160` +- `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` +- 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 +- 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. + +## Verdict + +- `PASS`: all required evidence is present and both independent five-run + four-writer sets remain within the predeclared range. +- `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. diff --git a/seaweed-block/scripts/run-phase173-fixed-work-baseline-gate.sh b/seaweed-block/scripts/run-phase173-fixed-work-baseline-gate.sh new file mode 100755 index 0000000000..ac66e7b6ba --- /dev/null +++ b/seaweed-block/scripts/run-phase173-fixed-work-baseline-gate.sh @@ -0,0 +1,179 @@ +#!/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=(sequential_4k scattered_4k batch_16 mounted_mixed) +WRITERS=(1 2 4 8) +SETS=2 +RUNS=5 +MAX_RANGE="1.25" + +mkdir -p "${ARTIFACT_DIR}" "${STORE_DIR}" "${ARTIFACT_DIR}/environment" "${ARTIFACT_DIR}/logs" +: >"${SUMMARY}" +: >"${RESULTS}" + +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 "runs_per_matrix_point=${RUNS}" +write_summary "four_writer_max_min_limit=${MAX_RANGE}" +write_summary "flusher_interval_ms=100" +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" + +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 + for shape in "${SHAPES[@]}"; do + for writers in "${WRITERS[@]}"; do + for run_id in $(seq 1 "${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_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}" + 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 * runs * len(shapes) * len(writers_values) +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 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"] or row["wal_writeat_calls"] != row["wal_append_ops"]: + raise SystemExit(f"API/WAL physical append 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}") + +summary = [] +gate_ok = True +for shape in shapes: + for writers in writers_values: + group = grouped[(shape, writers)] + if len(group) != sets * runs: + raise SystemExit(f"shape={shape} writers={writers} rows={len(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 + +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}"