Kaynağa Gözat

replace legacy PID soak with manual deterministic soak

高宇轩 3 ay önce
ebeveyn
işleme
dc7445d9da

tests/cocotb/test_6400_pi_differential.py → docs/historical/pid-retired/cocotb/test_6400_pi_differential.py


tests/cocotb/test_6400_v1_control_integration.py → docs/historical/pid-retired/cocotb/test_6400_v1_control_integration.py


tests/cocotb/test_6400_v1_host_protocol_integration.py → docs/historical/pid-retired/cocotb/test_6400_v1_host_protocol_integration.py


tests/cocotb/test_6400_v1_soak.py → docs/historical/pid-retired/cocotb/test_6400_v1_soak.py


tests/cocotb/thermal_6400_uart.py → docs/historical/pid-retired/cocotb/thermal_6400_uart.py


tests/cocotb/thermal_control_core_cocotb_top.v → docs/historical/pid-retired/cocotb/thermal_control_core_cocotb_top.v


tests/formal/6400_core_owner_properties_formal.v → docs/historical/pid-retired/formal/6400_core_owner_properties_formal.v


tests/formal/6400_host_command_properties_formal.v → docs/historical/pid-retired/formal/6400_host_command_properties_formal.v


tests/formal/6400_set_all_commit_properties_formal.v → docs/historical/pid-retired/formal/6400_set_all_commit_properties_formal.v


tests/formal/6400_snapshot_properties_formal.v → docs/historical/pid-retired/formal/6400_snapshot_properties_formal.v


tests/formal/6400_snapshot_transport_properties_formal.v → docs/historical/pid-retired/formal/6400_snapshot_transport_properties_formal.v


tests/sim/thermal_control_core_tb.v → docs/historical/pid-retired/sim/thermal_control_core_tb.v


tests/sim/thermal_control_hard_race_tb.v → docs/historical/pid-retired/sim/thermal_control_hard_race_tb.v


tools/encode_6400_hex.py → docs/historical/pid-retired/tools/encode_6400_hex.py


tools/generate_6400_v1.py → docs/historical/pid-retired/tools/generate_6400_v1.py


+ 2 - 0
products/6400-front-rear/analysis-replay-closure.json

@@ -19,12 +19,14 @@
     "tools/package_6400_canonical.py",
     "tools/package_6400_canonical.py",
     "tools/package_target.py",
     "tools/package_target.py",
     "tools/run_6400_formal.py",
     "tools/run_6400_formal.py",
+    "tools/run_6400_soak.py",
     "tools/run_6400_td.py",
     "tools/run_6400_td.py",
     "tools/target_registry.py",
     "tools/target_registry.py",
     "tests/host_i2c_register_bank_tb.v",
     "tests/host_i2c_register_bank_tb.v",
     "tests/host_i2c_register_slave_tb.v",
     "tests/host_i2c_register_slave_tb.v",
     "tests/host_i2c_register_read_tb.v",
     "tests/host_i2c_register_read_tb.v",
     "tests/host_i2c_register_seq_read_tb.v",
     "tests/host_i2c_register_seq_read_tb.v",
+    "tests/manual_6400_soak.py",
     "tests/sim/frame_rx_tb.v",
     "tests/sim/frame_rx_tb.v",
     "tests/sim/thermal_host_command_v2_tb.v",
     "tests/sim/thermal_host_command_v2_tb.v",
     "tests/formal/6400-properties.json",
     "tests/formal/6400-properties.json",

+ 110 - 0
tests/manual_6400_soak.py

