run_6400_formal.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. #!/usr/bin/env python3
  2. """Run and bind the active 6400-front-rear Formal target registry."""
  3. from __future__ import annotations
  4. import argparse
  5. from concurrent.futures import ThreadPoolExecutor
  6. from datetime import datetime, timezone
  7. import hashlib
  8. import json
  9. import os
  10. from pathlib import Path
  11. import re
  12. import shutil
  13. import signal
  14. import subprocess
  15. import sys
  16. import time
  17. from typing import Any, Iterable
  18. ROOT = Path(__file__).resolve().parents[1]
  19. FORMAL_DIR = ROOT / "tests" / "formal"
  20. MANIFEST = FORMAL_DIR / "6400-properties.json"
  21. SOLVER_MAP = FORMAL_DIR / "solver-map.yaml"
  22. ENVIRONMENT_RECEIPT = ROOT / "receipts" / "environment" / "container-image-6400.json"
  23. PROJECT_CONTRACT = ROOT / "projects" / "prod2u-6400-front-back" / "project.json"
  24. PROFILE_CONTRACT = ROOT / "products" / "6400-front-rear" / "project.json"
  25. SOURCE_MANIFEST = ROOT / "products" / "6400-front-rear" / "source-closure.json"
  26. DESIGN_LOCK = ROOT / "docs" / "architecture" / "6400-v1-design-lock.md"
  27. RECEIPT_SCHEMA = "prod2u-6400-formal-receipt-v1"
  28. def sha256_file(path: Path) -> str:
  29. digest = hashlib.sha256()
  30. with path.open("rb") as stream:
  31. for block in iter(lambda: stream.read(1024 * 1024), b""):
  32. digest.update(block)
  33. return digest.hexdigest()
  34. def canonical_sha256(value: Any) -> str:
  35. data = json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
  36. return hashlib.sha256(data.encode("utf-8")).hexdigest()
  37. def evidence_path(path: Path) -> str:
  38. resolved = path.resolve()
  39. try:
  40. return resolved.relative_to(ROOT.resolve()).as_posix()
  41. except ValueError:
  42. return resolved.as_posix()
  43. def formal_run_base() -> Path:
  44. configured = os.environ.get("PRODU2_FORMAL_RUN_BASE")
  45. base = Path(configured) if configured else (
  46. Path(os.environ.get("XDG_STATE_HOME", "/tmp")) / "prod2u" / "formal-runs"
  47. )
  48. resolved = base.expanduser().resolve()
  49. if resolved == ROOT.resolve() or ROOT.resolve() in resolved.parents:
  50. raise RuntimeError("formal run base must be outside the Git worktree")
  51. return resolved
  52. def run_text(argv: list[str], *, check: bool = True) -> str:
  53. result = subprocess.run(
  54. argv,
  55. cwd=ROOT,
  56. check=check,
  57. text=True,
  58. stdout=subprocess.PIPE,
  59. stderr=subprocess.STDOUT,
  60. )
  61. return result.stdout.strip()
  62. def repository_state() -> dict[str, Any]:
  63. commit = run_text(["git", "rev-parse", "HEAD"])
  64. branch = run_text(["git", "branch", "--show-current"])
  65. status_lines = [
  66. line for line in run_text(
  67. ["git", "status", "--porcelain=v1", "--untracked-files=all"]
  68. ).splitlines()
  69. if line
  70. ]
  71. return {
  72. "commit": commit,
  73. "branch": branch,
  74. "clean": not status_lines,
  75. "status_lines": status_lines,
  76. }
  77. def contract_binding() -> dict[str, Any]:
  78. paths = {
  79. "project_contract": PROJECT_CONTRACT,
  80. "profile_contract": PROFILE_CONTRACT,
  81. "source_manifest": SOURCE_MANIFEST,
  82. "design_lock": DESIGN_LOCK,
  83. "formal_manifest": MANIFEST,
  84. "solver_map": SOLVER_MAP,
  85. }
  86. return {
  87. name: {"path": path.relative_to(ROOT).as_posix(), "sha256": sha256_file(path)}
  88. for name, path in paths.items()
  89. }
  90. def source_binding() -> dict[str, Any]:
  91. manifest = json.loads(SOURCE_MANIFEST.read_text(encoding="utf-8"))
  92. entries: list[dict[str, str]] = []
  93. for relative in manifest["sources"]:
  94. path = ROOT / relative
  95. if not path.is_file():
  96. raise FileNotFoundError(f"source closure entry is missing: {relative}")
  97. entries.append({"path": relative, "sha256": sha256_file(path)})
  98. return {
  99. "manifest_sha256": sha256_file(SOURCE_MANIFEST),
  100. "source_count": len(entries),
  101. "sources": entries,
  102. "source_tree_sha256": canonical_sha256(entries),
  103. }
  104. def sby_files(sby_path: Path) -> list[Path]:
  105. files: list[Path] = []
  106. in_files = False
  107. for raw in sby_path.read_text(encoding="utf-8").splitlines():
  108. line = raw.strip()
  109. if line == "[files]":
  110. in_files = True
  111. continue
  112. if in_files and line.startswith("["):
  113. break
  114. if not in_files or not line or line.startswith("#"):
  115. continue
  116. source_token = line.split()[-1]
  117. source = (sby_path.parent / source_token).resolve()
  118. if not source.is_file():
  119. raise FileNotFoundError(f"formal input is missing: {source}")
  120. files.append(source)
  121. return files
  122. def formal_input_binding(targets: Iterable[dict[str, Any]]) -> dict[str, Any]:
  123. values: list[dict[str, Any]] = []
  124. for target in targets:
  125. sby_path = FORMAL_DIR / target["sby"]
  126. files = [
  127. {"path": path.relative_to(ROOT).as_posix(), "sha256": sha256_file(path)}
  128. for path in sby_files(sby_path)
  129. ]
  130. values.append({
  131. "name": target["name"],
  132. "mode": target["mode"],
  133. "depth": target["depth"],
  134. "tasks": target["tasks"],
  135. "sby": {
  136. "path": sby_path.relative_to(ROOT).as_posix(),
  137. "sha256": sha256_file(sby_path),
  138. },
  139. "files": files,
  140. "input_sha256": canonical_sha256({"sby": sha256_file(sby_path), "files": files}),
  141. })
  142. return {"targets": values, "sha256": canonical_sha256(values)}
  143. def executable_evidence(name: str, version_args: list[str], version_override: str = "") -> dict[str, Any]:
  144. executable = shutil.which(name)
  145. failures: list[str] = []
  146. output = ""
  147. if executable is None:
  148. return {
  149. "name": name,
  150. "path": "",
  151. "sha256": "0" * 64,
  152. "version": "",
  153. "status": "fail",
  154. "failures": [f"tool_missing:{name}"],
  155. }
  156. result = subprocess.run(
  157. [executable, *version_args],
  158. cwd=ROOT,
  159. check=False,
  160. text=True,
  161. stdout=subprocess.PIPE,
  162. stderr=subprocess.STDOUT,
  163. )
  164. output = result.stdout.strip()
  165. if result.returncode != 0:
  166. failures.append(f"tool_version_probe_failed:{name}:{result.returncode}")
  167. version = version_override or next((line.strip() for line in output.splitlines() if line.strip()), "")
  168. if not version:
  169. failures.append(f"tool_version_missing:{name}")
  170. return {
  171. "name": name,
  172. "path": executable,
  173. "sha256": sha256_file(Path(executable).resolve()),
  174. "version": version,
  175. "status": "pass" if not failures else "fail",
  176. "failures": failures,
  177. }
  178. def toolchain_evidence(environment: dict[str, Any]) -> dict[str, Any]:
  179. tools = [
  180. executable_evidence("sby", ["-h"], f"git:{environment['sby_commit']}"),
  181. executable_evidence("yosys", ["-V"]),
  182. executable_evidence("boolector", ["--version"]),
  183. executable_evidence("z3", ["--version"]),
  184. ]
  185. failures = [failure for tool in tools for failure in tool["failures"]]
  186. return {"status": "pass" if not failures else "fail", "tools": tools, "failures": failures}
  187. def compiled_property_ids(workdir: Path) -> tuple[list[str], list[str], str, list[str]]:
  188. design_json = workdir / "model" / "design.json"
  189. assertions: set[str] = set()
  190. covers: set[str] = set()
  191. failures: list[str] = []
  192. try:
  193. payload = json.loads(design_json.read_text(encoding="utf-8"))
  194. modules = payload.get("modules", [])
  195. for module in modules if isinstance(modules, list) else []:
  196. module_name = str(module.get("name", ""))
  197. for cell_sort in module.get("cell_sorts", []):
  198. sort_type = str(cell_sort.get("type", ""))
  199. for cell in cell_sort.get("cells", []):
  200. name = str(cell.get("name", ""))
  201. flavor = cell.get("parameters", {}).get("FLAVOR")
  202. if not module_name or not name:
  203. continue
  204. identifier = f"{module_name}.{name}"
  205. if sort_type == "$assert" or flavor == "assert":
  206. assertions.add(identifier)
  207. elif sort_type == "$cover" or flavor == "cover":
  208. covers.add(identifier)
  209. except (OSError, UnicodeError, json.JSONDecodeError, AttributeError, TypeError) as exc:
  210. failures.append(f"compiled_properties_unavailable:{type(exc).__name__}")
  211. design_hash = sha256_file(design_json) if design_json.is_file() else "0" * 64
  212. return sorted(assertions), sorted(covers), design_hash, failures
  213. def cover_hit_ids(workdir: Path) -> list[str]:
  214. pattern = re.compile(r"(?i)reached cover statement\s+(\S+)\s+at\s+\S+:\d+")
  215. hits: set[str] = set()
  216. for path in (workdir / "PASS", workdir / "logfile.txt"):
  217. if not path.is_file():
  218. continue
  219. for value in pattern.findall(path.read_text(encoding="utf-8", errors="replace")):
  220. if value.casefold() != "in":
  221. hits.add(value)
  222. return sorted(hits)
  223. def property_cell_ids(values: Iterable[str]) -> set[str]:
  224. """Normalize JNY module IDs and SBY hierarchical IDs to cell names."""
  225. normalized: set[str] = set()
  226. for value in values:
  227. positions = [value.rfind(marker) for marker in ("$assert$", "$cover$")]
  228. start = max(positions)
  229. normalized.add(value[start:] if start >= 0 else value)
  230. return normalized
  231. def relative_artifacts(workdir: Path, pattern: str) -> list[dict[str, str]]:
  232. return [
  233. {"path": evidence_path(path), "sha256": sha256_file(path)}
  234. for path in sorted(workdir.rglob(pattern))
  235. if path.is_file()
  236. ]
  237. def run_job(job: dict[str, Any], run_root: Path, timeout: int) -> dict[str, Any]:
  238. target = job["target"]
  239. task = job["task"]
  240. suffix = task if task != "default" else "default"
  241. workdir = run_root / "work" / target["name"] / suffix
  242. workdir.parent.mkdir(parents=True, exist_ok=True)
  243. sby_path = FORMAL_DIR / target["sby"]
  244. command = [shutil.which("sby") or "sby", "-f", "-d", str(workdir), sby_path.name]
  245. if task != "default":
  246. command.append(task)
  247. started = time.monotonic()
  248. timed_out = False
  249. process = subprocess.Popen(
  250. command,
  251. cwd=FORMAL_DIR,
  252. text=True,
  253. stdout=subprocess.PIPE,
  254. stderr=subprocess.STDOUT,
  255. start_new_session=True,
  256. )
  257. try:
  258. output, _ = process.communicate(timeout=timeout)
  259. returncode: int | None = process.returncode
  260. except subprocess.TimeoutExpired as exc:
  261. timed_out = True
  262. partial_output = exc.stdout.decode(errors="replace") if isinstance(exc.stdout, bytes) else (exc.stdout or "")
  263. if os.name == "posix":
  264. try:
  265. os.killpg(process.pid, signal.SIGTERM)
  266. except ProcessLookupError:
  267. pass
  268. else:
  269. process.terminate()
  270. try:
  271. final_output, _ = process.communicate(timeout=5)
  272. except subprocess.TimeoutExpired:
  273. if os.name == "posix":
  274. try:
  275. os.killpg(process.pid, signal.SIGKILL)
  276. except ProcessLookupError:
  277. pass
  278. else:
  279. process.kill()
  280. final_output, _ = process.communicate()
  281. # A retry of communicate() returns all captured output, including the
  282. # bytes reported by TimeoutExpired. Do not prepend partial_output and
  283. # duplicate the solver log.
  284. output = final_output if final_output is not None else partial_output
  285. returncode = process.returncode
  286. duration = time.monotonic() - started
  287. process_log = workdir.parent / f"{suffix}.process.log"
  288. process_log.write_text(output, encoding="utf-8")
  289. status_file = workdir / "status"
  290. status_raw = status_file.read_text(encoding="utf-8", errors="replace").strip() if status_file.is_file() else ""
  291. status_token = status_raw.split()[0].upper() if status_raw else "MISSING"
  292. logfile = workdir / "logfile.txt"
  293. log_text = logfile.read_text(encoding="utf-8", errors="replace") if logfile.is_file() else ""
  294. assertions, covers, design_hash, failures = compiled_property_ids(workdir)
  295. if timed_out:
  296. failures.append("timeout")
  297. if returncode != 0:
  298. failures.append(f"returncode:{returncode}")
  299. if status_token != "PASS":
  300. failures.append(f"status:{status_token}")
  301. if not (workdir / "PASS").is_file() or (workdir / "FAIL").exists():
  302. failures.append("pass_fail_marker_mismatch")
  303. if "DONE (PASS" not in log_text:
  304. failures.append("sby_done_pass_missing")
  305. if target["mode"] in {"prove", "bmc"}:
  306. if not assertions:
  307. failures.append("compiled_assertions_missing")
  308. if target["mode"] == "prove" and "successful proof by k-induction" not in log_text:
  309. failures.append("k_induction_evidence_missing")
  310. expected_solver = task
  311. if not re.search(rf"(?im)Solver:\s*{re.escape(expected_solver)}\b", log_text):
  312. failures.append(f"solver_observation_missing:{expected_solver}")
  313. elif target["mode"] == "cover":
  314. hits = cover_hit_ids(workdir)
  315. if not covers:
  316. failures.append("compiled_covers_missing")
  317. if property_cell_ids(hits) != property_cell_ids(covers):
  318. failures.append(f"cover_hit_set_mismatch:{len(hits)}/{len(covers)}")
  319. if not relative_artifacts(workdir, "*.vcd"):
  320. failures.append("cover_trace_missing")
  321. else:
  322. failures.append(f"unsupported_mode:{target['mode']}")
  323. return {
  324. "name": target["name"],
  325. "task": task,
  326. "mode": target["mode"],
  327. "depth": target["depth"],
  328. "status": "pass" if not failures else "fail",
  329. "returncode": returncode,
  330. "timed_out": timed_out,
  331. "duration_seconds": round(duration, 3),
  332. "command": command,
  333. "workdir": evidence_path(workdir),
  334. "process_log": {
  335. "path": evidence_path(process_log),
  336. "sha256": sha256_file(process_log),
  337. },
  338. "sby_log_sha256": sha256_file(logfile) if logfile.is_file() else "0" * 64,
  339. "compiled_design_sha256": design_hash,
  340. "compiled_assertion_count": len(assertions),
  341. "compiled_cover_count": len(covers),
  342. "compiled_assertion_ids": assertions,
  343. "compiled_cover_ids": covers,
  344. "cover_hit_ids": cover_hit_ids(workdir) if target["mode"] == "cover" else [],
  345. "traces": relative_artifacts(workdir, "*.vcd") if target["mode"] == "cover" else [],
  346. "evidence_failures": failures,
  347. }
  348. def validate_manifest(manifest: dict[str, Any]) -> None:
  349. properties = manifest.get("properties", [])
  350. ids = [entry.get("id") for entry in properties]
  351. if not ids or any(not isinstance(value, str) or not value for value in ids):
  352. raise ValueError("formal property IDs must be non-empty strings")
  353. if len(ids) != len(set(ids)):
  354. raise ValueError(f"formal property IDs must be unique, got {ids}")
  355. proof_targets = manifest.get("proof_targets", [])
  356. if not proof_targets:
  357. raise ValueError("proof_targets is empty")
  358. harnesses = {entry["sby"] for entry in proof_targets}
  359. if any(entry.get("harness") not in harnesses for entry in properties):
  360. raise ValueError("a formal property references a non-proof harness")
  361. for target in [*proof_targets, *manifest.get("cover_targets", [])]:
  362. sby_path = FORMAL_DIR / target["sby"]
  363. if not sby_path.is_file():
  364. raise FileNotFoundError(sby_path)
  365. text = sby_path.read_text(encoding="utf-8")
  366. if not re.search(rf"(?m)^mode\s+{re.escape(target['mode'])}\s*$", text):
  367. raise ValueError(f"mode mismatch in {sby_path.name}")
  368. if not re.search(rf"(?m)^depth\s+{target['depth']}\s*$", text):
  369. raise ValueError(f"depth mismatch in {sby_path.name}")
  370. def main(argv: list[str] | None = None) -> int:
  371. parser = argparse.ArgumentParser()
  372. parser.add_argument("--run-id")
  373. parser.add_argument("--jobs", type=int, default=1)
  374. parser.add_argument("--timeout-seconds", type=int, default=600)
  375. args = parser.parse_args(argv)
  376. if args.jobs != 1:
  377. parser.error("6400 formal permits exactly one heavy solver task at a time")
  378. timestamp = datetime.now(timezone.utc)
  379. run_id = args.run_id or timestamp.strftime("6400-formal-%Y%m%dT%H%M%SZ")
  380. if not re.fullmatch(r"[A-Za-z0-9._-]+", run_id):
  381. parser.error("run ID may contain only letters, digits, dot, underscore, and hyphen")
  382. run_root = formal_run_base() / run_id
  383. if run_root.exists():
  384. parser.error(f"run directory already exists: {run_root}")
  385. run_root.mkdir(parents=True)
  386. manifest = json.loads(MANIFEST.read_text(encoding="utf-8"))
  387. validate_manifest(manifest)
  388. repository = repository_state()
  389. if not repository["clean"]:
  390. raise RuntimeError("formal acceptance requires a clean worktree")
  391. environment = json.loads(ENVIRONMENT_RECEIPT.read_text(encoding="utf-8"))
  392. observed_digest = os.environ.get("PROD2U_CONTAINER_DIGEST", "")
  393. observed_image_id = os.environ.get("PROD2U_CONTAINER_IMAGE_ID", "")
  394. host_mounted = os.environ.get("PROD2U_FORMAL_HOST_MOUNTED", "") == "1"
  395. if host_mounted:
  396. distro = os.environ.get("WSL_DISTRO_NAME", "")
  397. suite_root = Path(os.environ.get("OSS_CAD_SUITE_ROOT", "")).resolve()
  398. expected_root = Path("/data/prod2u/oss-cad-suite/latest").resolve()
  399. if distro != "Debian13" or suite_root != expected_root:
  400. raise RuntimeError("host-mounted formal requires Debian13 and the pinned OSS CAD Suite path")
  401. if not (suite_root / "bin" / "sby").is_file():
  402. raise RuntimeError("host-mounted formal sby executable is missing")
  403. elif (observed_digest != environment.get("digest") or
  404. observed_image_id != environment.get("image_id")):
  405. raise RuntimeError("container identity environment does not match the pinned image receipt")
  406. tools = toolchain_evidence(environment)
  407. if tools["status"] != "pass":
  408. raise RuntimeError(f"formal toolchain evidence failed: {tools['failures']}")
  409. targets = [*manifest["proof_targets"], *manifest["cover_targets"]]
  410. formal_inputs = formal_input_binding(targets)
  411. jobs = [
  412. {"target": target, "task": task}
  413. for target in targets
  414. for task in (target["tasks"] or ["default"])
  415. ]
  416. with ThreadPoolExecutor(max_workers=max(1, min(args.jobs, len(jobs)))) as executor:
  417. results = list(executor.map(lambda job: run_job(job, run_root, args.timeout_seconds), jobs))
  418. result_by_target: dict[str, list[dict[str, Any]]] = {}
  419. for result in results:
  420. result_by_target.setdefault(result["name"], []).append(result)
  421. target_results = [
  422. {
  423. "name": target["name"],
  424. "sby": target["sby"],
  425. "mode": target["mode"],
  426. "depth": target["depth"],
  427. "status": "pass" if all(item["status"] == "pass" for item in result_by_target[target["name"]]) else "fail",
  428. "tasks": result_by_target[target["name"]],
  429. }
  430. for target in targets
  431. ]
  432. target_status = {entry["sby"]: entry["status"] for entry in target_results}
  433. result_status_by_name = {entry["name"]: entry["status"] for entry in target_results}
  434. witness_status = {
  435. property_id: result_status_by_name.get(target["name"], "fail")
  436. for target in manifest["cover_targets"]
  437. for property_id in target.get("witnesses", [])
  438. }
  439. properties = []
  440. for entry in manifest["properties"]:
  441. proof_status = target_status.get(entry["harness"], "fail")
  442. witness = witness_status.get(entry["id"], "not_required")
  443. properties.append({
  444. **entry,
  445. "proof_status": proof_status,
  446. "witness_status": witness,
  447. "status": "pass" if proof_status == "pass" and witness in {"pass", "not_required"} else "fail",
  448. })
  449. passed = all(entry["status"] == "pass" for entry in target_results)
  450. receipt = {
  451. "schema": RECEIPT_SCHEMA,
  452. "status": "pass" if passed else "fail",
  453. "verification_layer": "formal",
  454. "run_id": run_id,
  455. "started_utc": timestamp.isoformat(),
  456. "finished_utc": datetime.now(timezone.utc).isoformat(),
  457. "command": [sys.executable, str(Path(__file__).relative_to(ROOT)), *sys.argv[1:]],
  458. "repository": repository,
  459. "contracts": contract_binding(),
  460. "source_binding": source_binding(),
  461. "formal_inputs": formal_inputs,
  462. "container": {
  463. "status": "not_used_host_mounted" if host_mounted else "used",
  464. "image": None if host_mounted else environment["image"],
  465. "digest": None if host_mounted else observed_digest,
  466. "image_id": None if host_mounted else observed_image_id,
  467. "receipt_sha256": sha256_file(ENVIRONMENT_RECEIPT),
  468. "sby_commit": environment["sby_commit"],
  469. },
  470. "execution_environment": {
  471. "kind": "host-mounted-toolchain" if host_mounted else "container",
  472. "identity": (
  473. "WSL2 Debian13; OSS CAD Suite /data/prod2u/oss-cad-suite/latest"
  474. if host_mounted else environment["image"]
  475. ),
  476. },
  477. "toolchain": tools,
  478. "properties": properties,
  479. "targets": target_results,
  480. "applicable_bitstream": False,
  481. "bitstream_sha256": None,
  482. "physical_evidence": {
  483. "hardware": "not_run",
  484. "jtag": "not_run",
  485. "com": "not_run",
  486. "real_bmc": "not_run",
  487. "real_rs232": "not_run",
  488. "real_ttl_uart": "not_run",
  489. "real_thermal_performance": "not_run",
  490. },
  491. "authority_boundary": "Formal proves RTL properties and reachable witnesses only; it is not TD, bitstream, hardware, or thermal evidence.",
  492. }
  493. receipt_path = run_root / "formal-receipt.json"
  494. receipt_path.write_text(json.dumps(receipt, indent=2, sort_keys=True) + "\n", encoding="utf-8")
  495. print(json.dumps({
  496. "status": receipt["status"],
  497. "run_id": run_id,
  498. "receipt": evidence_path(receipt_path),
  499. "receipt_sha256": sha256_file(receipt_path),
  500. "target_count": len(target_results),
  501. "task_count": len(results),
  502. }, indent=2, sort_keys=True))
  503. return 0 if passed else 1
  504. if __name__ == "__main__":
  505. raise SystemExit(main())