فهرست منبع

test(6400): add accelerated soak and fault seeding

root 3 ماه پیش
والد
کامیت
e04803fad1
4فایلهای تغییر یافته به همراه594 افزوده شده و 0 حذف شده
  1. 11 0
      tests/cocotb/prod2u_6400_v1_cocotb_top.v
  2. 237 0
      tests/cocotb/test_6400_v1_soak.py
  3. 221 0
      tools/run_6400_mutation.py
  4. 125 0
      tools/run_6400_soak.py

+ 11 - 0
tests/cocotb/prod2u_6400_v1_cocotb_top.v

@@ -13,6 +13,7 @@ module prod2u_6400_v1_cocotb_top #(
     input  wire        bmc_rs232_rx,
     output wire        bmc_rs232_tx,
     input  wire        tick_1s_test,
+    input  wire        reset_test,
     output wire [23:0] ptc_pwm_out,
     output wire [3:0]  front_fan_pwm_out,
     output wire [3:0]  rear_fan_pwm_out,
@@ -75,6 +76,16 @@ module prod2u_6400_v1_cocotb_top #(
         force u_dut.ct_response_error = 4'd0;
     end
 
+    // Simulation-only global reset/reconfiguration injection. The production
+    // top intentionally has no software reset pin; forcing its common rst_n
+    // models a device reset while still exercising every real state element.
+    always @(reset_test) begin
+        if (reset_test === 1'b1)
+            force u_dut.rst_n = 1'b0;
+        else
+            release u_dut.rst_n;
+    end
+
     assign rst_n_mon = u_dut.rst_n;
     assign control_state_mon = u_dut.control_state;
     assign bmc_epoch_mon = u_dut.bmc_epoch;

+ 237 - 0
tests/cocotb/test_6400_v1_soak.py

@@ -0,0 +1,237 @@
+"""L11 accelerated randomized full-top soak with deterministic coverage."""
+
+from __future__ import annotations
+
+import json
+import os
+from pathlib import Path
+import random
+
+import cocotb
+from cocotb.triggers import RisingEdge, Timer
+
+from thermal_6400_uart import (
+    BMC_CLKS_PER_BIT,
+    CLOCK_NS,
+    GET_SNAPSHOT,
+    HOST_CLKS_PER_BIT,
+    SET_STIMULUS,
+    SET_STIMULUS_ACK,
+    SET_TARGET,
+    SET_TARGET_ACK,
+    bring_auto,
+    clock_cycles,
+    encode_frame,
+    get_snapshot,
+    host_transaction,
+    initialize,
+    pulse_tick_1s,
+    send_bmc_snapshot,
+    send_uart,
+    wait_for,
+)
+
+
+SEED = int(os.environ.get("PROD2U_SOAK_SEED", "1677779166"))
+ITERATIONS = int(os.environ.get("PROD2U_SOAK_ITERATIONS", "96"))
+
+
+def values(snapshot: dict[str, object], name: str) -> list[int]:
+    value = snapshot[name]
+    assert isinstance(value, list)
+    return [int(item) for item in value]
+
+
+async def wait_control_epoch(dut, previous: int, label: str) -> None:
+    await wait_for(
+        dut,
+        lambda: int(dut.control_epoch_mon.value) != previous,
+        cycles=1200,
+        label=label,
+    )
+
+
+async def send_noise(dut, rng: random.Random) -> None:
+    before_commit = int(dut.target_commit_count_mon.value)
+    before_response = int(dut.host_response_count_mon.value)
+    # A bad-CRC target-shaped frame plus arbitrary bytes must not commit or
+    # produce a response. Let the bounded idle unlock recover the selected port.
+    corrupt = bytearray(encode_frame(SET_TARGET, bytes([rng.randint(55, 75)])))
+    corrupt[-1] ^= 0x80
+    port = "rs232" if rng.randrange(2) == 0 else "ttl"
+    await send_uart(getattr(dut, f"host_{port}_rx"), corrupt, HOST_CLKS_PER_BIT)
+    await send_uart(getattr(dut, f"host_{port}_rx"), bytes(rng.randrange(256) for _ in range(5)), HOST_CLKS_PER_BIT)
+    await clock_cycles(dut, 1400)
+    assert int(dut.target_commit_count_mon.value) == before_commit
+    assert int(dut.host_response_count_mon.value) == before_response
+
+
+async def recover_safe(dut) -> None:
+    for _ in range(4):
+        previous = int(dut.control_epoch_mon.value)
+        await send_bmc_snapshot(dut, [60] * 24)
+        if int(dut.control_state_mon.value) in (4, 5):
+            await wait_control_epoch(dut, previous, "soak recovery control pass")
+    await wait_for(
+        dut,
+        lambda: int(dut.global_fault_mon.value) == 0
+        and int(dut.lane_fault_mask_mon.value) == 0
+        and int(dut.control_state_mon.value) == 4,
+        cycles=1600,
+        label="soak recovery AUTO",
+    )
+
+
+async def validate_snapshot(dut, port: str, counters: dict[str, int]) -> dict[str, object]:
+    snapshot = await get_snapshot(dut, port)
+    assert snapshot["control_state"] in range(7)
+    for name in ("ptc_requested", "ptc_applied", "front_requested", "front_applied", "rear_requested", "rear_applied"):
+        assert all(0 <= value <= 100 for value in values(snapshot, name))
+    if snapshot["global_fault"]:
+        assert values(snapshot, "ptc_applied") == [0] * 24
+        assert values(snapshot, "front_applied") == [100] * 4
+        assert values(snapshot, "rear_applied") == [100] * 4
+    assert int(dut.pwm_deadline_miss_mon.value) == 0
+    counters["get_snapshot"] += 1
+    return snapshot
+
+
+@cocotb.test()
+async def test_accelerated_randomized_system_soak(dut):
+    rng = random.Random(SEED)
+    counters = {
+        "bmc_random": 0,
+        "invalid": 0,
+        "stale": 0,
+        "get_snapshot": 0,
+        "set_target": 0,
+        "repeated_set": 0,
+        "stimulus": 0,
+        "recovery": 0,
+        "epoch_wrap": 0,
+        "uart_noise": 0,
+        "reset": 0,
+        "hard_limit": 0,
+        "state_transitions": 0,
+        "virtual_seconds": 0,
+    }
+    dut.reset_test.value = 0
+    previous_state = 0
+    await bring_auto(dut)
+
+    # Exercise the 16-bit acquisition epoch rollover with real BMC UART frames.
+    dut.u_dut.u_bmc_snapshot.epoch.value = 0xFFFE
+    await send_bmc_snapshot(dut, [60] * 24)
+    assert int(dut.bmc_epoch_mon.value) == 0xFFFF
+    await send_bmc_snapshot(dut, [60] * 24)
+    assert int(dut.bmc_epoch_mon.value) == 0
+    counters["epoch_wrap"] += 1
+
+    for iteration in range(ITERATIONS):
+        action = iteration % 8
+        if action == 0:
+            temperatures: list[int | None] = [rng.randint(54, 75) for _ in range(24)]
+            if iteration % 16 == 0:
+                temperatures[rng.randrange(24)] = None
+                counters["invalid"] += 1
+            previous = int(dut.control_epoch_mon.value)
+            await send_bmc_snapshot(dut, temperatures)
+            await wait_control_epoch(dut, previous, "random BMC control pass")
+            counters["bmc_random"] += 1
+        elif action == 1:
+            port = "rs232" if iteration & 1 else "ttl"
+            target = rng.choice((58, 63, 70, 75))
+            kind, payload = await host_transaction(dut, port, SET_TARGET, bytes([target]))
+            assert (kind, payload) == (SET_TARGET_ACK, b"")
+            kind, payload = await host_transaction(dut, port, SET_TARGET, bytes([target]))
+            assert (kind, payload) == (SET_TARGET_ACK, b"")
+            counters["set_target"] += 2
+            counters["repeated_set"] += 1
+            await recover_safe(dut)
+            counters["recovery"] += 1
+        elif action == 2:
+            await pulse_tick_1s(dut, 3)
+            counters["virtual_seconds"] += 3
+            await wait_for(dut, lambda: int(dut.global_fault_mon.value) == 1, cycles=300, label="random stale clamp")
+            stale = await validate_snapshot(dut, "rs232", counters)
+            assert values(stale, "ptc_applied") == [0] * 24
+            counters["stale"] += 1
+            await recover_safe(dut)
+            counters["recovery"] += 1
+        elif action == 3:
+            await validate_snapshot(dut, "ttl" if iteration & 1 else "rs232", counters)
+        elif action == 4:
+            ptc = [rng.randint(0, 45) for _ in range(24)]
+            front = [rng.randint(20, 70) for _ in range(4)]
+            rear = [rng.randint(20, 70) for _ in range(4)]
+            duration = rng.randint(1, 3)
+            kind, payload = await host_transaction(
+                dut, "rs232", SET_STIMULUS, bytes([duration, *ptc, *front, *rear])
+            )
+            assert (kind, payload) == (SET_STIMULUS_ACK, b"")
+            previous = int(dut.control_epoch_mon.value)
+            await send_bmc_snapshot(dut, [60] * 24)
+            await wait_control_epoch(dut, previous, "stimulus commit")
+            await pulse_tick_1s(dut, duration)
+            counters["virtual_seconds"] += duration
+            assert int(dut.stimulus_active_mon.value) == 0
+            counters["stimulus"] += 1
+        elif action == 5:
+            await send_noise(dut, rng)
+            counters["uart_noise"] += 1
+        elif action == 6:
+            lane = rng.randrange(4)
+            temperatures = [60] * 24
+            temperatures[lane * 6 + rng.randrange(6)] = 77
+            previous = int(dut.control_epoch_mon.value)
+            await send_bmc_snapshot(dut, temperatures)
+            await wait_control_epoch(dut, previous, "hard-limit control pass")
+            assert int(dut.lane_fault_mask_mon.value) & (1 << lane)
+            snap = await validate_snapshot(dut, "ttl", counters)
+            assert values(snap, "ptc_applied")[lane * 6 : lane * 6 + 6] == [0] * 6
+            assert values(snap, "front_applied")[lane] == 100
+            assert values(snap, "rear_applied")[lane] == 100
+            counters["hard_limit"] += 1
+            await recover_safe(dut)
+            counters["recovery"] += 1
+        else:
+            # Two deterministic mid-run global resets/reconfigurations.
+            if iteration in (31, 63):
+                dut.reset_test.value = 1
+                await clock_cycles(dut, 4)
+                dut.reset_test.value = 0
+                await initialize(dut)
+                for _ in range(4):
+                    await send_bmc_snapshot(dut, [60] * 24)
+                await wait_for(dut, lambda: int(dut.control_state_mon.value) == 4, cycles=1200, label="AUTO after reset")
+                counters["reset"] += 1
+            else:
+                await validate_snapshot(dut, "rs232", counters)
+
+        state = int(dut.control_state_mon.value)
+        if state != previous_state:
+            counters["state_transitions"] += 1
+            previous_state = state
+        assert state in range(7)
+        assert int(dut.pwm_deadline_miss_mon.value) == 0
+
+    final_snapshot = await validate_snapshot(dut, "ttl", counters)
+    assert final_snapshot["control_epoch"] >= 1
+    required_nonzero = (
+        "bmc_random", "invalid", "stale", "get_snapshot", "set_target",
+        "repeated_set", "stimulus", "recovery", "epoch_wrap", "uart_noise",
+        "reset", "hard_limit", "state_transitions", "virtual_seconds",
+    )
+    assert all(counters[name] > 0 for name in required_nonzero), counters
+    result = {
+        "schema": "prod2u-6400-soak-result-v1",
+        "seed": SEED,
+        "iterations": ITERATIONS,
+        "counters": counters,
+        "final_control_epoch": int(final_snapshot["control_epoch"]),
+        "final_bmc_epoch": int(final_snapshot["bmc_epoch"]),
+        "status": "PASS",
+    }
+    result_path = Path(os.environ["PROD2U_SOAK_RESULT"])
+    result_path.write_text(json.dumps(result, indent=2, sort_keys=True) + "\n", encoding="utf-8")
+    cocotb.log.info("L11_SOAK_PASS %s", json.dumps(result, sort_keys=True))

+ 221 - 0
tools/run_6400_mutation.py

@@ -0,0 +1,221 @@
+#!/usr/bin/env python3
+"""L12 bounded fault seeding in disposable clones of the clean source tree."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from datetime import datetime, timezone
+import hashlib
+import json
+import os
+from pathlib import Path
+import re
+import subprocess
+import tempfile
+import time
+
+
+ROOT = Path(__file__).resolve().parents[1]
+
+
+@dataclass(frozen=True)
+class Mutation:
+    name: str
+    path: str
+    old: str
+    new: str
+    gate: str
+
+
+GATES = {
+    "host": ["python3", "tests/cocotb/run_6400_v1_integration.py", "host_protocol"],
+    "control": ["python3", "tests/cocotb/run_6400_v1_integration.py", "control"],
+    "bmc": ["python3", "tests/cocotb/run_6400_bmc_fuzz.py"],
+    "pwm": ["python3", "tools/run_6400_v1.py", "pwm"],
+}
+MUTATIONS = (
+    Mutation(
+        "crc_decision_inverted",
+        "src/common/frame_rx.v",
+        "if ({byte_data, received_crc_low} == crc_value) begin",
+        "if ({byte_data, received_crc_low} != crc_value) begin",
+        "host",
+    ),
+    Mutation(
+        "hard_safety_comparator_changed",
+        "src/control/thermal_control_core.v",
+        "end else if (sample_temperature >= HARD_LIMIT) begin",
+        "end else if (sample_temperature > HARD_LIMIT) begin",
+        "control",
+    ),
+    Mutation(
+        "bank_pointer_flip_suppressed",
+        "src/acquisition/bmc_ascii_snapshot.v",
+        "active_bank <= ~active_bank;",
+        "active_bank <= active_bank;",
+        "bmc",
+    ),
+    Mutation(
+        "pwm_deadline_shortened",
+        "src/actuator/pwm_bitmap_engine.v",
+        "parameter integer PHASE_CLKS = 500,",
+        "parameter integer PHASE_CLKS = 32,",
+        "pwm",
+    ),
+    Mutation(
+        "stale_threshold_off_by_one",
+        "src/acquisition/bmc_ascii_snapshot.v",
+        "assign stale = (age_seconds >= STALE_SECONDS[15:0]);",
+        "assign stale = (age_seconds > STALE_SECONDS[15:0]);",
+        "control",
+    ),
+    Mutation(
+        "invalid_mask_bit_shifted",
+        "src/acquisition/bmc_ascii_snapshot.v",
+        "valid1[byte_count[5:1]] <= 1'b0;",
+        "valid1[byte_count[5:1] ^ 5'd1] <= 1'b0;",
+        "control",
+    ),
+)
+
+
+def sha256(path: Path) -> str:
+    return hashlib.sha256(path.read_bytes()).hexdigest()
+
+
+def git(*args: str, cwd: Path = ROOT) -> str:
+    return subprocess.check_output(["git", *args], cwd=cwd, text=True).strip()
+
+
+def run(command: list[str], cwd: Path, log: Path, timeout: int = 600) -> dict[str, object]:
+    started = time.monotonic()
+    env = os.environ.copy()
+    env["PYTHONDONTWRITEBYTECODE"] = "1"
+    with log.open("wb") as stream:
+        completed = subprocess.run(
+            command,
+            cwd=cwd,
+            env=env,
+            stdout=stream,
+            stderr=subprocess.STDOUT,
+            timeout=timeout,
+            check=False,
+        )
+    text = log.read_text(encoding="utf-8", errors="replace")
+    return {
+        "command": command,
+        "exit_code": completed.returncode,
+        "duration_seconds": round(time.monotonic() - started, 3),
+        "log": str(log),
+        "log_sha256": sha256(log),
+        "failure_signature": bool(re.search(r"(FAIL|AssertionError|FATAL|failed|error)", text, re.IGNORECASE)),
+        "tail": "\n".join(text.splitlines()[-40:]),
+    }
+
+
+def clone_at(commit: str, destination: Path) -> None:
+    subprocess.run(["git", "clone", "--quiet", "--shared", "--no-checkout", str(ROOT), str(destination)], check=True)
+    subprocess.run(["git", "checkout", "--quiet", "--detach", commit], cwd=destination, check=True)
+
+
+def apply_mutation(root: Path, mutation: Mutation) -> dict[str, str]:
+    path = root / mutation.path
+    before = path.read_text(encoding="utf-8")
+    count = before.count(mutation.old)
+    if count != 1:
+        raise RuntimeError(f"{mutation.name}: expected one mutation site, found {count}")
+    after = before.replace(mutation.old, mutation.new, 1)
+    path.write_text(after, encoding="utf-8")
+    return {
+        "before_sha256": hashlib.sha256(before.encode()).hexdigest(),
+        "after_sha256": hashlib.sha256(after.encode()).hexdigest(),
+        "diff": git("diff", "--", mutation.path, cwd=root),
+    }
+
+
+def main() -> int:
+    dirty = git("status", "--porcelain")
+    if dirty:
+        raise SystemExit(f"mutation gate requires a clean source worktree:\n{dirty}")
+    commit = git("rev-parse", "HEAD")
+    tree = git("rev-parse", "HEAD^{tree}")
+    stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
+    run_id = f"6400-mutation-{stamp}-{commit[:8]}"
+    run_root = Path(os.environ.get("PROD2U_MUTATION_RUN_ROOT", "/data/prod2u/cpld-runs")) / run_id
+    run_root.mkdir(parents=True, exist_ok=False)
+    records: dict[str, object] = {}
+    status = "PASS"
+
+    # Establish that every detector passes on the unmodified commit before
+    # interpreting a mutant failure as useful evidence.
+    with tempfile.TemporaryDirectory(prefix="prod2u-6400-mutation-baseline-") as directory:
+        baseline_root = Path(directory) / "source"
+        clone_at(commit, baseline_root)
+        baselines: dict[str, object] = {}
+        for gate, command in GATES.items():
+            record = run(command, baseline_root, run_root / f"baseline-{gate}.log")
+            baselines[gate] = record
+            print(f"baseline {gate}: exit={record['exit_code']} duration_s={record['duration_seconds']}", flush=True)
+            if record["exit_code"] != 0:
+                status = "FAIL"
+        records["baselines"] = baselines
+
+    mutation_records: list[dict[str, object]] = []
+    if status == "PASS":
+        for mutation in MUTATIONS:
+            with tempfile.TemporaryDirectory(prefix=f"prod2u-6400-{mutation.name}-") as directory:
+                clone = Path(directory) / "source"
+                clone_at(commit, clone)
+                patch = apply_mutation(clone, mutation)
+                record = run(GATES[mutation.gate], clone, run_root / f"mutation-{mutation.name}.log")
+                detected = bool(record["exit_code"] != 0 and record["failure_signature"])
+                item = {
+                    "name": mutation.name,
+                    "path": mutation.path,
+                    "gate": mutation.gate,
+                    "detected": detected,
+                    "production_tree_unchanged": not bool(git("status", "--porcelain")),
+                    "patch": patch,
+                    "run": record,
+                }
+                mutation_records.append(item)
+                print(
+                    f"mutation {mutation.name}: detected={detected} "
+                    f"exit={record['exit_code']} duration_s={record['duration_seconds']}",
+                    flush=True,
+                )
+                if not detected:
+                    status = "FAIL"
+    records["mutations"] = mutation_records
+    if git("status", "--porcelain"):
+        status = "FAIL"
+
+    receipt = {
+        "schema": "prod2u-6400-mutation-receipt-v1",
+        "run_id": run_id,
+        "status": status,
+        "generated_at": datetime.now(timezone.utc).isoformat(),
+        "commit": commit,
+        "tree": tree,
+        "clean_before": not bool(dirty),
+        "clean_after": not bool(git("status", "--porcelain")),
+        "command": "python3 tools/run_6400_mutation.py",
+        "required_mutations": len(MUTATIONS),
+        "detected_mutations": sum(bool(item["detected"]) for item in mutation_records),
+        "container_image_id": os.environ.get("PROD2U_CONTAINER_IMAGE_ID"),
+        "container_digest": os.environ.get("PROD2U_CONTAINER_DIGEST"),
+        "hardware": "NOT RUN",
+        **records,
+    }
+    receipt_path = run_root / "mutation-receipt.json"
+    receipt_path.write_text(json.dumps(receipt, indent=2, sort_keys=True) + "\n", encoding="utf-8")
+    print(receipt_path)
+    if status == "PASS":
+        print(f"L12_MUTATION_PASS detected={len(MUTATIONS)}/{len(MUTATIONS)}")
+        return 0
+    print(f"L12_MUTATION_FAIL detected={receipt['detected_mutations']}/{len(MUTATIONS)}")
+    return 1
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())

+ 125 - 0
tools/run_6400_soak.py

@@ -0,0 +1,125 @@
+#!/usr/bin/env python3
+"""Run L11 deterministic randomized soak and emit a source-bound receipt."""
+
+from __future__ import annotations
+
+from datetime import datetime, timezone
+import hashlib
+import json
+import os
+from pathlib import Path
+import subprocess
+import tempfile
+import time
+import xml.etree.ElementTree as ET
+
+try:
+    from cocotb_tools.runner import get_runner
+except ModuleNotFoundError:
+    from cocotb.runner import get_runner
+
+
+ROOT = Path(__file__).resolve().parents[1]
+TEST_DIR = ROOT / "tests/cocotb"
+CLOSURE = ROOT / "products/6400-control/source-closure.json"
+WRAPPER = TEST_DIR / "prod2u_6400_v1_cocotb_top.v"
+
+
+def sha256(path: Path) -> str:
+    return hashlib.sha256(path.read_bytes()).hexdigest()
+
+
+def git(*args: str) -> str:
+    return subprocess.check_output(["git", *args], cwd=ROOT, text=True).strip()
+
+
+def main() -> int:
+    dirty = git("status", "--porcelain")
+    if dirty:
+        raise SystemExit(f"soak requires a clean source worktree:\n{dirty}")
+    commit = git("rev-parse", "HEAD")
+    tree = git("rev-parse", "HEAD^{tree}")
+    closure = json.loads(CLOSURE.read_text(encoding="utf-8"))
+    sources = [ROOT / item for item in closure["sources"] if item.endswith(".v")]
+    input_paths = [CLOSURE, WRAPPER, TEST_DIR / "thermal_6400_uart.py", TEST_DIR / "test_6400_v1_soak.py", *sources]
+    inputs = {str(path.relative_to(ROOT)): sha256(path) for path in input_paths}
+    source_hash = hashlib.sha256(json.dumps(inputs, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
+    stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
+    run_id = f"6400-soak-{stamp}-{commit[:8]}"
+    run_root = Path(os.environ.get("PROD2U_SOAK_RUN_ROOT", "/data/prod2u/cpld-runs")) / run_id
+    run_root.mkdir(parents=True, exist_ok=False)
+    result_json = run_root / "soak-result.json"
+    results_xml = run_root / "results.xml"
+    seed = int(os.environ.get("PROD2U_SOAK_SEED", "1677779166"))
+    iterations = int(os.environ.get("PROD2U_SOAK_ITERATIONS", "96"))
+    runner = get_runner("icarus")
+    started = time.monotonic()
+    status = "FAIL"
+    failure = None
+    try:
+        runner.build(
+            sources=[*sources, WRAPPER],
+            hdl_toplevel="prod2u_6400_v1_cocotb_top",
+            build_dir=run_root / "build",
+            build_args=["-g2012", "-I", str(ROOT)],
+            parameters={"ENABLE_STIMULUS": 1},
+            always=True,
+        )
+        result_path = Path(runner.test(
+            hdl_toplevel="prod2u_6400_v1_cocotb_top",
+            test_module="test_6400_v1_soak",
+            test_dir=TEST_DIR,
+            build_dir=run_root / "build",
+            results_xml=str(results_xml),
+            extra_env={
+                "PROD2U_SOAK_RESULT": str(result_json),
+                "PROD2U_SOAK_SEED": str(seed),
+                "PROD2U_SOAK_ITERATIONS": str(iterations),
+                "PYTHONPATH": str(TEST_DIR),
+            },
+        ))
+        xml = ET.parse(result_path).getroot()
+        cases = xml.findall(".//testcase")
+        failures = xml.findall(".//failure") + xml.findall(".//error")
+        skipped = xml.findall(".//skipped")
+        if len(cases) != 1 or failures or skipped or not result_json.is_file():
+            raise RuntimeError(f"incomplete soak cases={len(cases)} failures={len(failures)} skipped={len(skipped)}")
+        status = "PASS"
+    except Exception as exc:  # receipt must survive a failed test
+        failure = f"{type(exc).__name__}: {exc}"
+    duration = round(time.monotonic() - started, 3)
+    payload = json.loads(result_json.read_text(encoding="utf-8")) if result_json.is_file() else None
+    receipt = {
+        "schema": "prod2u-6400-soak-receipt-v1",
+        "run_id": run_id,
+        "status": status,
+        "generated_at": datetime.now(timezone.utc).isoformat(),
+        "commit": commit,
+        "tree": tree,
+        "clean": not bool(dirty),
+        "command": "python3 tools/run_6400_soak.py",
+        "seed": seed,
+        "iterations": iterations,
+        "duration_seconds": duration,
+        "source_manifest_sha256": source_hash,
+        "inputs": inputs,
+        "container_image_id": os.environ.get("PROD2U_CONTAINER_IMAGE_ID"),
+        "container_digest": os.environ.get("PROD2U_CONTAINER_DIGEST"),
+        "result": payload,
+        "results_xml": str(results_xml) if results_xml.is_file() else None,
+        "results_xml_sha256": sha256(results_xml) if results_xml.is_file() else None,
+        "failure": failure,
+        "hardware": "NOT RUN",
+    }
+    receipt_path = run_root / "soak-receipt.json"
+    receipt_path.write_text(json.dumps(receipt, indent=2, sort_keys=True) + "\n", encoding="utf-8")
+    print(receipt_path)
+    if status == "PASS":
+        print(f"L11_SOAK_PASS iterations={iterations} seed={seed} duration_s={duration}")
+        return 0
+    print(f"L11_SOAK_FAIL {failure}")
+    return 1
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())