Quellcode durchsuchen

fix: bind all candidate package receipts

Codex Resource Selftest vor 4 Monaten
Ursprung
Commit
53d09becc0
3 geänderte Dateien mit 142 neuen und 25 gelöschten Zeilen
  1. 22 0
      tests/unit/test_codex_harness.py
  2. 117 23
      tools/codex_harness.py
  3. 3 2
      tools/prod2u_p4_harness.py

+ 22 - 0
tests/unit/test_codex_harness.py

@@ -87,6 +87,28 @@ class CodexHarnessTests(unittest.TestCase):
             self.assertEqual(receipt["status"], "pass")
             self.assertEqual(receipt["status"], "pass")
             self.assertEqual(receipt["failures"], [])
             self.assertEqual(receipt["failures"], [])
 
 
+    def test_supplied_receipt_is_copied_with_package_bindings(self):
+        with tempfile.TemporaryDirectory() as directory:
+            root = Path(directory)
+            bitstream = root / "candidate.bit"
+            bitstream.write_bytes(b"candidate-bitstream")
+            source_receipt = root / "icarus.json"
+            source_receipt.write_text('{"schema":"hdl","status":"pass"}\n', encoding="utf-8")
+            package = codex_harness.create_unverified_package(
+                bitstream=bitstream,
+                project=Path("projects/prod2u-door-temp/project.json"),
+                commit="0123abcd",
+                run_id="c" * 32,
+                output_root=root / "dist",
+                verification_receipts={"icarus": source_receipt},
+            )
+            bound = json.loads((package / "evidence/icarus-receipt.json").read_text(encoding="utf-8"))
+            self.assertEqual(bound["status"], "pass")
+            self.assertEqual(bound["verification_run_id"], "c" * 32)
+            self.assertEqual(bound["commit"], "0123abcd")
+            self.assertRegex(bound["project_config_sha256"], r"^[0-9a-f]{64}$")
+            self.assertRegex(bound["source_receipt_sha256"], r"^[0-9a-f]{64}$")
+
     def test_build_source_list_and_build_info_use_only_the_new_contract(self):
     def test_build_source_list_and_build_info_use_only_the_new_contract(self):
         sources = prod2u_p4_normal_v3_build.PRODUCTION_RTL_SOURCES
         sources = prod2u_p4_normal_v3_build.PRODUCTION_RTL_SOURCES
         self.assertIn("src/common/frame_rx.v", sources)
         self.assertIn("src/common/frame_rx.v", sources)

+ 117 - 23
tools/codex_harness.py

@@ -46,17 +46,49 @@ PACKAGE_MANIFEST_SCHEMA = "prod2u-simple-package-manifest-v2"
 RUNTIME_PROFILE = "prod2u-door-temp-115200-v1"
 RUNTIME_PROFILE = "prod2u-door-temp-115200-v1"
 
 
 
 
-def _receipt_payload(*, name: str, run_id: str, commit: str, bitstream_sha256: str) -> dict[str, Any]:
+def _receipt_payload(*, name: str, run_id: str, commit: str, bitstream_sha256: str, project_config_sha256: str) -> dict[str, Any]:
     return {
     return {
         "schema": f"prod2u-p4-normal-v3-{name}-receipt-v1",
         "schema": f"prod2u-p4-normal-v3-{name}-receipt-v1",
         "status": "not_run",
         "status": "not_run",
         "verification_run_id": run_id,
         "verification_run_id": run_id,
         "commit": commit,
         "commit": commit,
         "bitstream_sha256": bitstream_sha256,
         "bitstream_sha256": bitstream_sha256,
+        "project_config_sha256": project_config_sha256,
         "authority_boundary": "Offline package placeholder. No COM, JTAG, programming, or board action.",
         "authority_boundary": "Offline package placeholder. No COM, JTAG, programming, or board action.",
     }
     }
 
 
 
 