@@ -0,0 +1,110 @@
+#!/usr/bin/env python3
+"""Deterministic, simulator-free 6400 manual protocol and watchdog soak."""
+from __future__ import annotations
+import json
+import os
+import random
+from pathlib import Path
+
+SAFE = bytes([0] * 24 + [20] * 8)
+STATUS_OK, STATUS_UNSUPPORTED, STATUS_BAD_LENGTH, STATUS_BAD_VALUE, STATUS_SAFETY_LOCKED = range(5)
+
+def crc16(data: bytes) -> int:
+    crc = 0xFFFF
+    for byte in data:
+        crc ^= byte << 8
+        for _ in range(8):
+            crc = ((crc << 1) ^ 0x1021) & 0xFFFF if crc & 0x8000 else (crc << 1) & 0xFFFF
+    return crc
+
+def frame(kind: int, payload: bytes = b"") -> bytes:
+    body = bytes((kind, len(payload))) + payload
+    return b"\xA5\x5A" + body + crc16(body).to_bytes(2, "little")
+
+def decode(raw: bytes) -> tuple[int, bytes]:
+    if len(raw) < 6 or raw[:2] != b"\xA5\x5A" or len(raw) != raw[3] + 6:
+        raise AssertionError("invalid frame")
+    if int.from_bytes(raw[-2:], "little") != crc16(raw[2:-2]):
+        raise AssertionError("CRC mismatch")
+    return raw[2], raw[4:-2]
+
+class Model:
+    def __init__(self) -> None:
+        self.staging = bytearray(32)
+        self.mask = 0
+        self.active = bytearray(SAFE)
+        self.manual = False
+        self.watchdog = 0
+        self.hard = False
+        self.epoch = 0
+
+    def stage(self, index: int, value: int) -> None:
+        self.staging[index] = value
+        self.mask |= 1 << index
+
+    def command(self, kind: int) -> tuple[int, int]:
+        if kind != 0x01:
+            return STATUS_UNSUPPORTED, 0
+        missing = (~self.mask) & ((1 << 32) - 1)
+        if missing:
+            return STATUS_BAD_LENGTH, (missing & -missing).bit_length() - 1
+        for index, value in enumerate(self.staging):
+            if value > 100:
+                return STATUS_BAD_VALUE, index
+        if self.hard:
+            return STATUS_SAFETY_LOCKED, 0
+        self.active[:] = self.staging
+        self.mask = 0
+        self.manual = True
+        self.watchdog = 30
+        self.epoch += 1
+        return STATUS_OK, 0
+
+    def tick(self, seconds: int = 1) -> None:
+        self.watchdog = max(0, self.watchdog - seconds)
+        if self.watchdog == 0 and self.manual:
+            self.active[:] = SAFE
+            self.manual = False
+
+def main() -> int:
+    iterations = int(os.environ.get("PROD2U_SOAK_ITERATIONS", "2048"))
+    seed = int(os.environ.get("PROD2U_SOAK_SEED", "64006400"))
+    rng = random.Random(seed)
+    model = Model()
+    commits = invalids = timeouts = 0
+    for step in range(iterations):
+        values = bytes(rng.randrange(101) for _ in range(32))
+        raw = frame(0x01, values)
+        kind, payload = decode(raw)
+        assert kind == 0x01 and payload == values
+        for index, value in enumerate(values):
+            model.stage(index, value)
+        status, detail = model.command(0x01)
+        assert (status, detail) == (STATUS_OK, 0)
+        assert bytes(model.active) == values and model.manual and model.watchdog == 30
+        commits += 1
+        if step % 4 == 0:
+            model.stage(7, 101)
+            old = bytes(model.active)
+            status, detail = model.command(0x01)
+            assert (status, detail) == (STATUS_BAD_VALUE, 7)
+            assert bytes(model.active) == old and model.watchdog == 30
+            invalids += 1
+            model.stage(7, values[7])
+            model.mask = (1 << 32) - 1
+        status, detail = model.command(0x04)
+        assert (status, detail) == (STATUS_UNSUPPORTED, 0)
+        assert model.watchdog == 30
+        model.tick(30)
+        assert bytes(model.active) == SAFE and not model.manual and model.watchdog == 0
+        timeouts += 1
+    assert SAFE == bytes([0] * 24 + [20] * 8)
+    result = {"status": "PASS", "seed": seed, "iterations": iterations, "commits": commits, "invalid_values": invalids, "timeouts": timeouts, "safe_vector": SAFE.hex()}
+    output = os.environ.get("PROD2U_SOAK_RESULT")
+    if output:
+        Path(output).write_text(json.dumps(result, indent=2, sort_keys=True) + "\n", encoding="utf-8")
+    print("MANUAL_SOAK_PASS", json.dumps(result, sort_keys=True))
+    return 0
+
+if __name__ == "__main__":
+    raise SystemExit(main())

+ 1 - 0
tools/package_6400_canonical.py

@@ -116,6 +116,7 @@ def base_paths() -> list[str]:
         "tools/doctor_linux.py", "tools/check_6400_closures.py", "tools/generate_target.py",
         "tools/doctor_linux.py", "tools/check_6400_closures.py", "tools/generate_target.py",
         "tools/resource_scheduler.py",
         "tools/resource_scheduler.py",
         "tools/generate_6400_manual.py", "tools/target_registry.py", "tools/run_6400_td.py",
         "tools/generate_6400_manual.py", "tools/target_registry.py", "tools/run_6400_td.py",
+        "tools/run_6400_soak.py",
         "tools/package_target.py", "tools/package_6400_canonical.py",
         "tools/package_target.py", "tools/package_6400_canonical.py",
         "tools/overlay_6400_packages.py",
         "tools/overlay_6400_packages.py",
         "tests/unit/test_6400_closure_separation.py",
         "tests/unit/test_6400_closure_separation.py",

+ 30 - 92
tools/run_6400_soak.py

@@ -1,125 +1,63 @@
 #!/usr/bin/env python3
 #!/usr/bin/env python3
-"""Run L11 deterministic randomized soak and emit a source-bound receipt."""
-
+"""Run the active simulator-free 6400 manual soak and emit a receipt."""
 from __future__ import annotations
 from __future__ import annotations
