Просмотр исходного кода

test(resource): add deterministic UART A B recorder

root 3 месяцев назад
Родитель
Сommit
1f42f18c5e
1 измененных файлов с 134 добавлено и 0 удалено
  1. 134 0
      tools/run_uart_resource_ab.py

+ 134 - 0
tools/run_uart_resource_ab.py

@@ -0,0 +1,134 @@
+#!/usr/bin/env python3
+"""Run and record the fixed-27 versus fractional Host UART A/B trial."""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+from pathlib import Path
+import subprocess
+import tempfile
+
+
+ROOT = Path(__file__).resolve().parents[1]
+DEFAULT_OUTPUT = ROOT / "receipts" / "resource" / "uart-baud-ab.json"
+CANDIDATES = {
+    "fixed_27": {
+        "top": "uart_fixed_candidate_top",
+        "sources": [
+            "src/common/uart_rx_byte.v",
+            "src/common/uart_tx_byte.v",
+            "tests/resource/uart_fixed_candidate_top.v",
+        ],
+        "wire_behavior": "27 clocks per bit; 925925.926 baud; +0.469% nominal error",
+    },
+    "fractional_27_28": {
+        "top": "uart_fractional_candidate_top",
+        "sources": [
+            "src/common/uart_rx_byte_fractional.v",
+            "src/common/uart_tx_byte_fractional.v",
+            "tests/resource/uart_fractional_candidate_top.v",
+        ],
+        "wire_behavior": "phase accumulator; 27/28 clocks per bit; zero long-term nominal error",
+    },
+}
+
+
+def run(argv: list[str]) -> str:
+    result = subprocess.run(argv, cwd=ROOT, check=True, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
+    return result.stdout
+
+
+def sha256(path: Path) -> str:
+    return hashlib.sha256(path.read_bytes()).hexdigest()
+
+
+def yosys_stats(top: str, sources: list[str]) -> tuple[dict[str, object], str]:
+    script = (
+        "read_verilog " + " ".join(sources) + "; "
+        f"hierarchy -check -top {top}; synth -noabc -top {top}; abc -lut 4; stat -json"
+    )
+    output = run(["yosys", "-Q", "-T", "-p", script])
+    marker = output.rfind('{\n   "creator"')
+    if marker < 0:
+        raise RuntimeError("Yosys JSON statistics were not found")
+    value, _ = json.JSONDecoder().raw_decode(output[marker:])
+    design = value["design"]
+    types = design["num_cells_by_type"]
+    dff = sum(int(count) for name, count in types.items() if "DFF" in name)
+    return {
+        "lut4": int(types.get("$lut", 0)),
+        "dff": dff,
+        "total_cells": int(design["num_cells"]),
+        "cell_types": types,
+    }, script
+
+
+def main() -> int:
+    parser = argparse.ArgumentParser()
+    parser.add_argument("--output", type=Path, default=DEFAULT_OUTPUT)
+    args = parser.parse_args()
+    status = run(["git", "status", "--porcelain"])
+    if status:
+        raise RuntimeError("resource A/B receipts require a clean worktree")
+    commit = run(["git", "rev-parse", "HEAD"]).strip()
+    with tempfile.TemporaryDirectory(prefix="prod2u-uart-ab-") as directory:
+        simulation = Path(directory) / "uart_baud_candidates_tb.vvp"
+        simulation_sources = [
+            "src/common/uart_rx_byte.v",
+            "src/common/uart_tx_byte.v",
+            "src/common/uart_rx_byte_fractional.v",
+            "src/common/uart_tx_byte_fractional.v",
+            "tests/sim/uart_baud_candidates_tb.v",
+        ]
+        run(["iverilog", "-g2012", "-Wall", "-s", "uart_baud_candidates_tb", "-o", str(simulation), *simulation_sources])
+        simulation_output = run(["vvp", str(simulation)]).strip()
+    results: dict[str, object] = {}
+    for name, candidate in CANDIDATES.items():
+        top = str(candidate["top"])
+        sources = list(candidate["sources"])
+        run(["verilator", "--lint-only", "--Wall", "--top-module", top, *sources])
+        resources, yosys_script = yosys_stats(top, sources)
+        results[name] = {
+            "top": top,
+            "sources": {source: sha256(ROOT / source) for source in sources},
+            "wire_behavior": candidate["wire_behavior"],
+            "yosys_lut4_mapping": resources,
+            "yosys_script": yosys_script,
+            "verilator_lint": "PASS",
+        }
+    fixed_lut = results["fixed_27"]["yosys_lut4_mapping"]["lut4"]
+    fractional_lut = results["fractional_27_28"]["yosys_lut4_mapping"]["lut4"]
+    if fixed_lut > fractional_lut:
+        raise RuntimeError("selection rule changed: fractional candidate is now smaller")
+    receipt = {
+        "schema": "prod2u-6400-uart-resource-ab-v1",
+        "run_id": f"uart-baud-ab-{commit[:12]}",
+        "source_commit": commit,
+        "project_sha256": sha256(ROOT / "products/6400-control/project.json"),
+        "contract_sha256": (ROOT / "generated/6400/contract-sha256.txt").read_text(encoding="ascii").strip(),
+        "tools": {
+            "yosys": run(["yosys", "-V"]).strip(),
+            "verilator": run(["verilator", "--version"]).strip(),
+            "iverilog": run(["iverilog", "-V"]).splitlines()[0],
+        },
+        "bit_level_simulation": {
+            "status": "PASS",
+            "coverage": "peer 26/27/28 clocks, +/-1-clock per-bit jitter, arbitrary start phase, 64 continuous bytes, TX loopback",
+            "output": simulation_output,
+        },
+        "candidates": results,
+        "selected": "fixed_27",
+        "selection_reason": "Both candidates passed bit-level simulation and lint; fixed-27 uses fewer mapped LUT4 and DFF resources.",
+        "td_resource_comparison": "PENDING_L13_TD_RUN",
+        "hardware_validation_state": "NOT RUN",
+    }
+    args.output.parent.mkdir(parents=True, exist_ok=True)
+    args.output.write_text(json.dumps(receipt, indent=2, sort_keys=True) + "\n", encoding="utf-8")
+    print(f"PASS: selected fixed_27 ({fixed_lut} LUT4 vs {fractional_lut} LUT4)")
+    return 0
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())