Procházet zdrojové kódy

fix(mse): bind firmware and review identity to the packaged TD receipt

Fresh TD bitstream f3242a47 cannot share historical canonical identity
b4b0eda4. release_set_id now follows the live receipt's run_id, commit,
and parsed LUT/MSLICE/DSP.

Co-authored-by: Cursor <cursoragent@cursor.com>
root před 3 měsíci
rodič
revize
54d03a625f

+ 48 - 16
package_for_agent_analysis.py

@@ -1738,8 +1738,8 @@ def collect_analysis_inputs(
             # back to ARTIFACT or sibling filenames collapse to the wrong tip.
             # back to ARTIFACT or sibling filenames collapse to the wrong tip.
             delivery = str(head or binding_commit or "").strip()
             delivery = str(head or binding_commit or "").strip()
             artifact = str(
             artifact = str(
-                binding.get("artifact_source_commit")
-                or report_artifact
+                report_artifact
+                or binding.get("artifact_source_commit")
                 or pkg_prov.ARTIFACT_DEFAULT
                 or pkg_prov.ARTIFACT_DEFAULT
                 or ""
                 or ""
             ).strip()
             ).strip()
@@ -1936,11 +1936,7 @@ def collect_analysis_inputs(
                 or binding.get("software_verification_run_id")
                 or binding.get("software_verification_run_id")
                 or ""
                 or ""
             ).strip()
             ).strip()
