#!/usr/bin/env python3 """CPU-only repair of audited saved grades. Never sends candidate feedback or model requests.""" from __future__ import annotations import argparse from datetime import datetime, timezone import json from pathlib import Path import shutil import subprocess import sys import tempfile try: from . import programbench_adapter as benchmark except ImportError: import programbench_adapter as benchmark CALIBRATION_SHA256 = "4560d07154e68c0ae4c55529fd84a68c0dab25a4ad5110f2448295b2ac2b137f" MASK_SHA256 = "070d17aeed8a78489fbc6356f57b269078125f4b75062f077da3b03b7a4b672c" AUDITED_MODULE_SHA256 = "805b5a6c38d7c0211bb9c09c31a44d52192e8a39ab46eeee106a7d6975e93fd5" APPROVED = { "xsv-single-r1": { "eval_sha256": "4c17aaf64d003c90f67d691b4a8ef130d46e65dfe47f08ec7e1ba6b657847254", "summary_sha256": "9e07b225237f0a3c17b582e1b2e12c38767942eb321bd7de8bd8128fd2654b20", "submission_sha256": "4884753a13cc2439e6173b18a58a21d43a2d1c0e872c4b95b66c3fc6a6a417e5", "not_run_count": 62, "passed": 351, "extra_count": 0, }, "xsv-peers-r1": { "eval_sha256": "b2cc654c2978842f070766d6cb42ccfdb7fe8eafcac800964977786d6bae8ef7", "summary_sha256": "59dd3eeeb6503028cf495521da237fca423a6cc8e0356041118b8c4fcee0a10f", "submission_sha256": "6a57c9563cbe40b27926a01577baa0a3184403d00ffe7ebf3bf6523e4cb54a34", "not_run_count": 62, "passed": 122, "extra_count": 0, }, "xsv-async-r1": { "eval_sha256": "4f7c282e7af4401b5c9abea565964840d835fdf7d19ff1681a6a425b813d86de", "summary_sha256": "881583faf0325ff9d637d805b188a732d97b91c2cba4fcd1b5ff6088f9b7b144", "submission_sha256": "ba9515767912f514f712c971f8f10168cae27b6ac5d10ed9ca6fd353bd67f517", "not_run_count": 68, "passed": 95, "extra_count": 1, }, } def recover_candidate_summary(summary, result, mask, audit): """Reclassify only a separately hash-audited candidate collection failure.""" prefix = "private-audit-branch/eval.tests.private_dispatch" if summary.get("reference") or summary.get("complete") or any(summary.get(key) for key in ( "error_code", "branch_error_count", "system_error_count", "missing_test_count")): raise ValueError("Candidate collection recovery cannot ignore infrastructure failure") if len(mask) != len(set(mask)) or len(mask) != summary["expected_test_count"]: raise ValueError("Official mask is inconsistent") tests = {f"{test['branch']}/{test['name']}": test for test in result["test_results"]} if set(mask) - tests.keys(): raise ValueError("Official mask keys are missing") omitted = [tests[name] for name in mask if tests[name]["status"] == "not_run"] if (len(omitted) != audit["not_run_count"] or summary["not_run_count"] != len(omitted) or any(not f"{t['branch']}/{t['name']}".startswith(prefix + ".") or t.get("extra", {}).get("error_code") != "missing_from_junit_xml" for t in omitted)): raise ValueError("Omissions differ from the audited candidate-dependent collection") if not audit["extra_count"] and any("[" not in t["name"] for t in omitted): raise ValueError("Expected only dynamically parameterized omissions") errors = [t for t in result["test_results"] if t["status"] in {"error", "system_error"}] if (len(errors) != audit["extra_count"] or summary["warning_count"] != audit["extra_count"] or summary["unexpected_test_count"] != audit["extra_count"] or summary["test_count"] != len(mask) + audit["extra_count"]): raise ValueError("Unexpected evaluator diagnostic") for error in errors: extra = error.get("extra", {}) if (f"{error['branch']}/{error['name']}" != prefix or extra.get("message") != "collection failure" or not all(text in extra.get("text", "") for text in ("/workspace/executable", "--help", "assert 1 == 0"))): raise ValueError("Collection error is not the audited candidate --help failure") passed = sum(tests[name]["status"] == "passed" for name in mask) if passed != audit["passed"] or passed != summary["passed"]: raise ValueError("Pass count differs from the audited observation") score = passed / len(mask) return {**summary, "score": score, "analysis_score": score, "test_count": len(mask), "valid": True, "complete": False, "raw_complete": False, "scoring_status": "candidate_collection_failed", "recovery": { "policy": "audited_candidate_collection_fixed_official_mask", "raw_score": summary["score"], "raw_test_count": summary["test_count"], "raw_warning_count": summary["warning_count"], "raw_unexpected_test_count": summary["unexpected_test_count"], "omitted_expected_tests_counted_failed": len(omitted), "synthetic_collection_error_records_excluded": audit["extra_count"], "audited_module_sha256": AUDITED_MODULE_SHA256, **{key: value for key, value in audit.items() if key.endswith("sha256")}}} def load(path): return json.loads(Path(path).read_text()) def archive_original(root, path): saved = root / "recovery" / "originals" / path.relative_to(root) saved.parent.mkdir(parents=True, exist_ok=True) digest_path = saved.with_name(saved.name + ".archive-sha256.json") if saved.exists(): actual = benchmark.sha256(saved) if digest_path.exists(): expected = load(digest_path)["sha256"] else: # An interrupted first archive can leave a complete renamed file # before its digest is saved. Only the still-identical source proves it. expected = benchmark.sha256(path) if actual != expected: raise ValueError("Preserved recovery archive is corrupt or unverifiable") if not digest_path.exists(): benchmark.write_json(digest_path, {"sha256": actual}) return with tempfile.NamedTemporaryFile(dir=saved.parent, prefix=".archive-", delete=False) as stream: temporary = Path(stream.name) try: shutil.copyfile(path, temporary) digest = benchmark.sha256(path) if digest != benchmark.sha256(temporary): raise ValueError("Recovery archive did not preserve original bytes") temporary.replace(saved) benchmark.write_json(digest_path, {"sha256": digest}) finally: temporary.unlink(missing_ok=True) def update_episode(root, episode, replacements): grades_path = episode / "grades.json" grades = load(grades_path) for grade in grades: if grade["sha256"] in replacements: path, summary = replacements[grade["sha256"]] grade.update(score=summary["analysis_score"], valid=summary["valid"], evaluation_complete=summary["complete"], scoring_status=summary["scoring_status"], summary_path=str(path), error=None) archive_original(root, grades_path) benchmark.write_json(grades_path, grades) status_path = episode / "status.json" status = load(status_path) archive_original(root, status_path) status["grading_failed"] = any(not g.get("valid") for g in grades) runner_path = episode / "runner" / "result.json" runner = load(runner_path) if runner_path.exists() else {} if runner.get("stop_reason"): status["stop_reason"] = runner["stop_reason"] if (not status["grading_failed"] and runner.get("stop_reason") == "completed" and not runner.get("snapshot_error")): status["status"] = "completed" status["grading_recovery"] = "audited_saved_artifacts_v1" benchmark.write_json(status_path, status) last = grades[-1] metrics = {"grading_recovered": 1, "grading_valid": int(bool(last.get("valid"))), "grader_complete": int(bool(last.get("evaluation_complete"))), "added_api_tokens": 0} if last.get("valid") and last.get("score") is not None: metrics["hidden_test_fraction"] = last["score"] with (root / "events.jsonl").open("a") as stream: stream.write(json.dumps({"timestamp": datetime.now(timezone.utc).isoformat(), "run_id": episode.name, "kind": "run_finished", "status": status["status"], "metrics": metrics}) + "\n") def report_entry(run_id, summary, original, raw_path, corrected_path, kind): return {"run_id": run_id, "kind": kind, "submission_sha256": summary["submission_sha256"], "raw_eval_sha256": benchmark.sha256(Path(original["eval_json"])), "raw_summary_sha256": benchmark.sha256(raw_path), "corrected_summary_sha256": benchmark.sha256(corrected_path) if corrected_path.exists() else None, "raw_score": original["score"], "score": summary["analysis_score"], "raw_test_count": original["test_count"], "test_count": summary["test_count"], "not_run_count": summary["not_run_count"], "valid": summary["valid"], "complete": summary["complete"], "added_api_tokens": 0} def recover_xsv(args): root = args.experiment_dir.resolve() entries = [] for run_id, audit in APPROVED.items(): episode = root / "episodes" / run_id grades = load(episode / "grades.json") grade = next((g for g in grades if g["sha256"] == audit["submission_sha256"]), None) if grade is None: continue # A separately recorded paid retry may have replaced this episode. summary_path = Path(grade["summary_path"]) summary = load(summary_path) if summary.get("recovery", {}).get("policy") == "audited_candidate_collection_fixed_official_mask": continue eval_path = Path(summary["eval_json"]) mask_path = summary_path.with_name("official-mask.json") for path, expected in [(summary_path, audit["summary_sha256"]), (eval_path, audit["eval_sha256"]), (Path(grade["snapshot_path"]), audit["submission_sha256"]), (mask_path, MASK_SHA256)]: if benchmark.sha256(path) != expected: raise ValueError(f"Unreviewed artifact in {run_id}; explicit audit required") recovered = recover_candidate_summary(summary, load(eval_path), load(mask_path), audit) recovered["recovery"]["calibration_sha256"] = CALIBRATION_SHA256 output = episode / "evaluations-recovered" / audit["submission_sha256"] / "summary.json" if not args.dry_run: archive_original(root, summary_path) benchmark.write_json(output, recovered) update_episode(root, episode, {audit["submission_sha256"]: (output, recovered)}) entries.append(report_entry(run_id, recovered, summary, summary_path, output, "candidate_collection_failed")) return entries def regrade_ripgrep(args): root = args.experiment_dir.resolve() episode = root / "episodes" / "ripgrep-single-r1" grades = load(episode / "grades.json") replacements, entries = {}, [] for grade in grades: if grade.get("valid") or grade["sha256"] in replacements: continue original_path = Path(grade["summary_path"]) original = load(original_path) submission = Path(grade["snapshot_path"]) if benchmark.sha256(submission) != grade["sha256"]: raise ValueError("Saved submission digest mismatch") output = episode / "evaluations-regraded" / grade["sha256"] summary_path = output / original["instance_id"] / "summary.json" if args.dry_run: continue if not summary_path.exists(): output.mkdir(parents=True, exist_ok=True) command = [args.evaluator_python, str(Path(__file__).with_name("programbench_adapter.py")), "--manifest", str(args.manifest.resolve()), "--programbench-root", str(args.programbench_root.resolve()), "--cpus", str(args.evaluator_cpus), "--memory", "30g", "--resource-mode", "container" if args.resource_mode == "docker" else args.resource_mode, "--branch-timeout-seconds", str(args.evaluator_branch_timeout), "--evaluator-wheelhouse", str(args.evaluator_wheelhouse.resolve()), "grade", "--instance-id", original["instance_id"], "--submission", str(submission), "--calibration", str(args.calibration.resolve()), "--output-dir", str(output)] with (output / "regrade.log").open("w") as stream: completed = subprocess.run(command, stdout=stream, stderr=subprocess.STDOUT, timeout=21600) if completed.returncode: raise RuntimeError("Saved-artifact CPU regrade failed; inspect private regrade.log") corrected = load(summary_path) if (corrected.get("submission_sha256") != grade["sha256"] or corrected.get("official_mask_sha256") != original["official_mask_sha256"] or corrected.get("evaluator_repair") != "pause_timeout_during_pytest_report_v1"): raise ValueError("CPU regrade changed candidate, official mask, or repair version") archive_original(root, original_path) replacements[grade["sha256"]] = (summary_path, corrected) entries.append(report_entry(episode.name, corrected, original, original_path, summary_path, "same_artifact_cpu_regrade")) if replacements: update_episode(root, episode, replacements) return entries def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--experiment-dir", type=Path, required=True) parser.add_argument("--calibration", type=Path, required=True) parser.add_argument("--manifest", type=Path, default=benchmark.DEFAULT_MANIFEST) parser.add_argument("--evaluator-python", default=sys.executable) parser.add_argument("--evaluator-cpus", type=int, default=16) parser.add_argument("--evaluator-branch-timeout", type=int, default=3600) parser.add_argument("--programbench-root", type=Path) parser.add_argument("--evaluator-wheelhouse", type=Path) parser.add_argument("--resource-mode", choices=["slurm", "docker"], default="slurm") parser.add_argument("--regrade-ripgrep", action="store_true") parser.add_argument("--dry-run", action="store_true") args = parser.parse_args() if args.evaluator_cpus < 1: parser.error("Evaluator CPU count must be positive") if args.evaluator_branch_timeout < 1: parser.error("Evaluator branch timeout must be positive") if benchmark.sha256(args.calibration) != CALIBRATION_SHA256: raise ValueError("Recovery requires the exact successful reference calibration") benchmark.check_calibration(args.calibration, args.manifest, benchmark.load_manifest(args.manifest)) if args.regrade_ripgrep and (not args.programbench_root or not args.evaluator_wheelhouse): parser.error("CPU regrading requires programbench root and evaluator wheelhouse") report_path = args.experiment_dir / "recovery-report.json" prior = load(report_path).get("entries", []) if report_path.exists() else [] entries = recover_xsv(args) report = {"version": 1, "policy": "audited_candidate_collection_fixed_official_mask_and_same_artifact_cpu_regrade", "calibration_sha256": CALIBRATION_SHA256, "entries": prior + entries} if not args.dry_run: benchmark.write_json(report_path, report) if args.regrade_ripgrep: entries.extend(regrade_ripgrep(args)) report["entries"] = prior + entries if not args.dry_run: benchmark.write_json(report_path, report) incomplete = any(not entry["valid"] for entry in entries) print(json.dumps({"status": "dry_run" if args.dry_run else "incomplete" if incomplete else "recovered", "entries": entries})) if incomplete: raise SystemExit(2) if __name__ == "__main__": main()