from __future__ import annotations import argparse import json import shutil import socket import subprocess import sys import time import urllib.request from datetime import datetime, timezone from pathlib import Path from typing import Any SOURCE_HEAD = "59cc6c2fd7ebd7ef7925cad552a01a4b8b6e4d5e" def write_json(path: Path, payload: Any) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(payload, indent=2, sort_keys=True, default=str) + "\n", encoding="utf-8") def truncate(text: str, limit: int = 4000) -> str: return text[-limit:] if len(text) > limit else text def ignore_modern(dir_path: str, names: list[str]) -> set[str]: ignored = {"reports", "final_proof", ".dettools_checkpoints", "__pycache__"} ignored.update(name for name in names if name.endswith(".pyc")) ignored.update(name for name in names if name.startswith(".dettools_")) ignored.update(name for name in names if name == "carddemo.sqlite") return ignored & set(names) def ignore_source(dir_path: str, names: list[str]) -> set[str]: ignored = {".git", "__pycache__"} ignored.update(name for name in names if name.endswith(".pyc")) return ignored & set(names) def copy_clean_workspace(modern_root: Path, source_root: Path, scratch_root: Path) -> dict[str, str]: if scratch_root.exists(): raise SystemExit(f"scratch root already exists; choose another path: {scratch_root}") source_copy = scratch_root / "source" modern_copy = scratch_root / "modern_carddemo" scratch_root.mkdir(parents=True) shutil.copytree(source_root, source_copy, ignore=ignore_source) shutil.copytree(modern_root, modern_copy, ignore=ignore_modern) return {"scratch_root": str(scratch_root), "source_copy": str(source_copy), "modern_copy": str(modern_copy)} def run_command(name: str, command: list[str], cwd: Path, timeout: int = 120) -> dict[str, Any]: started = time.monotonic() result = subprocess.run(command, cwd=cwd, capture_output=True, text=True, timeout=timeout) return { "name": name, "command": " ".join(command), "cwd": str(cwd), "returncode": result.returncode, "passed": result.returncode == 0, "duration_seconds": round(time.monotonic() - started, 3), "stdout_tail": truncate(result.stdout), "stderr_tail": truncate(result.stderr), } def free_port(start: int = 8091, stop: int = 8999) -> int: for port in range(start, stop + 1): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: sock.settimeout(0.1) if sock.connect_ex(("127.0.0.1", port)) != 0: return port raise SystemExit("no free local port found for clean server smoke") def fetch_json(url: str, timeout: float = 5.0) -> Any: with urllib.request.urlopen(url, timeout=timeout) as response: return json.loads(response.read().decode("utf-8")) def wait_for_server(port: int, timeout_seconds: float = 10.0) -> None: deadline = time.monotonic() + timeout_seconds last_error = "" while time.monotonic() < deadline: try: fetch_json(f"http://127.0.0.1:{port}/api/health", timeout=1.0) return except Exception as exc: # noqa: BLE001 last_error = str(exc) time.sleep(0.25) raise RuntimeError(f"server did not become healthy on port {port}: {last_error}") def run_server_smoke(modern_copy: Path, port: int) -> dict[str, Any]: out_path = modern_copy / "server_smoke.out.log" err_path = modern_copy / "server_smoke.err.log" with out_path.open("w", encoding="utf-8") as stdout, err_path.open("w", encoding="utf-8") as stderr: proc = subprocess.Popen( [ sys.executable, "-m", "carddemo.cli", "serve", "--source-root", "..\\source", "--db-path", ".\\carddemo.sqlite", "--port", str(port), ], cwd=modern_copy, stdout=stdout, stderr=stderr, text=True, ) try: wait_for_server(port) api_smoke = { "health": fetch_json(f"http://127.0.0.1:{port}/api/health"), "summary": fetch_json(f"http://127.0.0.1:{port}/api/summary"), "mq_system_date": fetch_json( f"http://127.0.0.1:{port}/api/mq/system-date?now=2026-05-23T11:12:13" ), "batch_resource_setup_tranidx": fetch_json( f"http://127.0.0.1:{port}/api/batch/resource-setup?job=TRANIDX" ), } checks = { "health_ok": api_smoke["health"].get("status") == "ok", "summary_customers_50": api_smoke["summary"]["counts"]["customers"] == 50, "mq_date_reply": api_smoke["mq_system_date"]["reply_message"] == "SYSTEM DATE : 05-23-2026SYSTEM TIME : 11:12:13", "tranidx_key_contract": api_smoke["batch_resource_setup_tranidx"]["alternate_index"]["keys"] == {"length": 26, "offset": 304}, } return { "passed": all(checks.values()), "server_command": f"{sys.executable} -m carddemo.cli serve --source-root ..\\source --db-path .\\carddemo.sqlite --port {port}", "port": port, "checks": checks, "api_smoke": api_smoke, "stdout_log": str(out_path), "stderr_log": str(err_path), } finally: proc.terminate() try: proc.wait(timeout=5) except subprocess.TimeoutExpired: proc.kill() proc.wait(timeout=5) def main() -> None: parser = argparse.ArgumentParser(description="Verify CardDemo reproducibility from a clean copied workspace") parser.add_argument("--modern-root", type=Path, default=Path(__file__).resolve().parents[1]) parser.add_argument("--source-root", type=Path, default=Path(__file__).resolve().parents[2] / "source") parser.add_argument("--scratch-root", type=Path, default=None) parser.add_argument("--out-path", type=Path, default=None) parser.add_argument("--source-head", default=SOURCE_HEAD) args = parser.parse_args() modern_root = args.modern_root.resolve() source_root = args.source_root.resolve() timestamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ") scratch_root = (args.scratch_root or modern_root.parent / f"clean_repro_{timestamp}").resolve() out_path = (args.out_path or modern_root / "final_proof" / "CLEAN_REPRO_VERIFICATION.json").resolve() copied = copy_clean_workspace(modern_root, source_root, scratch_root) modern_copy = Path(copied["modern_copy"]) port = free_port() commands = [ run_command( "setup", [sys.executable, "-m", "carddemo.cli", "init-db", "--source-root", "..\\source", "--db-path", ".\\carddemo.sqlite"], modern_copy, ), run_command("test", [sys.executable, "-m", "unittest", "discover", "-s", "tests"], modern_copy, timeout=180), run_command( "receipt", [ sys.executable, "tools\\generate_receipts.py", "--source-root", "..\\source", "--db-path", ".\\carddemo.sqlite", "--out-dir", ".\\reports", ], modern_copy, timeout=180, ), run_command( "static_oracle_replay", [ sys.executable, "tools\\replay_static_oracles.py", "--source-root", "..\\source", "--out-dir", ".\\reports", "--source-head", args.source_head, ], modern_copy, timeout=180, ), run_command( "a_grade_promotion", [ sys.executable, "tools\\evaluate_a_grade_promotion.py", "--source-root", "..\\source", "--out-dir", ".\\final_proof", ], modern_copy, timeout=180, ), run_command( "no_cost_confidence", [ sys.executable, "tools\\build_no_cost_confidence.py", "--source-root", "..\\source", "--out-dir", ".\\final_proof", ], modern_copy, timeout=180, ), run_command( "package_final_proof", [ sys.executable, "tools\\package_final_proof.py", "--source-root", "..\\source", ], modern_copy, timeout=180, ), ] server_smoke = run_server_smoke(modern_copy, port) report = { "verification_version": "carddemo_clean_repro_verification_v0", "generated_utc": datetime.now(timezone.utc).replace(microsecond=0).isoformat(), "source_head": args.source_head, "copied_workspace": copied, "server_port": port, "commands": commands, "api_smoke_passed": server_smoke["passed"], "api_smoke": server_smoke["api_smoke"], "server_smoke": { "passed": server_smoke["passed"], "server_command": server_smoke["server_command"], "checks": server_smoke["checks"], "stdout_log": server_smoke["stdout_log"], "stderr_log": server_smoke["stderr_log"], }, } report["passed"] = all(row["passed"] for row in commands) and server_smoke["passed"] write_json(out_path, report) print(json.dumps({"passed": report["passed"], "out_path": str(out_path), "scratch_root": str(scratch_root)}, indent=2)) if not report["passed"]: raise SystemExit(1) if __name__ == "__main__": main()