-            td_bound = str(
-                binding.get("td_bound_commit")
-                or binding.get("artifact_source_commit")
-                or artifact
-            ).strip()
+            td_bound = str(report_artifact or artifact).strip()
             release_identity = {
             release_identity = {
                 "schema": "prod2u-release-set-identity-v1",
                 "schema": "prod2u-release-set-identity-v1",
                 "algorithm_version": "prod2u-release-set-id-v1",
                 "algorithm_version": "prod2u-release-set-id-v1",
@@ -1957,8 +1953,12 @@ def collect_analysis_inputs(
                 "delivery_commit": delivery,
                 "delivery_commit": delivery,
                 "bitstream_sha256": bit_sha,
                 "bitstream_sha256": bit_sha,
                 "td_binding_status": "pass",
                 "td_binding_status": "pass",
-                "td_policy": "reused_exact_source_bound_td",
-                "production_binding": "37/37/0/0",
+                "td_policy": (
+                    "reused_exact_source_bound_td"
+                    if bit_sha == pkg_prov.CANONICAL_TD_A1_BITSTREAM
+                    else "fresh_td"
+                ),
+                "production_binding": None,
                 "production_polarity_config": {
                 "production_polarity_config": {
                     "limit_active_high": polarity.get("limit_active_high"),
                     "limit_active_high": polarity.get("limit_active_high"),
                     "dir_close_level": polarity.get("dir_close_level"),
                     "dir_close_level": polarity.get("dir_close_level"),
@@ -1985,14 +1985,46 @@ def collect_analysis_inputs(
                 ),
                 ),
             }
             }
             try:
             try:
-                td_fields = pkg_prov.load_canonical_td_a1_fields(root)
-                release_identity["lut"] = td_fields.get("lut")
-                release_identity["mslice"] = td_fields.get("mslice")
-                release_identity["dsp"] = td_fields.get("dsp")
-                if not release_identity.get("td_receipt_sha256"):
-                    release_identity["td_receipt_sha256"] = td_fields.get("td_receipt_sha256")
+                live_parsed = pkg_prov.parse_td_resource_fields(td_report_payload)
+                if live_parsed.get("lut") is not None:
+                    release_identity["lut"] = live_parsed.get("lut")
+                if live_parsed.get("mslice") is not None:
+                    release_identity["mslice"] = live_parsed.get("mslice")
+                if live_parsed.get("dsp") is not None:
+                    release_identity["dsp"] = live_parsed.get("dsp")
             except Exception:  # noqa: BLE001
             except Exception:  # noqa: BLE001
-                pass
+                live_parsed = {}
+            n_inputs = len(art_to_del.get("inputs") or [])
+            changed_n = len(art_to_del.get("production_changed_paths") or [])
+            if n_inputs:
+                matched = n_inputs - changed_n
+                if matched < 0:
+                    matched = 0
+                release_identity["production_binding"] = pkg_prov.format_production_binding(
+                    expected=n_inputs,
+                    matched=matched,
+                    missing=0,
+                    hash_mismatch=changed_n,
+                )
+            if (
+                release_identity.get("lut") is None
+                or release_identity.get("mslice") is None
+                or release_identity.get("dsp") is None
+            ) and bit_sha == pkg_prov.CANONICAL_TD_A1_BITSTREAM:
+                try:
+                    td_fields = pkg_prov.load_canonical_td_a1_fields(root)
+                    if release_identity.get("lut") is None:
+                        release_identity["lut"] = td_fields.get("lut")
+                    if release_identity.get("mslice") is None:
+                        release_identity["mslice"] = td_fields.get("mslice")
+                    if release_identity.get("dsp") is None:
+                        release_identity["dsp"] = td_fields.get("dsp")
+                    if not release_identity.get("td_receipt_sha256"):
+                        release_identity["td_receipt_sha256"] = td_fields.get(
+                            "td_receipt_sha256"
+                        )
+                except Exception:  # noqa: BLE001
+                    pass
             for report_meta in binding.get("td_reports") or []:
             for report_meta in binding.get("td_reports") or []:
                 if isinstance(report_meta, dict) and report_meta.get("sha256"):
                 if isinstance(report_meta, dict) and report_meta.get("sha256"):
                     release_identity["td_receipt_sha256"] = report_meta.get("sha256")
                     release_identity["td_receipt_sha256"] = report_meta.get("sha256")

+ 16 - 3
tests/unit/test_build_firmware_package.py

@@ -59,7 +59,9 @@ def _write_report(path: Path, *, bitstream_sha256: str | None = None, project_sh
     report = {
     report = {
         "run_id": FAKE_TD_RUN_ID,
         "run_id": FAKE_TD_RUN_ID,
         "verification_run_id": "88888888888888888888888888888888",
         "verification_run_id": "88888888888888888888888888888888",
+        "status": "pass",
         "commit_full": "fe1a0a2a19622b6f290905ec14795bb6cce6899d",
         "commit_full": "fe1a0a2a19622b6f290905ec14795bb6cce6899d",
+        "commit": "fe1a0a2a19622b6f290905ec14795bb6cce6899d",
         "project_config_sha256": project_sha,
         "project_config_sha256": project_sha,
         "td_source_manifest_sha256": "8e0da456e865f3c3afa613d2660c1ed0ebf0e422ef51ec7acef223c2017a14bd",
         "td_source_manifest_sha256": "8e0da456e865f3c3afa613d2660c1ed0ebf0e422ef51ec7acef223c2017a14bd",
         "bitstream_sha256": bitstream_sha256,
         "bitstream_sha256": bitstream_sha256,
@@ -84,7 +86,7 @@ def _write_report(path: Path, *, bitstream_sha256: str | None = None, project_sh
                 "bram": {"used": 0},
                 "bram": {"used": 0},
                 "dsp": {"used": 0},
                 "dsp": {"used": 0},
             },
             },
-            "packing": {"total_slices": 570},
+            "packing": {"mslice": 570, "lslice": 570, "total_slices": 1140},
         },
         },
     }
     }
     path.write_text(json.dumps(report), encoding="utf-8")
     path.write_text(json.dumps(report), encoding="utf-8")
@@ -147,8 +149,19 @@ class BuildFirmwarePackageTests(unittest.TestCase):
                 self.assertEqual(polarity["masks"]["dir_close_level_mask"], "3'b111")
                 self.assertEqual(polarity["masks"]["dir_close_level_mask"], "3'b111")
                 self.assertEqual(polarity["masks"]["close_limit_is_ls_mask"], "3'b111")
                 self.assertEqual(polarity["masks"]["close_limit_is_ls_mask"], "3'b111")
                 self.assertEqual(len(polarity["sha256"]), 64)
                 self.assertEqual(len(polarity["sha256"]), 64)