-
-from datetime import datetime, timezone
 import hashlib
 import hashlib
 import json
 import json
 import os
 import os
 from pathlib import Path
 from pathlib import Path
 import subprocess
 import subprocess
-import tempfile
+import sys
 import time
 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]
 ROOT = Path(__file__).resolve().parents[1]
-TEST_DIR = ROOT / "tests/cocotb"
 CLOSURE = ROOT / "products/6400-front-rear/source-closure.json"
 CLOSURE = ROOT / "products/6400-front-rear/source-closure.json"
-WRAPPER = TEST_DIR / "prod2u_6400_v1_cocotb_top.v"
-
 
 
 def sha256(path: Path) -> str:
 def sha256(path: Path) -> str:
-    return hashlib.sha256(path.read_bytes()).hexdigest()
-
+    digest = hashlib.sha256()
+    with path.open("rb") as stream:
+        for block in iter(lambda: stream.read(1024 * 1024), b""):
+            digest.update(block)
+    return digest.hexdigest()
 
 
 def git(*args: str) -> str:
 def git(*args: str) -> str:
     return subprocess.check_output(["git", *args], cwd=ROOT, text=True).strip()
     return subprocess.check_output(["git", *args], cwd=ROOT, text=True).strip()
 
 
-
 def main() -> int:
 def main() -> int:
     dirty = git("status", "--porcelain")
     dirty = git("status", "--porcelain")
     if dirty:
     if dirty:
-        raise SystemExit(f"soak requires a clean source worktree:\n{dirty}")
-    commit = git("rev-parse", "HEAD")
-    tree = git("rev-parse", "HEAD^{tree}")
+        raise SystemExit("soak requires a clean source worktree")
+    commit, tree = git("rev-parse", "HEAD"), git("rev-parse", "HEAD^{tree}")
     closure = json.loads(CLOSURE.read_text(encoding="utf-8"))
     closure = json.loads(CLOSURE.read_text(encoding="utf-8"))
     sources = [ROOT / item for item in closure["sources"] if item.endswith(".v")]
     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
+    test = ROOT / "tests/manual_6400_soak.py"
+    inputs = [CLOSURE, test, *sources]
+    source_manifest = hashlib.sha256(
+        json.dumps({str(p.relative_to(ROOT)): sha256(p) for p in inputs}, sort_keys=True, separators=(",", ":")).encode()
+    ).hexdigest()
+    run_id = "6400-manual-soak-" + commit[:8]
+    run_root = Path(os.environ.get("PROD2U_SOAK_RUN_ROOT", "/data/prod2u/runs")) / run_id
     run_root.mkdir(parents=True, exist_ok=False)
     run_root.mkdir(parents=True, exist_ok=False)
     result_json = run_root / "soak-result.json"
     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")
+    env = os.environ.copy()
+    env["PROD2U_SOAK_RESULT"] = str(result_json)
+    env.setdefault("PROD2U_SOAK_ITERATIONS", "2048")
+    env.setdefault("PROD2U_SOAK_SEED", "64006400")
     started = time.monotonic()
     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={"BMC_INITIAL_EPOCH": 0xFFFA},
-            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
+    completed = subprocess.run([sys.executable, "-B", str(test)], cwd=ROOT, env=env, text=True, capture_output=True, check=False)
+    status = "PASS" if completed.returncode == 0 and result_json.is_file() else "FAIL"
     receipt = {
     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",
+      "schema": "prod2u-6400-manual-soak-receipt-v1", "run_id": run_id, "status": status,
+      "commit": commit, "tree": tree, "clean": not bool(dirty),
+      "command": "python3 tools/run_6400_soak.py", "duration_seconds": round(time.monotonic() - started, 3),
+      "source_manifest_sha256": source_manifest, "iterations": int(env["PROD2U_SOAK_ITERATIONS"]),
+      "seed": int(env["PROD2U_SOAK_SEED"]), "result": json.loads(result_json.read_text()) if result_json.is_file() else None,
+      "stdout": completed.stdout[-4000:], "stderr": completed.stderr[-4000:], "hardware": "NOT_RUN",
     }
     }
     receipt_path = run_root / "soak-receipt.json"
     receipt_path = run_root / "soak-receipt.json"
     receipt_path.write_text(json.dumps(receipt, indent=2, sort_keys=True) + "\n", encoding="utf-8")
     receipt_path.write_text(json.dumps(receipt, indent=2, sort_keys=True) + "\n", encoding="utf-8")
     print(receipt_path)
     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
-
+    print("MANUAL_SOAK_PASS" if status == "PASS" else "MANUAL_SOAK_FAIL")
+    return 0 if status == "PASS" else 1
 
 
 if __name__ == "__main__":
 if __name__ == "__main__":
     raise SystemExit(main())
     raise SystemExit(main())