storage: add exact shipped-path attribution gate

This commit is contained in:
pingqiu committed 2026-08-01 00:34:52 -07:00
1 parent 99e746e33c
commit 86222889cd
6 files changed
+760 -6

No files matched your search

+2
View File
@@ -328,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)
}
}
@@ -2,9 +2,12 @@ package storage
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"runtime"
"runtime/pprof"
"sort"
"strconv"
"sync"
@@ -19,6 +22,8 @@ const (
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
@@ -61,9 +66,16 @@ type phase173FixedWorkResult struct {
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"`
@@ -72,19 +84,95 @@ type phase173FixedWorkResult struct {
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"} {
@@ -287,6 +375,16 @@ func runPhase173FixedWork(
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)
@@ -295,6 +393,16 @@ func runPhase173FixedWork(
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()
}
}()
foreground, latencies, err := runPhase173Operations(s, cfg, cfg.APIOperations, 0, payloads, true)
if err != nil {
return phase173FixedWorkResult{}, fmt.Errorf("phase173 foreground: %w", err)
@@ -310,6 +418,12 @@ func runPhase173FixedWork(
return phase173FixedWorkResult{}, fmt.Errorf("phase173 final drain: %w", err)
}
finalDrain := time.Since(drainStart)
if profilesActive {
if err := stopProfiles(); err != nil {
return phase173FixedWorkResult{}, err
}
profilesActive = false
}
writeAfter := s.WriteInstrumentation()
flushAfter := s.FlusherInstrumentation()
@@ -345,6 +459,12 @@ func runPhase173FixedWork(
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
}
@@ -386,9 +506,16 @@ func runPhase173FixedWork(
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,
@@ -397,21 +524,133 @@ func runPhase173FixedWork(
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++ {
@@ -0,0 +1,76 @@
# 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`
- `profile_scope_exact=true`
- `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.
## 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,408 @@
#!/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 "measurement_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 -xz 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 "profile_scope_exact=true"
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}")
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()
for event in ("task-clock", "cycles", "instructions", "cache-misses", "context-switches", "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}")
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"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_ns={plain['wal_append_ns']}",
f"commit_lock_wait_ops={plain['commit_lock_wait_ops']}",
f"commit_lock_wait_ns={plain['commit_lock_wait_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_header_reads={plain['flush_header_reads']}",
f"flush_header_read_ns={plain['flush_header_read_ns']}",
f"flush_record_reads={plain['flush_record_reads']}",
f"flush_record_read_ns={plain['flush_record_read_ns']}",
f"flush_record_decode_ops={plain['flush_record_decode_ops']}",
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",
"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}"