"""Immutable, resource-bounded phase-three scientific run and presentation.""" 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 sha(path): return hashlib.sha256(path.read_bytes()).hexdigest() def now(): return dt.datetime.now(dt.timezone.utc).isoformat() def main(run_id): base=Path(__file__).resolve().parent run=base/"results"/run_id if run.exists(): raise FileExistsError("Refusing to overwrite a run") config=json.loads((base/"phase3_config.json").read_text()) required=("schedule_benchmark.py","biased_policy.py","plot_phase3.py","summarize_phase3.py", "schedule_math.md","biased_math.md","PROTOCOL.md","phase3_config.json") for name in required: if not (base/name).is_file(): raise FileNotFoundError(name) run.mkdir(parents=True) source=run/"source" source.mkdir() for path in sorted(base.glob("*.py")): shutil.copy2(path,source/path.name) shutil.copytree(base/"vendor",source/"vendor",ignore=shutil.ignore_patterns("__pycache__")) shutil.copytree(base/"inputs",run/"inputs") (run/"docs").mkdir() for name in ("schedule_math.md","biased_math.md"): shutil.copy2(base/name,run/"docs"/name) for name in ("PROTOCOL.md","phase3_config.json"): shutil.copy2(base/name,run/name) (run/"logs").mkdir() (run/"figures").mkdir() started=time.monotonic() status={"run_id":run_id,"status":"RUNNING","started_utc":now(), "python":sys.version,"platform":platform.platform(), "packages":{p:importlib.metadata.version(p) for p in ("numpy","scipy","matplotlib")}, "config_sha256":sha(run/"phase3_config.json"), "source_sha256":{str(p.relative_to(source)):sha(p) for p in sorted(source.rglob("*.py"))}, "input_sha256":{p.name:sha(p) for p in sorted((run/"inputs").glob("*.json"))}, "stages":[]} def save(): (run/"status.json").write_text(json.dumps(status,indent=2)+"\n") 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(): cap=int(config["address_space_gib"])*1024**3 resource.setrlimit(resource.RLIMIT_AS,(cap,cap)) def stage(name,arguments,seconds,allow_partial=False): row={"stage":name,"started_utc":now(),"timeout_seconds":seconds,"status":"RUNNING"} status["stages"].append(row) save() t=time.monotonic() print("START "+name,flush=True) try: with (run/"logs"/(name+".log")).open("w") as log: completed=subprocess.run([sys.executable,str(source/arguments[0]),*arguments[1:]], env=env,stdout=log,stderr=subprocess.STDOUT,timeout=seconds,preexec_fn=limits) row.update(returncode=completed.returncode, status="COMPLETE" if completed.returncode==0 else "PARTIAL" if allow_partial else "FAILED") if completed.returncode and not allow_partial: raise RuntimeError(f"{name} failed; inspect retained log") except Exception as error: row.update(status="FAILED",error=repr(error)) raise finally: row["runtime_seconds"]=time.monotonic()-t save() print(f"END {name}: {row['status']}",flush=True) save() try: stage("schedules",["schedule_benchmark.py","--witnesses",str(run/"inputs"/"witnesses.json"), "--certificates",str(run/"inputs"/"certificates.json"),"--output",str(run/"schedules.json"), "--self-test"],config["schedule_stage_seconds"]) stage("biased",["biased_policy.py","--config",str(run/"phase3_config.json"), "--output",str(run/"biased_results.json")],config["biased_stage_seconds"],allow_partial=True) stage("summary",["summarize_phase3.py","--run-dir",str(run)],90) stage("plots",["plot_phase3.py","--run-dir",str(run)],120) bias=json.loads((run/"biased_results.json").read_text()) status["status"]="COMPLETE" if bias["status"]=="complete" else "COMPLETE_WITH_MISSING_BIASED_CASES" except Exception as error: status.update(status="FAILED",error=repr(error)) raise finally: status.update(finished_utc=now(),runtime_seconds=time.monotonic()-started) save() if __name__=="__main__": parser=argparse.ArgumentParser() parser.add_argument("--run-id",required=True) main(parser.parse_args().run_id)