-                identity = builder.motor_polarity_config_identity(ROOT)
-                self.assertEqual(polarity["sha256"], identity["sha256"])
+                polarity_id = builder.motor_polarity_config_identity(ROOT)
+                self.assertEqual(polarity["sha256"], polarity_id["sha256"])
+                identity = json.loads(zipf.read("meta/release-set-identity.json"))
+                self.assertEqual(identity["bitstream_sha256"], FAKE_BIT_SHA)
+                self.assertNotEqual(
+                    identity["bitstream_sha256"],
+                    pkg_prov.CANONICAL_TD_A1_BITSTREAM,
+                )
+                self.assertEqual(identity["td_artifact_run_id"], FAKE_TD_RUN_ID)
+                self.assertEqual(identity["lut"], 1113)
+                self.assertEqual(identity["mslice"], 570)
+                self.assertEqual(identity["td_policy"], "fresh_td")
+                self.assertEqual(identity["td_binding_status"], "pass")
                 sums = zipf.read("SHA256SUMS.txt").decode("utf-8")
                 sums = zipf.read("SHA256SUMS.txt").decode("utf-8")
                 self.assertIn("fw.bit", sums)
                 self.assertIn("fw.bit", sums)
 
 

+ 63 - 0
tests/unit/test_mse_r10_td_resources.py

@@ -2,6 +2,7 @@
 
 
 from __future__ import annotations
 from __future__ import annotations
 
 
+import json
 from pathlib import Path
 from pathlib import Path
 
 
 from tools import package_provenance as pkg_prov
 from tools import package_provenance as pkg_prov
@@ -100,3 +101,65 @@ def test_snapshot_hash_false_empty_paths_fails():
     check = pkg_prov.validate_source_closure_relations(rel)
     check = pkg_prov.validate_source_closure_relations(rel)
     assert check["status"] == "fail"
     assert check["status"] == "fail"
     assert any("empty_paths" in f for f in check["failures"])
     assert any("empty_paths" in f for f in check["failures"])
+
+
+def test_load_td_identity_fields_fresh_not_canonical(tmp_path: Path):
+    bitstream = "a" * 64
+    bound = "c9e7e2b90d60b5018d859b67a55fb162ad0eca39"
+    receipt = tmp_path / "td-receipt.json"
+    doc = {
+        "status": "pass",
+        "run_id": "018969d8b4194ba285ca6dd18c1180bf",
+        "verification_run_id": "e10d2026081301474900000000000000",
+        "commit": bound,
+        "commit_full": bound,
+        "bitstream_sha256": bitstream,
+        "mslice": 1089,
+        "synthesis_input_manifest": {"inputs": {f"f{i}.v": "b" * 64 for i in range(37)}},
+        "resources": {
+            "utilization": {
+                "lut": {"used": 4320},
+                "dsp": {"used": 1},
+            },
+            "packing": {"mslice": 1089, "lslice": 1089, "total_slices": 2178},
+        },
+    }
+    receipt.write_text(json.dumps(doc), encoding="utf-8")
+    fields = pkg_prov.load_td_identity_fields(receipt, repo_root=ROOT)
+    assert fields["bitstream_sha256"] == bitstream
+    assert fields["bitstream_sha256"] != pkg_prov.CANONICAL_TD_A1_BITSTREAM
+    assert fields["td_bound_commit"] == bound
+    assert fields["td_artifact_run_id"] == "018969d8b4194ba285ca6dd18c1180bf"
+    assert fields["lut"] == 4320
+    assert fields["mslice"] == 1089
+    assert fields["dsp"] == 1
+    assert fields["td_policy"] == "fresh_td"
+    assert fields["production_binding"] == "37/37/0/0"
+    ident = pkg_prov.build_shared_release_identity(
+        delivery_commit="d" * 40,
+        package_stage="final-review",
+        matrix_verification_tip="e" * 40,
+        software_verification_run_id="mse-r10-test",
+        config_fingerprint="x",
+        reference_set_fingerprint="y",
+        repo_root=ROOT,
+        claim_bound_bitstream=True,
+        td_fields=fields,
+    )
+    assert ident["bitstream_sha256"] == bitstream
+    assert ident["artifact_source_commit"] == bound
+    assert ident["lut"] == 4320
+    assert ident["mslice"] == 1089
+    assert ident["td_policy"] == "fresh_td"
+    canonical = pkg_prov.load_canonical_td_a1_fields(ROOT)
+    assert ident["release_set_id"] != pkg_prov.build_shared_release_identity(
+        delivery_commit="d" * 40,
+        package_stage="final-review",
+        matrix_verification_tip="e" * 40,
+        software_verification_run_id="mse-r10-test",
+        config_fingerprint="x",
+        reference_set_fingerprint="y",
+        repo_root=ROOT,
+        claim_bound_bitstream=True,
+    )["release_set_id"]
+    assert canonical["bitstream_sha256"] == pkg_prov.CANONICAL_TD_A1_BITSTREAM

