Datasets:
Download experiments/t3-flat/t3flat/cli.py from PV-SJTU/PV-Bench: direct link, hf CLI and curl.
- Browser
- Download file 22.6 kB
-
https://huggingface.co/datasets/PV-SJTU/PV-Bench/resolve/main/experiments/t3-flat/t3flat/cli.py
- Command line
-
hf download hf://datasets/PV-SJTU/PV-Bench/experiments/t3-flat/t3flat/cli.py
-
curl -L -o cli.py https://huggingface.co/datasets/PV-SJTU/PV-Bench/resolve/main/experiments/t3-flat/t3flat/cli.py
22.6 kB
| """Command-line interface for the PV-Bench T3-flat experiment harness.""" | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import os | |
| import shlex | |
| import shutil | |
| import subprocess | |
| import sys | |
| import time | |
| from collections import Counter, defaultdict | |
| from concurrent.futures import ThreadPoolExecutor | |
| from pathlib import Path | |
| from pvbench_common import agents, container, credentials, egress, evalset, passthrough | |
| from pvbench_common import manifest as manifest_module | |
| from t3 import audit as audit_module | |
| from t3 import backend as backend_module | |
| from t3.cli import DEFAULT_MODELS, EFFORTS, ORACLE_MODEL, RETRY_WAITS, _redacted_argv, _rename_attempt | |
| from t3.config import AUTH_MODES, excluded, pool_for | |
| from . import evaluate, pool, runners, validity, workspace | |
| from .config import FLAT_DIR, Case, Config, case_from_id, home, load | |
| DEFAULT_MODEL = DEFAULT_MODELS["codex"] | |
| T3_EVAL_SET_DIR = FLAT_DIR.parent / "t3" | |
| def make_case(args: argparse.Namespace) -> Case: | |
| runner = getattr(args, "runner", "codex") | |
| default = ORACLE_MODEL if getattr(args, "oracle", False) else DEFAULT_MODELS[runner] | |
| try: | |
| return case_from_id(args.case, args.model or default, args.mask, runner) | |
| except ValueError as error: | |
| raise SystemExit(f"t3flat: {error}") from None | |
| def _validate_case(cfg: Config, case: Case) -> dict: | |
| """The problem is a T3 target and the case is in the frozen pool; returns the pool entry.""" | |
| if case.problem in pool_for(case.be): | |
| raise SystemExit(f"refusing: {case.problem} is in the T3 proof-reference pool") | |
| if case.problem in excluded(): | |
| raise SystemExit(f"refusing: {case.problem} is listed in excluded.txt") | |
| if not (case.source_dir / "solution_annotated.c").is_file(): | |
| raise SystemExit(f"no rocq T3 case: {case.problem}") | |
| try: | |
| entry = pool.load_pool(cfg.task.eval_set_version).get(case.case_id) | |
| except evalset.EvalSetError as error: | |
| raise SystemExit(f"t3flat: {error}") from None | |
| if entry is None: | |
| raise SystemExit(f"refusing: {case.case_id} is not in eval set {cfg.task.eval_set_version}") | |
| return entry | |
| def check_report(cfg: Config, case: Case) -> str: | |
| valid, lines, failures = validity.check(cfg, case, write=False) | |
| lines += ["", *validity.summary_lines(validity.summary(case, valid, failures))] | |
| classes = sorted({failure["class"] for failure in failures}) | |
| report = "\n".join(lines) + f"\nvalid: {'YES' if valid else 'NO ' + ','.join(classes)}\n" | |
| case.run_dir.mkdir(parents=True, exist_ok=True) | |
| (case.run_dir / "validity.txt").write_text(report) | |
| return report | |
| def _dry_run(cfg: Config, case: Case, ws: Path, evidence: Path, fixed: dict, timeout: int, effort: str, | |
| target: dict) -> None: | |
| eg = runners.egress_descriptor(cfg.task) | |
| creds = None | |
| try: | |
| creds = credentials.prepare(case.runner, cfg.auth_mode, attempt_dir=evidence, **passthrough.credentials_kwargs()) | |
| except credentials.CredentialsError as error: | |
| print(f"note: credentials not available ({error}); omitted from this dry run") | |
| try: | |
| cache = None | |
| if creds is not None: | |
| cache = evidence / "auth" / "cache" | |
| cache.mkdir(parents=True, exist_ok=True) | |
| inv = runners.attempt_invocation(cfg, case, ws, effort, eg, creds, cache) | |
| finally: | |
| if creds is not None: | |
| credentials.scrub(creds) | |
| try: | |
| image_id = container.image_id(cfg.image) | |
| except container.ContainerError: | |
| image_id = "<unresolved>" | |
| data = validity.build_manifest(cfg, case, ws, inv, None, image_id=image_id, fixed=fixed, timeout=timeout, | |
| reasoning_effort=effort, target=target, | |
| credentials_desc=credentials.describe(creds) if creds is not None else None, | |
| egress_=eg) | |
| manifest_module.write(evidence / "manifest.json", data) | |
| from t3 import workspace as t3_workspace | |
| print(f"workspace: {ws}") | |
| print("\n".join(" " + path for path in t3_workspace.listing(ws))) | |
| print(f"\nimage: {cfg.image} ({image_id})") | |
| print("would run:") | |
| print(" " + shlex.join(_redacted_argv(runners.docker_argv(inv)))) | |
| def cmd_run(args: argparse.Namespace) -> None: | |
| if args.oracle and args.dry_run: | |
| raise SystemExit("t3flat: --oracle and --dry-run are exclusive") | |
| cfg = load() | |
| if args.auth: | |
| import dataclasses | |
| cfg = dataclasses.replace(cfg, auth_mode=args.auth) | |
| case = make_case(args) | |
| entry = _validate_case(cfg, case) | |
| destination = case.run_dir | |
| ws = case.ws_dir(cfg) | |
| if args.dry_run: | |
| destination = home() / "runs/dry" / case.model / case.rel | |
| ws = destination / "workspace" | |
| elif (destination / "evidence/status").is_file() and not args.force: | |
| raise SystemExit(f"{case.rel} [{case.model}]: run exists at {destination}; use --force to redo") | |
| if not args.dry_run: | |
| try: | |
| runners.preflight(cfg, need_proxy=not args.oracle) | |
| except RuntimeError as error: | |
| raise SystemExit(f"t3flat: {error}") from None | |
| if destination.exists(): | |
| shutil.rmtree(destination) | |
| evidence = destination / "evidence" | |
| evidence.mkdir(parents=True) | |
| timeout = args.timeout or validity.clock_s(cfg) | |
| print(f"preparing fresh VCs for {case.case_id}", flush=True) | |
| try: | |
| target = workspace.build(cfg, case, ws, entry, timeout) | |
| except RuntimeError as error: | |
| raise SystemExit(f"t3flat: {error}") from None | |
| fixed = validity.fixed_inputs(ws) | |
| print(f"target: {case.goal} ({target['kind']}); clock {timeout // 60} min" | |
| + (" (overridden by --timeout; fails validity)" if timeout != validity.clock_s(cfg) else ""), flush=True) | |
| if args.dry_run: | |
| _dry_run(cfg, case, ws, evidence, fixed, timeout, args.reasoning_effort, target) | |
| return | |
| concurrent = int(os.environ.get("PVBENCH_CONCURRENT", "1") or 1) | |
| try: | |
| if args.oracle: | |
| outcome = runners.oracle(cfg, case, ws, evidence, target=target, fixed=fixed) | |
| else: | |
| def attempt(): | |
| return runners.run(cfg, case, ws, evidence, timeout, target=target, | |
| reasoning_effort=args.reasoning_effort, fixed=fixed, concurrent=concurrent) | |
| outcome = attempt() | |
| for number, wait_seconds in enumerate(RETRY_WAITS, 1): | |
| trace = (evidence / "events.jsonl").read_text(errors="replace") | |
| if outcome.timed_out or validity.api_error(trace, case.runner) is None: | |
| break | |
| _rename_attempt(evidence, number) | |
| print(f" API error on attempt {number}; retrying in {wait_seconds}s", flush=True) | |
| time.sleep(wait_seconds) | |
| outcome = attempt() | |
| status = runners.collect(cfg, case, ws, evidence) | |
| except (container.ContainerError, egress.EgressError, credentials.CredentialsError) as error: | |
| raise SystemExit(f"t3flat: {error}") from None | |
| data = validity.read_manifest(case) or {} | |
| _, lines = audit_module.audit(evidence / "events.jsonl", sorted(case.out_dir.glob(f"*{case.suffix}")), | |
| validity.denied_hosts(data)) | |
| status += [" " + line for line in lines] | |
| status += [f"timed-out: {'yes' if outcome.timed_out else 'no'}", | |
| f"oom-killed: {'yes' if outcome.oom_killed else 'no'}", f"exit: {outcome.exit_code}"] | |
| (evidence / "status").write_text("\n".join(status) + "\n") | |
| report = check_report(cfg, case) | |
| if args.quiet: | |
| print(one_line(case), flush=True) | |
| else: | |
| print(f"{case.rel} [{case.model}]: " + " ".join(status)) | |
| print(report, end="") | |
| def _total_input(tokens: dict) -> int: | |
| return sum(tokens.get(key) or 0 for key in ("input", "cache_read", "cache_creation")) | |
| def one_line(case: Case) -> str: | |
| summary = json.loads((case.run_dir / "summary.json").read_text()) | |
| status = (case.ev_run / "status").read_text() if (case.ev_run / "status").is_file() else "" | |
| valid = "YES" if summary.get("valid") else "NO " + ",".join(summary.get("invalid_classes", [])) | |
| proof = "ok" if "local-check: OK" in status else "FAIL" | |
| return (f"{case.rel:<90} [{case.model}] valid: {valid:<14} proof {proof:<4} " | |
| f"{summary.get('wall_seconds', 0):6.0f}s {_total_input(summary.get('tokens', {})) / 1000:6.0f}k tok " | |
| f"{summary.get('tool_calls', {}).get('total', 0):3d} calls") | |
| def cmd_eval(args: argparse.Namespace) -> None: | |
| cfg = load() | |
| case = make_case(args) | |
| _validate_case(cfg, case) | |
| if not (case.ev_run / "status").is_file(): | |
| raise SystemExit(f"run T3-flat generation first: {case.run_dir}") | |
| try: | |
| print(evaluate.evaluate(cfg, case, allow_env_mismatch=args.allow_env_mismatch), end="") | |
| except container.ContainerError as error: | |
| raise SystemExit(f"t3flat: {error}") from None | |
| def cmd_check(args: argparse.Namespace) -> None: | |
| print(check_report(load(), make_case(args)), end="") | |
| def cmd_audit(args: argparse.Namespace) -> None: | |
| case = make_case(args) | |
| data = validity.read_manifest(case) | |
| if data is None: | |
| raise SystemExit(f"manifest missing or unreadable: {case.ev_run / 'manifest.json'}") | |
| answers = sorted(case.out_dir.glob(f"*{case.suffix}")) if case.out_dir.is_dir() else [] | |
| hard, lines = audit_module.audit(case.ev_run / "events.jsonl", answers, validity.denied_hosts(data)) | |
| print("\n".join(" " + line for line in lines)) | |
| print(f"audit: {hard} hard finding(s)") | |
| def cmd_pool_build(args: argparse.Namespace) -> None: | |
| """Regenerate every T3 problem's VCs in the image and freeze the pool (one version, once).""" | |
| cfg = load() | |
| version = args.version or cfg.task.eval_set_version | |
| for path in (evalset.path(FLAT_DIR, version), pool.goals_path(version)): | |
| if path.exists(): | |
| raise SystemExit(f"t3flat: {path} exists; a pool version is frozen, choose the next one") | |
| try: | |
| problems = list(evalset.load(T3_EVAL_SET_DIR, args.source_version)) | |
| except evalset.EvalSetError as error: | |
| raise SystemExit(f"t3flat: {error}") from None | |
| try: | |
| runners.preflight(cfg, need_proxy=False) | |
| except RuntimeError as error: | |
| raise SystemExit(f"t3flat: {error}") from None | |
| entries: dict[str, dict] = {} | |
| failed: list[str] = [] | |
| scratch = cfg.ws_root / "pool" / version | |
| for index, problem in enumerate(problems, 1): | |
| try: | |
| goal_text, skeleton_text = pool.generate_goal_file(cfg, problem, scratch / problem.rsplit("/", 1)[-1]) | |
| found = pool.entries_for(problem, goal_text, skeleton_text) | |
| except Exception as error: # noqa: BLE001 - one broken case must not stop the sweep | |
| failed.append(f"{problem}: {type(error).__name__}: {error}") | |
| print(f"FAIL {problem}: {type(error).__name__}: {error}", flush=True) | |
| continue | |
| entries.update(found) | |
| print(f"{index:3d}/{len(problems)} {problem}: {len(found)} manual VC goals", flush=True) | |
| shutil.rmtree(scratch, ignore_errors=True) | |
| if failed: | |
| raise SystemExit(f"t3flat: {len(failed)} problem(s) failed; pool not written:\n" + "\n".join(failed)) | |
| list_path, record_path = pool.write_pool(version, entries, args.source_version) | |
| kinds = Counter(entry["kind"] for entry in entries.values()) | |
| print(f"{len(entries)} goals of {len(problems)} problems -> {list_path.name}, {record_path.name}; " | |
| + ", ".join(f"{kind} {count}" for kind, count in kinds.most_common())) | |
| def _effective_jobs(cfg: Config, requested: int) -> int: | |
| try: | |
| cap = container.max_parallel(cfg.task, container.daemon_resources()) | |
| except container.ContainerError as error: | |
| raise SystemExit(f"t3flat: {error}") from None | |
| if requested > cap: | |
| print(f"--jobs {requested} capped at {cap} (daemon resources / per-attempt limits)", flush=True) | |
| return cap | |
| return requested | |
| def _list_entries(path: str) -> list[str]: | |
| return [line.strip() for line in Path(path).read_text().splitlines() | |
| if line.strip() and not line.lstrip().startswith("#")] | |
| def cmd_all(args: argparse.Namespace, command_name: str) -> None: | |
| cases = _list_entries(args.list) | |
| force = getattr(args, "force", False) | |
| jobs = _effective_jobs(load(), args.jobs) | |
| env = {**os.environ, "PVBENCH_CONCURRENT": str(jobs)} | |
| def one(case_id: str) -> str: | |
| runner = getattr(args, "runner", "codex") | |
| model = args.model or (DEFAULT_MODELS[runner] if command_name == "run" else DEFAULT_MODEL) | |
| try: | |
| case = case_from_id(case_id, model, args.mask, runner) | |
| except ValueError as error: | |
| print(f"{case_id}: {error}", flush=True) | |
| return "failed" | |
| if command_name == "run" and (case.ev_run / "status").is_file() and not force: | |
| print(f"{case.rel} [{case.model}]: run exists ({case.run_dir}); --force to redo", flush=True) | |
| return "skipped" | |
| if command_name == "eval" and (case.eval_dir / "verdict.txt").is_file() and not force: | |
| print(f"{case.rel} [{case.model}]: evaluation exists ({case.eval_dir}); --force to redo", flush=True) | |
| return "skipped" | |
| command = [sys.executable, str(FLAT_DIR / "t3flat.py"), command_name, case_id, model] | |
| if command_name == "run": | |
| command += ["--runner", runner, "--reasoning-effort", args.reasoning_effort, "--quiet"] | |
| if args.timeout: | |
| command += ["--timeout", str(args.timeout)] | |
| if args.auth: | |
| command += ["--auth", args.auth] | |
| if force: | |
| command.append("--force") | |
| if command_name == "eval" and args.allow_env_mismatch: | |
| command.append("--allow-env-mismatch") | |
| if args.mask: | |
| command += ["--mask", args.mask] | |
| print(f"started {case_id}", flush=True) | |
| result = subprocess.run(command, capture_output=True, text=True, env=env) | |
| output = result.stdout.strip() | |
| if not output: | |
| output = result.stderr.strip().splitlines()[-1] if result.stderr.strip() else f"{case_id}: no output" | |
| print(output, flush=True) | |
| return "completed" if result.returncode == 0 else "failed" | |
| with ThreadPoolExecutor(max_workers=jobs) as executor: | |
| results = list(executor.map(one, cases)) | |
| counts = {status: results.count(status) for status in ("completed", "skipped", "failed")} | |
| print(f"{command_name}-all: {counts['completed']} completed, {counts['skipped']} skipped, {counts['failed']} failed") | |
| def _verdict(path: Path) -> str: | |
| if not path.is_file(): | |
| return "-" | |
| line = next((l for l in path.read_text().splitlines() if l.startswith("verdict: ")), "") | |
| return line.removeprefix("verdict: ") if line else "-" | |
| def cmd_report(args: argparse.Namespace) -> None: | |
| cfg = load() | |
| base = home() / "runs" / args.model | |
| try: | |
| entries = pool.load_pool(cfg.task.eval_set_version) | |
| except evalset.EvalSetError as error: | |
| raise SystemExit(f"t3flat: {error}") from None | |
| rows = [] | |
| for summary_path in sorted(base.rglob("summary.json")): | |
| if summary_path.parent.name == "workspace" or "workspace" in summary_path.parent.parts: | |
| continue | |
| relative = summary_path.parent.relative_to(base).as_posix() | |
| if args.mask == "*": | |
| pass | |
| elif args.mask: | |
| if not relative.endswith(f"_Pass@{args.mask}"): | |
| continue | |
| elif "_Pass@" in relative: | |
| continue | |
| summary = json.loads(summary_path.read_text()) | |
| case_id = summary.get("case_id") or "" | |
| verdict = _verdict(home() / "evals" / args.model / relative / "verdict.txt") | |
| tokens = summary.get("tokens", {}) | |
| rows.append((relative, case_id, summary.get("kind") or entries.get(case_id, {}).get("kind", "?"), | |
| "YES" if summary.get("valid") else "NO " + ",".join(summary.get("invalid_classes", [])), | |
| verdict, summary.get("wall_seconds", 0), _total_input(tokens), | |
| summary.get("tool_calls", {}).get("total", 0))) | |
| if not rows: | |
| raise SystemExit(f"no T3-flat runs under {base}") | |
| width = max(len(row[0]) for row in rows) | |
| print(f"{'case':<{width}} kind valid verdict time tokens calls") | |
| for relative, _, kind, valid, verdict, seconds, tokens, calls in rows: | |
| print(f"{relative:<{width}} {kind:<17} {valid:<15} {verdict:<11} {seconds:6.0f}s {tokens / 1000:7.0f}k {calls:5d}") | |
| scored = [row for row in rows if row[4] in {"ACCEPT", "FAILED", "OTL"}] | |
| accepted = sum(row[4] == "ACCEPT" for row in scored) | |
| counts = ", ".join(f"{name} {sum(row[4] == name for row in rows)}" for name in ("ACCEPT", "FAILED", "OTL", "INVALID", "-")) | |
| label = "pass@1" if not args.mask else f"diagnostic mask {args.mask}" | |
| rate = accepted / len(scored) if scored else 0.0 | |
| print(f"\n{len(rows)} runs; scored {len(scored)}; {label} {accepted}/{len(scored)} = {rate:.3%}; {counts}") | |
| by_kind: dict[str, list[int]] = defaultdict(lambda: [0, 0]) | |
| by_corpus: dict[str, list[int]] = defaultdict(lambda: [0, 0]) | |
| by_problem: dict[str, list[int]] = defaultdict(lambda: [0, 0]) | |
| for _, case_id, kind, _, verdict, *_ in scored: | |
| problem = case_id.split("::", 1)[0] | |
| for table, key in ((by_kind, kind), (by_corpus, problem.split("/", 1)[0]), (by_problem, problem)): | |
| table[key][1] += 1 | |
| table[key][0] += verdict == "ACCEPT" | |
| for title, table in (("by kind", by_kind), ("by corpus", by_corpus)): | |
| print(title + ": " + ", ".join(f"{key} {ok}/{n}" for key, (ok, n) in sorted(table.items()))) | |
| pool_sizes = Counter(entry["problem"] for entry in entries.values()) | |
| complete = [p for p, (ok, n) in by_problem.items() if n == pool_sizes.get(p) and ok == n] | |
| covered = [p for p, (ok, n) in by_problem.items() if n == pool_sizes.get(p)] | |
| print(f"problems with every pool VC scored: {len(covered)}; all of them ACCEPT: {len(complete)}") | |
| def _common(parser: argparse.ArgumentParser) -> None: | |
| parser.add_argument("case", help="T3-flat case id: <problem>::<goal>") | |
| parser.add_argument("model", nargs="?", default=None) | |
| parser.add_argument("--mask", default="", help="non-formal diagnostic label; formal pass@1 leaves this empty") | |
| def main(argv: list[str] | None = None) -> None: | |
| parser = argparse.ArgumentParser(prog="t3flat", description=__doc__) | |
| subcommands = parser.add_subparsers(dest="command", required=True) | |
| command = subcommands.add_parser("run", help="run one fresh single-VC proof session") | |
| _common(command) | |
| passthrough.add_arguments(command) | |
| command.add_argument("--runner", choices=list(agents.NAMES), default="codex") | |
| command.add_argument("--timeout", type=int, default=None, | |
| help="agent wall clock in seconds (default: task.toml agent_timeout_s; an override fails validity)") | |
| command.add_argument("--reasoning-effort", choices=EFFORTS, default="high") | |
| command.add_argument("--auth", choices=AUTH_MODES, default=None) | |
| command.add_argument("--oracle", action="store_true", help="no model: the gold proof becomes the answer") | |
| command.add_argument("--dry-run", action="store_true") | |
| command.add_argument("--force", action="store_true") | |
| command.add_argument("--quiet", action="store_true") | |
| command.set_defaults(function=cmd_run) | |
| command = subcommands.add_parser("eval", help="clean deterministic build and target check") | |
| _common(command) | |
| command.add_argument("--allow-env-mismatch", action="store_true") | |
| command.set_defaults(function=cmd_eval) | |
| command = subcommands.add_parser("check", help="check run provenance/isolation/completion/integrity") | |
| _common(command) | |
| command.set_defaults(function=cmd_check) | |
| command = subcommands.add_parser("audit", help="summarize a run's trace, egress denials and answer scan") | |
| _common(command) | |
| command.set_defaults(function=cmd_audit) | |
| command = subcommands.add_parser("pool", help="pool management") | |
| pool_commands = command.add_subparsers(dest="pool_command", required=True) | |
| command = pool_commands.add_parser("build", help="freeze every manual VC goal of the T3 eval set") | |
| command.add_argument("--version", default=None, help="pool version to write (default: task.toml eval_set_version)") | |
| command.add_argument("--source-version", default="v1", help="T3 eval set the problems come from") | |
| command.set_defaults(function=cmd_pool_build) | |
| command = subcommands.add_parser("report", help="tabulate validity, verdicts, pass@1 and breakdowns") | |
| command.add_argument("model") | |
| command.add_argument("--mask", default="") | |
| command.set_defaults(function=cmd_report) | |
| command = subcommands.add_parser("run-all", help="run every case in a list (an eval set or a subset)") | |
| passthrough.add_arguments(command) | |
| command.add_argument("list") | |
| command.add_argument("model", nargs="?", default=None) | |
| command.add_argument("--jobs", type=int, default=2) | |
| command.add_argument("--runner", choices=list(agents.NAMES), default="codex") | |
| command.add_argument("--mask", default="") | |
| command.add_argument("--timeout", type=int, default=None) | |
| command.add_argument("--reasoning-effort", choices=EFFORTS, default="high") | |
| command.add_argument("--auth", choices=AUTH_MODES, default=None) | |
| command.add_argument("--force", action="store_true") | |
| command.set_defaults(function=lambda a: cmd_all(a, "run")) | |
| command = subcommands.add_parser("eval-all", help="evaluate every run in a list") | |
| command.add_argument("list") | |
| command.add_argument("model", nargs="?", default=None) | |
| command.add_argument("--jobs", type=int, default=2) | |
| command.add_argument("--mask", default="") | |
| command.add_argument("--allow-env-mismatch", action="store_true") | |
| command.add_argument("--force", action="store_true") | |
| command.set_defaults(function=lambda a: cmd_all(a, "eval")) | |
| args = parser.parse_args(argv) | |
| try: | |
| passthrough.export(args) | |
| except passthrough.PassthroughError as error: | |
| parser.error(str(error)) | |
| timeout = getattr(args, "timeout", None) | |
| if (timeout is not None and timeout <= 0) or getattr(args, "jobs", 1) <= 0: | |
| parser.error("--timeout and --jobs must be positive") | |
| args.function(args) | |
| if __name__ == "__main__": | |
| main() | |