"""Run and grade PhyCAD-Bench tasks.""" import argparse import ast import hashlib import json import os import re import subprocess import sys import tempfile from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait from decimal import Decimal from pathlib import Path from zipfile import ZIP_DEFLATED, ZipFile, ZipInfo from models import ModelTimeoutError, OpenAICompatibleAdapter ROOT = Path(__file__).resolve().parent TASKS = ROOT / "tasks" SOURCE_SHA256 = "e2bade23eb233f2210b152745c427708589574c83e4d6ccf764712481817e09b" SOURCE_ROOT = "cad-physics-sample/tasks" VERSION = "phycad-bench-v0.2" LEGACY_VERSION = "physics2cadbench-v0.2" OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1" SYSTEM_PROMPT = "You are editing a mechanical CAD solid to meet a physics performance target." TASK_FILES = ("instruction.txt", "setup.json", "start.py", "start.step", "simulate.py") RENDER_CODE = ( "import cadquery as cq, runpy, sys\n" "shape = runpy.run_path(sys.argv[1]).get('result')\n" "if isinstance(shape, cq.Workplane): shape = shape.val()\n" "if isinstance(shape, cq.Shape) and len(shape.Solids()) == 1: shape = shape.Solids()[0]\n" "if not isinstance(shape, cq.Shape) or shape.ShapeType() != 'Solid' " "or not shape.isValid() or len(shape.Solids()) != 1: " "raise ValueError('result must be one valid solid')\n" "cq.exporters.export(shape, sys.argv[2])\n" ) COMPARE_CODE = ( "import cadquery as cq, json, sys\n" "a = cq.importers.importStep(sys.argv[1]).val()\n" "b = cq.importers.importStep(sys.argv[2]).val()\n" "print(json.dumps({'a_minus_b_mm3': a.cut(b).Volume(), " "'b_minus_a_mm3': b.cut(a).Volume(), 'a_volume_mm3': a.Volume(), " "'b_volume_mm3': b.Volume()}))\n" ) def sha256(data: bytes) -> str: return hashlib.sha256(data).hexdigest() def zip_write(archive: ZipFile, name: str, data: bytes) -> None: info = ZipInfo(name, (1980, 1, 1, 0, 0, 0)) info.compress_type = ZIP_DEFLATED archive.writestr(info, data) def verified_sample(path: Path) -> ZipFile: if sha256(path.read_bytes()) != SOURCE_SHA256: raise ValueError("Source ZIP does not match the PR #94 CAD physics sample") archive = ZipFile(path) bad_member = archive.testzip() if bad_member: archive.close() raise ValueError(f"Corrupt source ZIP member: {bad_member}") return archive def task_ids() -> tuple[str, ...]: ids = tuple(sorted(path.name for path in TASKS.iterdir() if path.is_dir() and path.name.isdigit())) if not ids: raise ValueError(f"No numbered tasks found in {TASKS}") for task_id in ids: for name in TASK_FILES: if not (TASKS / task_id / name).is_file(): raise ValueError(f"Task {task_id} is missing {name}") return ids def task_file(task_id: str, name: str) -> bytes: if task_id not in task_ids() or name not in TASK_FILES: raise ValueError(f"Unknown task file: {task_id}/{name}") return (TASKS / task_id / name).read_bytes() def reference_file(archive: ZipFile, task_id: str, name: str) -> bytes: return archive.read(f"{SOURCE_ROOT}/{task_id}/{name}") def dataset_sha256() -> str: digest = hashlib.sha256() for task_id in task_ids(): for name in TASK_FILES: digest.update(f"{task_id}/{name}\0".encode()) digest.update(task_file(task_id, name)) return digest.hexdigest() def validate_candidate_source(code: str) -> None: if len(code.encode()) > 50_000: raise ValueError("CadQuery script exceeds 50 KB") tree = ast.parse(code) forbidden = {"open", "exec", "eval", "compile", "__import__", "globals", "locals", "vars", "getattr", "setattr", "delattr"} for node in ast.walk(tree): if isinstance(node, ast.Import) and any(alias.name not in ("cadquery", "math") for alias in node.names): raise ValueError("Only cadquery and math imports are allowed") if isinstance(node, ast.ImportFrom): raise ValueError("Use only plain cadquery and math imports") if isinstance(node, ast.Name) and node.id in forbidden: raise ValueError(f"Disallowed function: {node.id}") if isinstance(node, ast.Attribute) and node.attr.startswith("__"): raise ValueError("Dunder attributes are not allowed") def render_step(code: str, cad_python: Path) -> bytes: validate_candidate_source(code) in_container = os.environ.get("PHYCAD_BENCH_CONTAINER") == "1" if not in_container: if not Path("/usr/bin/sandbox-exec").is_file(): raise ValueError("Run inside the benchmark Docker image or on macOS with sandbox-exec") if cad_python.resolve().is_relative_to(Path("/Users")): raise ValueError("CadQuery Python must be outside /Users for sandbox isolation") with tempfile.TemporaryDirectory(prefix="orla-cad-candidate-") as directory: work = Path(directory) source = work / "candidate.py" output = work / "candidate.step" source.write_text(code) profile = ( '(version 1)(allow default)(deny network*)' '(deny file-read* (subpath "/Users"))' '(deny file-write* (subpath "/Users"))' ) env = {"HOME": directory, "XDG_CACHE_HOME": directory, "TMPDIR": directory, "PATH": "/opt/conda/envs/cad/bin:/usr/bin:/bin"} command = ([str(cad_python)] if in_container else ["/usr/bin/sandbox-exec", "-p", profile, str(cad_python)]) completed = subprocess.run( [*command, "-c", RENDER_CODE, str(source), str(output)], cwd=work, env=env, text=True, capture_output=True, timeout=90, check=False, ) if completed.returncode: raise ValueError(f"CadQuery execution failed: {completed.stderr[-1200:] or completed.stdout[-1200:]}") if not output.is_file() or output.stat().st_size > 10_000_000: raise ValueError("CadQuery did not produce a STEP solid under 10 MB") return output.read_bytes() def verify_start_geometry(cad_python: Path, original: bytes, reproduced: bytes) -> None: with tempfile.TemporaryDirectory(prefix="orla-cad-compare-") as directory: old = Path(directory) / "original.step" new = Path(directory) / "reproduced.step" old.write_bytes(original) new.write_bytes(reproduced) run = subprocess.run( [str(cad_python), "-c", COMPARE_CODE, str(old), str(new)], capture_output=True, text=True, timeout=90, check=False, ) if run.returncode: raise ValueError(f"Could not compare reconstructed STEP: {run.stderr[-1000:]}") result = json.loads(run.stdout) if (abs(result["a_volume_mm3"] - result["b_volume_mm3"]) > 1e-5 or result["a_minus_b_mm3"] > 1e-5 or result["b_minus_a_mm3"] > 1e-5): raise ValueError(f"Reconstructed source differs from original STEP: {result}") def grade_step(task_id: str, candidate_step: bytes, cad_python: Path, physics_python: Path) -> dict: result = {"task_id": task_id, "passed": False} result["candidate_step_sha256"] = sha256(candidate_step) with tempfile.TemporaryDirectory(prefix="orla-cad-physics-") as directory: work = Path(directory) (work / "before.step").write_bytes(task_file(task_id, "start.step")) for name in ("setup.json", "simulate.py"): (work / name).write_bytes(task_file(task_id, name)) (work / "after.step").write_bytes(candidate_step) env = {key: value for key, value in os.environ.items() if key != "OPENROUTER_API_KEY"} try: run = subprocess.run( [sys.executable, str(work / "simulate.py"), "--cad-python", str(cad_python), "--physics-python", str(physics_python)], cwd=work, env=env, capture_output=True, text=True, timeout=180, check=False, ) except subprocess.TimeoutExpired: return {**result, "stage": "physics", "error": "Physics run exceeded 180 seconds"} after_path = work / "after.results.json" if not after_path.is_file(): return {**result, "stage": "physics", "error": (run.stderr or run.stdout)[-1200:]} after = json.loads(after_path.read_text()) comparison = after.get("comparison_to_before", {}) return { **result, "stage": "graded", "passed": run.returncode == 0 and comparison.get("passed") is True, "checks": comparison.get("checks", {}), "improvement": {key: value for key, value in comparison.items() if key not in ("checks", "passed")}, "simulation_result": after.get("simulation_result"), "step_properties": after.get("step_properties"), } def grade_one(task_id: str, code: str, cad_python: Path, physics_python: Path) -> dict: try: candidate_step = render_step(code, cad_python) except (OSError, ValueError, SyntaxError, subprocess.TimeoutExpired) as exc: return {"task_id": task_id, "passed": False, "stage": "render", "error": str(exc)[-1200:]} return grade_step(task_id, candidate_step, cad_python, physics_python) def audit(args: argparse.Namespace) -> None: cad_python = Path(args.cad_python).expanduser().resolve() physics_python = Path(args.physics_python).expanduser().resolve() all_ids = task_ids() if args.task and args.task not in all_ids: raise ValueError(f"Unknown task: {args.task}") ids = (args.task,) if args.task else all_ids for task_id in ids: if not (TASKS / task_id / "solution.py").is_file(): raise ValueError(f"Task {task_id} is missing solution.py for audit") start = render_step(task_file(task_id, "start.py").decode(), cad_python) verify_start_geometry(cad_python, task_file(task_id, "start.step"), start) candidates = ( ("start.py", False, grade_step(task_id, start, cad_python, physics_python)), ("solution.py", True, grade_one( task_id, (TASKS / task_id / "solution.py").read_text(), cad_python, physics_python)), ) for name, expected_pass, report in candidates: if report.get("stage") != "graded" or report["passed"] is not expected_pass: raise ValueError( f"Task {task_id} {name} expected " f"{'PASS' if expected_pass else 'FAIL'}, got {report}" ) print(f"PASS: task {task_id} {name} " f"{'accepted' if expected_pass else 'rejected'}", flush=True) if args.reference_zip: with verified_sample(Path(args.reference_zip).expanduser().resolve()) as archive: for task_id in (task_id for task_id in ("001", "002", "003", "004") if task_id in ids): verify_start_geometry( cad_python, reference_file(archive, task_id, "before.step"), task_file(task_id, "start.step")) report = grade_step(task_id, reference_file(archive, task_id, "after.step"), cad_python, physics_python) if report.get("stage") != "graded" or report["passed"] is not True: raise ValueError(f"Task {task_id} source after.step expected PASS, got {report}") print(f"PASS: task {task_id} source after.step accepted", flush=True) noun = "task" if len(ids) == 1 else "tasks" print(f"PASS: {len(ids)} {noun} accepted gold scripts and rejected unchanged solids") def grade(args: argparse.Namespace) -> None: if args.task not in task_ids(): raise ValueError(f"Unknown task: {args.task}") code = Path(args.candidate).read_text() report = grade_one(args.task, code, Path(args.cad_python).resolve(), Path(args.physics_python).resolve()) Path(args.output).write_text(json.dumps(report, indent=2) + "\n") print(f"Task {args.task}: {'PASS' if report['passed'] else 'FAIL'} ({report.get('stage')})") print(f"Report: {args.output}") def extract_code(content: str) -> str: fences = re.findall(r"```(?:python|py)?\s*\n(.*?)```", content, flags=re.IGNORECASE | re.DOTALL) return (max(fences, key=len) if fences else content).strip() + "\n" def model_prompt(task_id: str) -> str: instruction = task_file(task_id, "instruction.txt").decode() setup = task_file(task_id, "setup.json").decode() start_code = task_file(task_id, "start.py").decode() step = task_file(task_id, "start.step").decode() return ( f"Task {task_id}. All lengths in millimeters.\n\n" f"Edit instruction:\n{instruction}\n\nPhysics setup:\n{setup}\n\n" f"Starting CadQuery script:\n```python\n{start_code}```\n\n" f"Starting STEP solid:\n```step\n{step}\n```\n\n" "Return a complete CadQuery 2.6.1 Python script. It must define `result` as one valid solid. " "Use only cadquery and math imports. Do not read or write files. " "Return only code, without commentary." ) def prompt_record(task_id: str) -> dict: prompt = model_prompt(task_id) return {"task_id": task_id, "prompt_sha256": sha256(prompt.encode()), "messages": [{"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": prompt}]} def export_prompts(args: argparse.Namespace) -> None: output = Path(args.output).expanduser().resolve() output.parent.mkdir(parents=True, exist_ok=True) with output.open("w") as stream: for task_id in task_ids(): stream.write(json.dumps(prompt_record(task_id)) + "\n") print(f"Exported {len(task_ids())} prompts: {output}") def grade_all(args: argparse.Namespace) -> None: submissions = Path(args.submissions).expanduser().resolve() if not submissions.is_dir(): raise ValueError(f"Submission folder does not exist: {submissions}") cad_python = Path(args.cad_python).expanduser().resolve() physics_python = Path(args.physics_python).expanduser().resolve() ids = task_ids() trials = [] for task_id in ids: source = submissions / f"{task_id}.py" if source.is_file(): code = source.read_text() result = grade_one(task_id, code, cad_python, physics_python) source_hash = sha256(code.encode()) else: result = {"task_id": task_id, "passed": False, "stage": "submission", "error": f"Missing {task_id}.py"} source_hash = None trials.append({"task_id": task_id, "submission_sha256": source_hash, "prompt_sha256": prompt_record(task_id)["prompt_sha256"], "grade": result}) print(f"Task {task_id}: {'PASS' if result['passed'] else 'FAIL'} ({result['stage']})", flush=True) passed = sum(trial["grade"]["passed"] for trial in trials) report = {"version": VERSION, "dataset_sha256": dataset_sha256(), "model": args.model, "task_count": len(ids), "passed": passed, "success_rate": passed / len(ids), "trials": trials} output = Path(args.output).expanduser().resolve() output.parent.mkdir(parents=True, exist_ok=True) temporary = output.with_name(output.name + ".tmp") temporary.write_text(json.dumps(report, indent=2) + "\n") os.replace(temporary, output) print(f"Overall: {passed}/{len(ids)} ({report['success_rate']:.1%})") print(f"Report: {output}") def usage_totals(trials: list[dict]) -> dict: fields = ("prompt_tokens", "completion_tokens", "total_tokens", "cost") totals = {} reported_trials = {} for field in fields: values = [(trial.get("usage") or {}).get(field) for trial in trials] values = [value for value in values if isinstance(value, (int, float))] reported_trials[field] = len(values) totals[field] = (float(sum(Decimal(str(value)) for value in values)) if field == "cost" else sum(values)) if values else None return {**totals, "reported_trials": reported_trials} def save_report(path: Path, report: dict) -> None: report["usage_totals"] = usage_totals(report["trials"]) path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_name(path.name + ".tmp") temporary.write_text(json.dumps(report, indent=2) + "\n") os.replace(temporary, path) scripts_zip = path.with_name(path.stem + ".scripts.zip") with ZipFile(scripts_zip.with_name(scripts_zip.name + ".tmp"), "w") as archive: for trial in report["trials"]: name = f"task-{trial['task_id']}-repeat-{trial['repeat']}.py" zip_write(archive, name, trial["cadquery_script"].encode()) os.replace(scripts_zip.with_name(scripts_zip.name + ".tmp"), scripts_zip) def run_model(args: argparse.Namespace) -> None: base_url = OPENROUTER_BASE_URL if args.command == "run-openrouter" else args.base_url api_key_env = "OPENROUTER_API_KEY" if args.command == "run-openrouter" else args.api_key_env adapter = OpenAICompatibleAdapter(base_url, api_key_env) request_config = {args.token_field: args.max_output_tokens} if args.reasoning_effort: request_config["reasoning_effort"] = args.reasoning_effort output = Path(args.output).expanduser().resolve() task_hash = dataset_sha256() ids = task_ids() run_config = {"adapter": "openai-compatible", "base_url": adapter.base_url, "api_key_env": api_key_env, "model_requested": args.model, "repeats": args.repeats, "request_config": request_config, "timeout_s": args.timeout} if output.exists(): report = json.loads(output.read_text()) if (report.get("version") not in (VERSION, LEGACY_VERSION) or report.get("dataset_sha256") != task_hash or any(report.get(key) != value for key, value in run_config.items())): raise ValueError("Existing report belongs to a different run configuration") report["version"] = VERSION else: report = {"version": VERSION, "dataset_sha256": task_hash, **run_config, "task_count": len(ids) * args.repeats, "trials": []} done = {(trial["task_id"], trial["repeat"]) for trial in report["trials"]} if len(done) != len(report["trials"]): raise ValueError("Existing report has duplicate trials") cad_python = Path(args.cad_python).expanduser().resolve() physics_python = Path(args.physics_python).expanduser().resolve() remaining = iter((task_id, repeat) for repeat in range(1, args.repeats + 1) for task_id in ids if (task_id, repeat) not in done) with ThreadPoolExecutor(max_workers=args.parallel_requests) as executor: pending = {} def submit_next() -> bool: try: task_id, repeat = next(remaining) except StopIteration: return False prompt = prompt_record(task_id) future = executor.submit( adapter.generate, args.model, prompt["messages"], request_config, args.timeout) pending[future] = (task_id, repeat, prompt["prompt_sha256"]) return True while len(pending) < args.parallel_requests and submit_next(): pass provider_error = None while pending: completed, _ = wait(pending, return_when=FIRST_COMPLETED) ready = [] for future in completed: task_id, repeat, prompt_hash = pending.pop(future) try: response = future.result() except ModelTimeoutError as exc: ready.append((task_id, repeat, prompt_hash, None, exc)) except Exception as exc: if provider_error is None: provider_error = exc else: ready.append((task_id, repeat, prompt_hash, response, None)) if provider_error is None: while len(pending) < args.parallel_requests and submit_next(): pass for task_id, repeat, prompt_hash, response, timeout_error in sorted( ready, key=lambda item: (item[1], item[0])): message = response.text if response else "" code = extract_code(message) if response else "" if timeout_error: grade_result = {"task_id": task_id, "passed": False, "stage": "provider", "error": str(timeout_error)} elif response.finish_reason == "content_filter": grade_result = {"task_id": task_id, "passed": False, "stage": "provider", "error": "Provider stopped the response before complete code"} else: grade_result = grade_one(task_id, code, cad_python, physics_python) report["trials"].append({ "task_id": task_id, "repeat": repeat, "cadquery_script": code, "raw_response": message, "prompt_sha256": prompt_hash, "served_model": response.served_model if response else None, "response_id": response.response_id if response else None, "finish_reason": response.finish_reason if response else None, "usage": response.usage if response else None, "grade": grade_result, }) report["trials"].sort(key=lambda trial: (trial["repeat"], trial["task_id"])) report["completed_trials"] = len(report["trials"]) report["passed"] = sum(t["grade"]["passed"] for t in report["trials"]) report["success_rate"] = (report["passed"] / report["task_count"] if report["completed_trials"] == report["task_count"] else None) save_report(output, report) print(f"Task {task_id} repeat {repeat}: {'PASS' if grade_result['passed'] else 'FAIL'} ({grade_result.get('stage')})", flush=True) if provider_error is not None: raise provider_error print(f"Overall: {report['passed']}/{report['task_count']} ({report['success_rate']:.1%})") print(f"Saved run: {output}") def main() -> None: parser = argparse.ArgumentParser(description=__doc__) commands = parser.add_subparsers(dest="command", required=True) commands.add_parser("list", help="List available task IDs") prompts_parser = commands.add_parser("export-prompts", help="Write provider-independent prompts as JSONL") prompts_parser.add_argument("--output", required=True) grade_parser = commands.add_parser("grade", help="Grade one CadQuery script") grade_parser.add_argument("--task", required=True) grade_parser.add_argument("--candidate", required=True) grade_parser.add_argument("--cad-python", default=os.environ.get("CAD_PYTHON")) grade_parser.add_argument("--physics-python", default=os.environ.get("PHYSICS_PYTHON")) grade_parser.add_argument("--output", required=True) all_parser = commands.add_parser("grade-all", help="Grade one numbered Python script per task") all_parser.add_argument("--submissions", required=True) all_parser.add_argument("--model", help="Model name to record in the report") all_parser.add_argument("--cad-python", default=os.environ.get("CAD_PYTHON")) all_parser.add_argument("--physics-python", default=os.environ.get("PHYSICS_PYTHON")) all_parser.add_argument("--output", required=True) audit_parser = commands.add_parser("audit", help="Check each task's gold script and unchanged solid") audit_parser.add_argument("--task", help="Check only one numbered task") audit_parser.add_argument("--reference-zip", help="Also check the original four source STEP edits") audit_parser.add_argument("--cad-python", default=os.environ.get("CAD_PYTHON")) audit_parser.add_argument("--physics-python", default=os.environ.get("PHYSICS_PYTHON")) for name, help_text, token_field in ( ("run", "Run an OpenAI-compatible local or cloud model", "max_tokens"), ("run-openrouter", "Run an OpenRouter model (convenience alias)", "max_completion_tokens"), ): run_parser = commands.add_parser(name, help=help_text) if name == "run": run_parser.add_argument("--base-url", required=True, help="API base URL ending at /v1 or equivalent") run_parser.add_argument("--api-key-env", help="Environment variable containing the API key") run_parser.add_argument("--model", required=True) run_parser.add_argument("--repeats", type=int, default=1) run_parser.add_argument("--parallel-requests", type=int, default=1, help="Maximum simultaneous model requests (1 to 16)") run_parser.add_argument("--max-output-tokens", type=int, default=4096) run_parser.add_argument("--token-field", choices=("max_tokens", "max_completion_tokens"), default=token_field) run_parser.add_argument("--reasoning-effort", choices=("low", "medium", "high")) run_parser.add_argument("--timeout", type=int, default=180, help="Seconds allowed for one model response") run_parser.add_argument("--cad-python", default=os.environ.get("CAD_PYTHON")) run_parser.add_argument("--physics-python", default=os.environ.get("PHYSICS_PYTHON")) run_parser.add_argument("--output", required=True) args = parser.parse_args() try: if args.command == "list": for task_id in task_ids(): print(f"{task_id}: {task_file(task_id, 'instruction.txt').decode().strip()}") return if args.command == "export-prompts": export_prompts(args) return if not args.cad_python or not args.physics_python: raise ValueError("Pass --cad-python and --physics-python, or set CAD_PYTHON and PHYSICS_PYTHON") if args.command == "grade": grade(args) elif args.command == "grade-all": grade_all(args) elif args.command == "audit": audit(args) elif args.command in ("run", "run-openrouter"): if not 1 <= args.repeats <= 3: raise ValueError("Repeats must be between 1 and 3") if not 1 <= args.parallel_requests <= 16: raise ValueError("--parallel-requests must be between 1 and 16") if args.max_output_tokens < 1 or args.timeout < 1: raise ValueError("--max-output-tokens and --timeout must be positive") run_model(args) except (OSError, ValueError, SyntaxError, KeyError, IndexError, json.JSONDecodeError, subprocess.TimeoutExpired) as exc: parser.exit(1, f"FAIL: {exc}\n") if __name__ == "__main__": main()