"""Versioned, single-threaded CPU study runner with fail-fast validation.""" from __future__ import annotations import argparse import datetime as dt import hashlib import importlib.metadata import json import os from pathlib import Path import platform import resource import shutil import subprocess import sys import time def digest(path): return hashlib.sha256(path.read_bytes()).hexdigest() def main(): parser = argparse.ArgumentParser() parser.add_argument("--config", type=Path, required=True) parser.add_argument("--run-id", required=True) args = parser.parse_args() root = Path(__file__).resolve().parents[1] if not args.run_id.startswith("run-") or "/" in args.run_id or ".." in args.run_id: raise ValueError("Unsafe run id") run_dir = root / "results" / args.run_id run_dir.mkdir(parents=True, exist_ok=False) for name in ("logs", "source", "figures"): (run_dir/name).mkdir() shutil.copy2(args.config, run_dir/"config.json") source_files = sorted((root/"src").glob("*.py")) for file in source_files: shutil.copy2(file,run_dir/"source"/file.name) if (root/"PROTOCOL.md").exists(): shutil.copy2(root/"PROTOCOL.md",run_dir/"PROTOCOL.md") if (root/"docs").exists(): shutil.copytree(root/"docs",run_dir/"docs") versions = {name:importlib.metadata.version(name) for name in ("numpy","scipy","matplotlib")} status = {"run_id":args.run_id,"status":"RUNNING","started_utc":dt.datetime.now(dt.timezone.utc).isoformat(), "python":sys.version,"platform":platform.platform(),"packages":versions, "config_sha256":digest(run_dir/"config.json"), "source_sha256":{file.name:digest(file) for file in source_files},"stages":[]} def save(): tmp = run_dir/"status.pending.json" tmp.write_text(json.dumps(status,indent=2,allow_nan=False)+"\n") tmp.replace(run_dir/"status.json") save() env = os.environ.copy() env.update(OMP_NUM_THREADS="1",OPENBLAS_NUM_THREADS="1",MKL_NUM_THREADS="1",NUMEXPR_NUM_THREADS="1",MPLBACKEND="Agg",PYTHONUNBUFFERED="1") def limits(): resource.setrlimit(resource.RLIMIT_AS,(8*1024**3,8*1024**3)) stages = [("regression","verify_main_examples.py",None), ("e1","e1_model_execution.py","e1.json"), ("e2","e2_pilot.py","e2.json"), ("e3","e3_policy_lp.py","e3.json"), ("plots","plot_results.py",None)] overall = time.monotonic() try: for name,script,output in stages: row = {"stage":name,"status":"RUNNING"} status["stages"].append(row) save() command = [sys.executable,str(run_dir/"source"/script)] if output: command += ["--config",str(run_dir/"config.json"),"--output",str(run_dir/output)] if name == "plots": command += ["--run-dir",str(run_dir)] t = time.monotonic() print(f"START {name}",flush=True) with (run_dir/"logs"/(name+".log")).open("w") as log: result = subprocess.run(command,stdout=log,stderr=subprocess.STDOUT,env=env, timeout=max(1,2700-(time.monotonic()-overall)),preexec_fn=limits) row.update(returncode=result.returncode,runtime_seconds=time.monotonic()-t, status="COMPLETE" if result.returncode==0 else "FAILED") save() print(f"END {name}: {row['status']} ({row['runtime_seconds']:.1f}s)",flush=True) if result.returncode: raise RuntimeError(f"Stage {name} failed; retained logs in {run_dir}") status["status"]="COMPLETE" except Exception as exc: status["status"]="FAILED" status["error"]=repr(exc) if status["stages"] and status["stages"][-1]["status"]=="RUNNING": status["stages"][-1]["status"]="FAILED" raise finally: status["finished_utc"]=dt.datetime.now(dt.timezone.utc).isoformat() status["runtime_seconds"]=time.monotonic()-overall save() if __name__ == "__main__": main()