+def _copy_bound_receipt(
+    source: Path,
+    destination: Path,
+    *,
+    run_id: str,
+    commit: str,
+    bitstream_sha256: str,
+    project_config_sha256: str,
+) -> dict[str, Any]:
+    try:
+        value = json.loads(Path(source).read_text(encoding="utf-8-sig"))
+    except (OSError, UnicodeError, json.JSONDecodeError) as exc:
+        raise ValueError(f"receipt is not readable JSON: {source}") from exc
+    if not isinstance(value, dict):
+        raise ValueError(f"receipt root must be an object: {source}")
+    bindings = {
+        "verification_run_id": run_id,
+        "commit": commit,
+        "bitstream_sha256": bitstream_sha256,
+        "project_config_sha256": project_config_sha256,
+    }
+    for field, expected in bindings.items():
+        observed = value.get(field)
+        if observed not in {None, "", expected}:
+            raise ValueError(f"receipt binding mismatch for {field}: {source}")
+        value[field] = expected
+    value["source_receipt_sha256"] = sha256_file(source)
+    _write_json(destination, value)
+    return value
+
+
 def _package_file_hashes(package: Path) -> dict[str, str]:
 def _package_file_hashes(package: Path) -> dict[str, str]:
     excluded = {
     excluded = {
         "package-info.json",
         "package-info.json",
@@ -159,6 +191,7 @@ def create_unverified_package(
     run_id: str,
     run_id: str,
     output_root: Path,
     output_root: Path,
     td_receipt: Path | None = None,
     td_receipt: Path | None = None,
+    verification_receipts: Mapping[str, Path] | None = None,
 ) -> Path:
 ) -> Path:
     if not COMMIT_RE.fullmatch(commit):
     if not COMMIT_RE.fullmatch(commit):
         raise ValueError("commit must be 8 lowercase hexadecimal characters")
         raise ValueError("commit must be 8 lowercase hexadecimal characters")
@@ -190,27 +223,54 @@ def create_unverified_package(
         if not source.is_file():
         if not source.is_file():
             raise FileNotFoundError(f"package source is missing: {source}")
             raise FileNotFoundError(f"package source is missing: {source}")
         shutil.copy2(source, package / name)
         shutil.copy2(source, package / name)
+    project_config_sha256 = sha256_file(package_project)
     source_manifest = build_source_manifest(repo)
     source_manifest = build_source_manifest(repo)
     _write_json(package / "source_manifest.json", source_manifest)
     _write_json(package / "source_manifest.json", source_manifest)
+    receipt_sources = dict(verification_receipts or {})
     if td_receipt is not None:
     if td_receipt is not None:
         receipt = Path(td_receipt)
         receipt = Path(td_receipt)
         if not receipt.is_file():
         if not receipt.is_file():
             raise FileNotFoundError(f"TD receipt is missing: {receipt}")
             raise FileNotFoundError(f"TD receipt is missing: {receipt}")
-        shutil.copy2(receipt, evidence / "td-primary-receipt.json")
-    else:
-        _write_json(
+        _copy_bound_receipt(
+            receipt,
             evidence / "td-primary-receipt.json",
             evidence / "td-primary-receipt.json",
-            _receipt_payload(name="td-primary", run_id=run_id, commit=commit, bitstream_sha256=bitstream_sha256),
+            run_id=run_id,
+            commit=commit,
+            bitstream_sha256=bitstream_sha256,
+            project_config_sha256=project_config_sha256,
         )
         )
-    _write_json(
-        evidence / "td-confirmation-receipt.json",
-        _receipt_payload(name="td-confirmation", run_id=run_id, commit=commit, bitstream_sha256=bitstream_sha256),
-    )
-    for name in ("python-unit", "icarus", "verilator", "cocotb", "formal"):
+    else:
         _write_json(
         _write_json(
-            evidence / f"{name}-receipt.json",
-            _receipt_payload(name=name, run_id=run_id, commit=commit, bitstream_sha256=bitstream_sha256),
+            evidence / "td-primary-receipt.json",
+            _receipt_payload(name="td-primary", run_id=run_id, commit=commit, bitstream_sha256=bitstream_sha256, project_config_sha256=project_config_sha256),
         )
         )
+    receipt_specs = {
+        "td-confirmation": "td-confirmation-receipt.json",
+        "python-unit": "python-unit-receipt.json",
+        "icarus": "icarus-receipt.json",
+        "verilator": "verilator-receipt.json",
+        "cocotb": "cocotb-receipt.json",
+        "formal": "formal-receipt.json",
+    }
+    for name, filename in receipt_specs.items():
+        source = receipt_sources.get(name)
+        if source is not None:
+            source_path = Path(source)
+            if not source_path.is_file():
+                raise FileNotFoundError(f"verification receipt is missing: {source_path}")
+            _copy_bound_receipt(
+                source_path,
+                evidence / filename,
+                run_id=run_id,
+                commit=commit,
+                bitstream_sha256=bitstream_sha256,
+                project_config_sha256=project_config_sha256,
+            )
+        else:
+            _write_json(
+                evidence / filename,
+                _receipt_payload(name=name, run_id=run_id, commit=commit, bitstream_sha256=bitstream_sha256, project_config_sha256=project_config_sha256),
+            )
     _write_json(
     _write_json(
         evidence / "package-selftest-result.json",
         evidence / "package-selftest-result.json",
         {
         {
@@ -228,12 +288,29 @@ def create_unverified_package(
         sha256_file(package_bitstream) + "\n", encoding="ascii", newline="\n"
         sha256_file(package_bitstream) + "\n", encoding="ascii", newline="\n"
     )
     )
     td_status = "not_run"
     td_status = "not_run"
+    td_synthesis_input_hash = None
+    confirmation_bitstream_sha256 = None
+    confirmation_synthesis_input_hash = None
     try:
     try:
         td_value = json.loads((evidence / "td-primary-receipt.json").read_text(encoding="utf-8-sig"))
         td_value = json.loads((evidence / "td-primary-receipt.json").read_text(encoding="utf-8-sig"))
         if isinstance(td_value, Mapping) and td_value.get("status") in {"pass", "fail", "blocked", "not_run"}:
         if isinstance(td_value, Mapping) and td_value.get("status") in {"pass", "fail", "blocked", "not_run"}:
             td_status = str(td_value["status"])
             td_status = str(td_value["status"])
+            td_synthesis_input_hash = td_value.get("synthesis_input_hash")
     except (OSError, UnicodeError, json.JSONDecodeError):
     except (OSError, UnicodeError, json.JSONDecodeError):
         td_status = "fail"
         td_status = "fail"
+    try:
+        confirmation_value = json.loads((evidence / "td-confirmation-receipt.json").read_text(encoding="utf-8-sig"))
+        if isinstance(confirmation_value, Mapping) and confirmation_value.get("status") == "pass":
+            confirmation_bitstream_sha256 = confirmation_value.get("bitstream_sha256")
+            confirmation_synthesis_input_hash = confirmation_value.get("synthesis_input_hash")
+    except (OSError, UnicodeError, json.JSONDecodeError):
+        pass
+    def receipt_status(filename: str) -> str:
+        try:
+            value = json.loads((evidence / filename).read_text(encoding="utf-8-sig"))
+        except (OSError, UnicodeError, json.JSONDecodeError):
+            return "fail"
+        return str(value.get("status", "fail")) if isinstance(value, Mapping) else "fail"
     validation_summary = {
     validation_summary = {
         "schema": "prod2u-p4-normal-v3-validation-summary-v1",
         "schema": "prod2u-p4-normal-v3-validation-summary-v1",
         "status": "UNVERIFIED",
         "status": "UNVERIFIED",
@@ -245,18 +322,18 @@ def create_unverified_package(
         "bitstream_sha256": bitstream_sha256,
         "bitstream_sha256": bitstream_sha256,
         "project_config_sha256": sha256_file(package_project),
         "project_config_sha256": sha256_file(package_project),
         "layers": {
         "layers": {
-            "python_unit": {"status": "not_run"},
-            "icarus": {"status": "not_run"},
-            "verilator": {"status": "not_run"},
-            "cocotb": {"status": "not_run"},
-            "formal": {"status": "not_run"},
+            "python_unit": {"status": receipt_status("python-unit-receipt.json")},
+            "icarus": {"status": receipt_status("icarus-receipt.json")},
+            "verilator": {"status": receipt_status("verilator-receipt.json")},
+            "cocotb": {"status": receipt_status("cocotb-receipt.json")},
+            "formal": {"status": receipt_status("formal-receipt.json")},
             "td_primary": {"status": td_status},
             "td_primary": {"status": td_status},
-            "td_confirmation": {"status": "not_run"},
-            "td_confirmation_artifacts": {"status": "not_run"},
-            "td_confirmation_bitstream": {"status": "not_run"},
-            "td_confirmation_synthesis": {"status": "not_run"},
-            "td_confirmation_manifest": {"status": "not_run"},
-            "resource_confirmation": {"status": "not_run"},
+            "td_confirmation": {"status": receipt_status("td-confirmation-receipt.json")},
+            "td_confirmation_artifacts": {"status": "pass" if confirmation_bitstream_sha256 else "not_run"},
+            "td_confirmation_bitstream": {"status": "pass" if confirmation_bitstream_sha256 else "not_run"},
+            "td_confirmation_synthesis": {"status": "pass" if confirmation_synthesis_input_hash else "not_run"},
+            "td_confirmation_manifest": {"status": "pass" if confirmation_synthesis_input_hash else "not_run"},
+            "resource_confirmation": {"status": "pass" if confirmation_bitstream_sha256 else "not_run"},
         },
         },
         "hardware_validation": "not_run",
         "hardware_validation": "not_run",
     }
     }
@@ -277,6 +354,9 @@ def create_unverified_package(
         "project_sha256": sha256_file(package_project),
         "project_sha256": sha256_file(package_project),
         "project_config_sha256": sha256_file(package_project),
         "project_config_sha256": sha256_file(package_project),
         "source_manifest_sha256": sha256_file(package / "source_manifest.json"),
         "source_manifest_sha256": sha256_file(package / "source_manifest.json"),
+        "synthesis_input_hash": td_synthesis_input_hash,
+        "confirmation_bitstream_sha256": confirmation_bitstream_sha256,
+        "confirmation_synthesis_input_hash": confirmation_synthesis_input_hash,
         "td_receipt_sha256": sha256_file(evidence / "td-primary-receipt.json"),
         "td_receipt_sha256": sha256_file(evidence / "td-primary-receipt.json"),
         "confirmation_td_receipt_sha256": sha256_file(evidence / "td-confirmation-receipt.json"),
         "confirmation_td_receipt_sha256": sha256_file(evidence / "td-confirmation-receipt.json"),
         "validation_summary_sha256": sha256_file(evidence / "validation-summary.json"),
         "validation_summary_sha256": sha256_file(evidence / "validation-summary.json"),
@@ -325,6 +405,13 @@ def main() -> int:
     package.add_argument("--run-id", required=True)
     package.add_argument("--run-id", required=True)
     package.add_argument("--output-root", type=Path, default=Path("dist"))
     package.add_argument("--output-root", type=Path, default=Path("dist"))
     package.add_argument("--td-receipt", type=Path)
     package.add_argument("--td-receipt", type=Path)
+    package.add_argument(
+        "--receipt",
+        action="append",
+        default=[],
+        metavar="NAME=PATH",
+        help="bind an additional receipt under evidence (NAME: python-unit, icarus, verilator, cocotb, formal, td-confirmation)",
+    )
     args = parser.parse_args()
     args = parser.parse_args()
     if args.command == "run-id":
     if args.command == "run-id":
         print(new_run_id())
         print(new_run_id())
@@ -333,6 +420,12 @@ def main() -> int:
     elif args.command == "manifest":
     elif args.command == "manifest":
         print(json.dumps(build_source_manifest(args.root), indent=2, sort_keys=True))
         print(json.dumps(build_source_manifest(args.root), indent=2, sort_keys=True))
     else:
     else:
+        receipt_map: dict[str, Path] = {}
+        for item in args.receipt:
+            name, separator, raw_path = item.partition("=")
+            if not separator or not name or not raw_path:
+                raise SystemExit(f"invalid --receipt value: {item!r}; expected NAME=PATH")
+            receipt_map[name] = Path(raw_path)
         print(create_unverified_package(
         print(create_unverified_package(
             bitstream=args.bitstream,
             bitstream=args.bitstream,
             project=args.project,
             project=args.project,
@@ -340,6 +433,7 @@ def main() -> int:
             run_id=args.run_id,
             run_id=args.run_id,
             output_root=args.output_root,
             output_root=args.output_root,
             td_receipt=args.td_receipt,
             td_receipt=args.td_receipt,
+            verification_receipts=receipt_map,
         ))
         ))
     return 0
     return 0
 
 

+ 3 - 2
tools/prod2u_p4_harness.py

@@ -3299,10 +3299,11 @@ def package_selftest_payload(
                     if isinstance(confirmation_layer, Mapping)
                     if isinstance(confirmation_layer, Mapping)
                     else None
                     else None
                 )
                 )
-                if confirmation_status not in {"not_run", "running"}:
+                if confirmation_status not in {"pass", "not_run", "running"}:
                     failures.append(
                     failures.append(
                         "urgent_confirmation_layer_invalid:td_confirmation"
                         "urgent_confirmation_layer_invalid:td_confirmation"
                     )
                     )
+                expected_confirmation_status = "pass" if confirmation_status == "pass" else "not_run"
                 for name in (
                 for name in (
                     "td_confirmation_artifacts",
                     "td_confirmation_artifacts",
                     "td_confirmation_bitstream",
                     "td_confirmation_bitstream",
@@ -3311,7 +3312,7 @@ def package_selftest_payload(
                     "resource_confirmation",
                     "resource_confirmation",
                 ):
                 ):
                     layer = layers.get(name)
                     layer = layers.get(name)
-                    if not isinstance(layer, Mapping) or layer.get("status") != "not_run":
+                    if not isinstance(layer, Mapping) or layer.get("status") != expected_confirmation_status:
                         failures.append(f"urgent_confirmation_layer_not_not_run:{name}")
                         failures.append(f"urgent_confirmation_layer_not_not_run:{name}")
 
 
     script_result: dict[str, Any] = {"status": "not_run", "returncode": None}
     script_result: dict[str, Any] = {"status": "not_run", "returncode": None}