+ 2 - 0
tests/unit/test_release_set_provenance.py

@@ -329,7 +329,9 @@ class FirmwarePackageProvenanceIntegrationTests(unittest.TestCase):
             run_id = "td-run-prov"
             run_id = "td-run-prov"
             report = {
             report = {
                 "run_id": run_id,
                 "run_id": run_id,
+                "status": "pass",
                 "commit_full": commit,
                 "commit_full": commit,
+                "commit": commit,
                 "project_config_sha256": project_sha,
                 "project_config_sha256": project_sha,
                 "td_source_manifest_sha256": "8e0da456e865f3c3afa613d2660c1ed0ebf0e422ef51ec7acef223c2017a14bd",
                 "td_source_manifest_sha256": "8e0da456e865f3c3afa613d2660c1ed0ebf0e422ef51ec7acef223c2017a14bd",
                 "bitstream_sha256": bit_sha,
                 "bitstream_sha256": bit_sha,

+ 20 - 3
tools/build_firmware_package.py

@@ -664,6 +664,21 @@ def build_firmware_package(
         raise PackagingError(
         raise PackagingError(
             "refusing Round-10 hardcoded td_artifact_run_id fallback"
             "refusing Round-10 hardcoded td_artifact_run_id fallback"
         )
         )
+    td_fields = pkg_prov.load_td_identity_fields(td_report_path, repo_root=ROOT)
+    receipt_artifact = str(td_fields.get("artifact_source_commit") or "").strip()
+    if receipt_artifact and receipt_artifact != artifact_commit:
+        raise PackagingError(
+            "TD receipt commit does not match artifact_commit "
+            f"({receipt_artifact} != {artifact_commit})"
+        )
+    if str(td_fields.get("bitstream_sha256") or "") != bitstream_sha256:
+        raise PackagingError(
+            "TD identity bitstream_sha256 does not match packaged bitstream bytes"
+        )
+    if str(td_fields.get("td_artifact_run_id") or "") != td_run_id:
+        raise PackagingError(
+            "TD identity td_artifact_run_id does not match TD report run_id"
+        )
     release_identity = pkg_prov.build_shared_release_identity(
     release_identity = pkg_prov.build_shared_release_identity(
         delivery_commit=final_dev_commit,
         delivery_commit=final_dev_commit,
         package_stage="final-review",
         package_stage="final-review",
@@ -674,6 +689,7 @@ def build_firmware_package(
         repo_root=ROOT,
         repo_root=ROOT,
         claim_bound_bitstream=True,
         claim_bound_bitstream=True,
         non_final=False,
         non_final=False,
+        td_fields=td_fields,
         extra={
         extra={
             "production_polarity_config": {
             "production_polarity_config": {
                 "limit_active_high": motor_polarity.get("limit_active_high"),
                 "limit_active_high": motor_polarity.get("limit_active_high"),
@@ -683,9 +699,10 @@ def build_firmware_package(
                 "config_fingerprint": motor_polarity["sha256"],
                 "config_fingerprint": motor_polarity["sha256"],
             },
             },
             "note": (
             "note": (
-                "Shared identity via package_provenance.build_shared_release_identity; "
-                "release_set_id uses td_artifact_run_id (= TD receipt run_id); "
-                "FINAL-DEV-COMMIT.txt is a deprecated alias for delivery_commit."
+                "Shared identity bound to the packaged TD receipt "
+                "(load_td_identity_fields); release_set_id uses that receipt's "
+                "run_id and bitstream SHA; FINAL-DEV-COMMIT.txt is a deprecated "
+                "alias for delivery_commit."
             ),
             ),
         },
         },
     )
     )

+ 93 - 4
tools/package_provenance.py

@@ -725,6 +725,7 @@ def load_canonical_td_a1_fields(repo_root: Path | None = None) -> dict[str, Any]
             _sha256_bytes(full.read_bytes()) if full.is_file() else None
             _sha256_bytes(full.read_bytes()) if full.is_file() else None
         ),
         ),
         "td_binding_status": "pass",
         "td_binding_status": "pass",
+        "td_policy": "reused_exact_source_bound_td",
         "production_binding": "37/37/0/0",
         "production_binding": "37/37/0/0",
         "lut": lut,
         "lut": lut,
         "mslice": mslice,
         "mslice": mslice,
@@ -733,6 +734,85 @@ def load_canonical_td_a1_fields(repo_root: Path | None = None) -> dict[str, Any]
     }
     }
 
 
 
 
+def format_production_binding(
+    *,
+    expected: int,
+    matched: int,
+    missing: int,
+    hash_mismatch: int,
+) -> str:
+    """Canonical ``expected/matched/missing/mismatch`` production-binding string."""
+    return f"{int(expected)}/{int(matched)}/{int(missing)}/{int(hash_mismatch)}"
+
+
+def load_td_identity_fields(
+    receipt_path: Path | str,
+    *,
+    repo_root: Path | None = None,
+) -> dict[str, Any]:
+    """Load TD identity from the receipt being packaged (historical or fresh).
+
+    Unlike ``load_canonical_td_a1_fields``, this does not require bitstream
+    ``b4b0eda4…``. Fresh TD receipts bind their own commit, run IDs, bitstream
+    SHA, and parsed LUT/MSLICE/DSP.
+    """
+    path = Path(receipt_path)
+    if not path.is_file():
+        raise FileNotFoundError(f"TD receipt not found: {path}")
+    raw = path.read_bytes()
+    doc = json.loads(raw.decode("utf-8"))
+    if not isinstance(doc, dict):
+        raise ValueError(f"TD receipt is not a JSON object: {path}")
+    run_id = str(doc.get("run_id") or doc.get("td_artifact_run_id") or "").strip()
+    if not run_id:
+        raise ValueError(f"TD receipt missing run_id: {path}")
+    bitstream = str(doc.get("bitstream_sha256") or "").strip()
+    if not bitstream:
+        raise ValueError(f"TD receipt missing bitstream_sha256: {path}")
+    bound = str(doc.get("commit_full") or doc.get("commit") or "").strip()
+    if not bound:
+        raise ValueError(f"TD receipt missing commit: {path}")
+    verification_run_id = str(doc.get("verification_run_id") or "").strip()
+    parsed = parse_td_resource_fields(doc)
+    inputs = doc.get("synthesis_input_manifest")
+    input_map = inputs.get("inputs") if isinstance(inputs, dict) else None
+    n_inputs = len(input_map) if isinstance(input_map, dict) else None
+    production_binding = (
+        format_production_binding(
+            expected=n_inputs, matched=n_inputs, missing=0, hash_mismatch=0
+        )
+        if n_inputs is not None
+        else None
+    )
+    root = Path(repo_root or ROOT)
+    try:
+        rel = str(path.resolve().relative_to(root.resolve())).replace("\\", "/")
+    except ValueError:
+        rel = str(path)
+    status = str(doc.get("status") or "").strip()
+    policy = (
+        "reused_exact_source_bound_td"
+        if bitstream == CANONICAL_TD_A1_BITSTREAM
+        else "fresh_td"
+    )
+    return {
+        "td_bound_commit": bound,
+        "artifact_source_commit": bound,
+        "bitstream_sha256": bitstream,
+        "td_artifact_run_id": run_id,
+        "td_verification_run_id": verification_run_id or None,
+        "td_receipt_path": rel,
+        "td_receipt_sha256": _sha256_bytes(raw),
+        "td_binding_status": "pass" if status.casefold() == "pass" else (status or "unknown"),
+        "td_policy": policy,
+        "production_binding": production_binding,
+        "lut": parsed["lut"],
+        "mslice": parsed["mslice"],
+        "dsp": parsed["dsp"],
+        "status": doc.get("status"),
+    }
+
+
 def build_shared_release_identity(
 def build_shared_release_identity(
     *,
     *,
     delivery_commit: str,
     delivery_commit: str,
@@ -746,12 +826,15 @@ def build_shared_release_identity(
     hardware_validation: str = "not_run",
     hardware_validation: str = "not_run",
     non_final: bool | None = None,
     non_final: bool | None = None,
     claim_bound_bitstream: bool = True,
     claim_bound_bitstream: bool = True,
+    td_fields: dict[str, Any] | None = None,
     extra: dict[str, Any] | None = None,
     extra: dict[str, Any] | None = None,
 ) -> dict[str, Any]:
 ) -> dict[str, Any]:
     """Single shared release identity for review + firmware packages.
     """Single shared release identity for review + firmware packages.
 
 
-    When ``claim_bound_bitstream`` is true, TD fields are loaded from the
-    canonical A1 receipt (never null run_id / receipt SHA).
+    When ``td_fields`` is provided (live TD receipt), those fields bind
+    identity and ``release_set_id``. Otherwise, if ``claim_bound_bitstream``
+    is true, fields load from the canonical A1 receipt (never null run_id /
+    receipt SHA).
     """
     """
     stage = package_stage.strip()
     stage = package_stage.strip()
     if non_final is None:
     if non_final is None:
@@ -759,7 +842,12 @@ def build_shared_release_identity(
     delivery = str(delivery_commit).strip()
     delivery = str(delivery_commit).strip()
     if not delivery:
     if not delivery:
         raise ValueError("delivery_commit required")
         raise ValueError("delivery_commit required")
-    td = load_canonical_td_a1_fields(repo_root) if claim_bound_bitstream else {}
+    if td_fields is not None:
+        td = dict(td_fields)
+    elif claim_bound_bitstream:
+        td = load_canonical_td_a1_fields(repo_root)
+    else:
+        td = {}
     artifact = str(td.get("artifact_source_commit") or CANONICAL_TD_A1_BOUND_COMMIT)
     artifact = str(td.get("artifact_source_commit") or CANONICAL_TD_A1_BOUND_COMMIT)
     td_run = str(td.get("td_artifact_run_id") or "")
     td_run = str(td.get("td_artifact_run_id") or "")
     bitstream = str(td.get("bitstream_sha256") or "")
     bitstream = str(td.get("bitstream_sha256") or "")
@@ -796,7 +884,8 @@ def build_shared_release_identity(
         "td_artifact_run_id": td_run or None,
         "td_artifact_run_id": td_run or None,
         "td_receipt_sha256": td.get("td_receipt_sha256"),
         "td_receipt_sha256": td.get("td_receipt_sha256"),
         "td_binding_status": td.get("td_binding_status") or ("pass" if claim_bound_bitstream else None),
         "td_binding_status": td.get("td_binding_status") or ("pass" if claim_bound_bitstream else None),
-        "production_binding": td.get("production_binding") if claim_bound_bitstream else None,
+        "td_policy": td.get("td_policy"),
+        "production_binding": td.get("production_binding") if (claim_bound_bitstream or td) else None,
         "production_polarity_fingerprint": config_fingerprint,
         "production_polarity_fingerprint": config_fingerprint,
         "reference_set_fingerprint": reference_set_fingerprint,
         "reference_set_fingerprint": reference_set_fingerprint,
         "hardware_validation": hardware_validation,
         "hardware_validation": hardware_validation,