#!/usr/bin/env python3 """Run and score the public Perch method-pair benchmarks. Standard-library only. The command adapter is a persistent NDJSON process: it receives one JSON object per line and returns one {"score": probability} per line. """ from __future__ import annotations import argparse import hashlib import json import math import os from pathlib import Path import shlex import subprocess import sys import time from urllib.error import HTTPError, URLError from urllib.request import Request, urlopen DATASET_URL = { domain: f"https://huggingface.co/datasets/perchscan/{domain}-pairs-public/resolve/main/benchmark.jsonl" for domain in ("bug", "security") } QUESTION = { "bug": { "type": "noul", "instructions": "Does this method contain a concrete behavioral bug a caller can reach?", "criteria": { "true": "A reachable input makes the method violate its visible contract by returning a wrong result, leaving wrong state, or causing an unintended failure.", "false": "No concrete reachable case is supported by the method and supplied context. A possible-looking pattern alone is not enough.", }, }, "security": { "type": "noul", "instructions": "Does this method contain a concrete security vulnerability an attacker can reach?", "criteria": { "true": "A concrete path crosses a security boundary and can be exploited; name a reachable source, sensitive operation, and missing or incorrect protection.", "false": "No concrete reachable case is supported by the method and supplied context. A possible-looking pattern alone is not enough.", }, }, } def dataset_bytes(domain: str, path: Path | None) -> bytes: if path is not None: return (path / "benchmark.jsonl" if path.is_dir() else path).read_bytes() with urlopen(DATASET_URL[domain], timeout=120) as response: return response.read() def load_pairs(domain: str, path: Path | None) -> tuple[list[dict], str]: raw = dataset_bytes(domain, path) pairs = [json.loads(line) for line in raw.splitlines() if line] if not pairs: raise ValueError("Benchmark contains no pairs") ids = set() for pair in pairs: if pair["domain"] != domain or pair["pair_id"] in ids: raise ValueError("Wrong domain or duplicate pair ID in benchmark") ids.add(pair["pair_id"]) for role in ("before", "after"): if pair[role]["labels"][domain] not in (0, 1): raise ValueError(f"Invalid {domain} label for {pair['pair_id']}:{role}") return pairs, hashlib.sha256(raw).hexdigest() def probability(value: object) -> float: if isinstance(value, bool): raise ValueError("Score must be a number, not a boolean") score = float(value) if not math.isfinite(score) or not 0 <= score <= 1: raise ValueError(f"Score must be a finite probability in [0, 1]: {value!r}") return score def prediction_scores(path: Path, pairs: list[dict], domain: str, require_complete: bool) -> dict[tuple[str, str], float]: expected = {(pair["pair_id"], role) for pair in pairs for role in ("before", "after")} scores = {} if not path.exists(): if require_complete: raise FileNotFoundError(path) return scores for line in path.read_text().splitlines(): if not line: continue row = json.loads(line) key = (row["pair_id"], row["role"]) if key not in expected or key in scores or row.get("domain", domain) != domain: raise ValueError(f"Unexpected or duplicate prediction: {key}") scores[key] = probability(row["score"]) if require_complete and scores.keys() != expected: missing = expected - scores.keys() raise ValueError(f"Predictions are missing {len(missing)} method sides") return scores def average_precision(items: list[tuple[int, float]]) -> float: positives = sum(label for label, _ in items) if not positives: return 0.0 ordered = sorted(items, key=lambda item: item[1], reverse=True) found = total = 0 i = 0 while i < len(ordered): j = i + 1 while j < len(ordered) and ordered[j][1] == ordered[i][1]: j += 1 positives_at_score = sum(label for label, _ in ordered[i:j]) found += positives_at_score total += found / j * positives_at_score i = j return total / positives def report(pairs: list[dict], scores: dict[tuple[str, str], float], domain: str, digest: str, model_revision: str, protocol_id: str, threshold: float) -> dict: items = [(pair[role]["labels"][domain], scores[pair["pair_id"], role]) for pair in pairs for role in ("before", "after")] tp = sum(label == 1 and score >= threshold for label, score in items) fp = sum(label == 0 and score >= threshold for label, score in items) fn = sum(label == 1 and score < threshold for label, score in items) tn = sum(label == 0 and score < threshold for label, score in items) eligible = correct = ties = 0 for pair in pairs: if pair["before"]["labels"][domain] == 1 and pair["after"]["labels"][domain] == 0: eligible += 1 before, after = scores[pair["pair_id"], "before"], scores[pair["pair_id"], "after"] correct += before > after ties += before == after precision = tp / (tp + fp) if tp + fp else 0.0 recall = tp / (tp + fn) if tp + fn else 0.0 return { "domain": domain, "model_revision": model_revision, "protocol_id": protocol_id, "threshold": threshold, "benchmark_sha256": digest, "benchmark_pairs": len(pairs), "benchmark_methods": len(items), "average_precision": average_precision(items), "precision": precision, "recall": recall, "f1": 2 * tp / (2 * tp + fp + fn) if 2 * tp + fp + fn else 0.0, "false_positives_per_true_positive": fp / tp if tp else None, "confusion": {"tp": tp, "fp": fp, "tn": tn, "fn": fn}, "vulnerable_or_buggy_before_above_fixed_after": { "correct": correct, "ties": ties, "eligible": eligible, }, } def jev_score(state: dict, domain: str, model: str, api_url: str) -> float: key = os.getenv("TYPESAFE_API_KEY") or os.getenv("PERCH_API_KEY") if not key: raise RuntimeError("Set TYPESAFE_API_KEY or PERCH_API_KEY to run Jev") name = "bug_any" if domain == "bug" else "security_any" payload = json.dumps({"model": model, "state": state, "questions": {name: QUESTION[domain]}}).encode() for attempt in range(4): request = Request(api_url, data=payload, method="POST", headers={ "Authorization": f"Bearer {key}", "Content-Type": "application/json", }) try: with urlopen(request, timeout=120) as response: answer = json.load(response) return probability(answer["answers"][name]["noul"]) except HTTPError as exc: if exc.code not in (429, 500, 502, 503, 504) or attempt == 3: raise RuntimeError(f"Jev request failed with HTTP {exc.code}") from None delay = exc.headers.get("Retry-After") time.sleep(float(delay) if delay and delay.isdigit() else 2 ** attempt) except URLError: if attempt == 3: raise RuntimeError("Jev request failed after four network attempts") from None time.sleep(2 ** attempt) raise AssertionError("unreachable") def run(args: argparse.Namespace) -> None: pairs, digest = load_pairs(args.domain, args.dataset) if args.scorer == "jev": revision, protocol = args.model_revision or "jev-1.13.0", "perch-broad-v1" else: if not args.command or not args.model_revision or not args.protocol_id: raise ValueError("Command scorer requires --command, --model-revision, and --protocol-id") revision, protocol = args.model_revision, args.protocol_id if args.predictions.exists(): for line in args.predictions.read_text().splitlines(): if line: row = json.loads(line) if row.get("model_revision") != revision or row.get("protocol_id") != protocol: raise ValueError("Existing prediction file uses another model or protocol") existing = prediction_scores(args.predictions, pairs, args.domain, False) pending = [(pair, role) for pair in pairs for role in ("before", "after") if (pair["pair_id"], role) not in existing] if args.limit: pending = pending[:args.limit] command = None if args.scorer == "command" and pending: command = subprocess.Popen(shlex.split(args.command), stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True, bufsize=1) args.predictions.parent.mkdir(parents=True, exist_ok=True) try: with args.predictions.open("a") as output: for index, (pair, role) in enumerate(pending, 1): state = pair[role]["state"] if args.scorer == "jev": score = jev_score(state, args.domain, revision, args.api_url) else: request = {"domain": args.domain, "pair_id": pair["pair_id"], "role": role, "language": pair.get("language"), "source": pair[role]["source"], "state": state, "question": QUESTION[args.domain]} assert command and command.stdin and command.stdout command.stdin.write(json.dumps(request, ensure_ascii=False) + "\n") command.stdin.flush() line = command.stdout.readline() if not line: raise RuntimeError("Model adapter stopped before returning a score") score = probability(json.loads(line)["score"]) output.write(json.dumps({"domain": args.domain, "pair_id": pair["pair_id"], "role": role, "score": score, "model_revision": revision, "protocol_id": protocol}) + "\n") output.flush() if index % 100 == 0 or index == len(pending): print(f"Scored {len(existing) + index}/{2 * len(pairs)} method sides", file=sys.stderr) finally: if command: command.stdin.close() try: command.wait(timeout=30) except subprocess.TimeoutExpired: command.terminate() command.wait(timeout=5) finally: command.stdout.close() scores = prediction_scores(args.predictions, pairs, args.domain, False) if len(scores) != 2 * len(pairs): print(f"Incomplete: {len(scores)}/{2 * len(pairs)} sides; rerun to resume", file=sys.stderr) return result = report(pairs, scores, args.domain, digest, revision, protocol, args.threshold) args.report.parent.mkdir(parents=True, exist_ok=True) args.report.write_text(json.dumps(result, indent=2, sort_keys=True) + "\n") print(json.dumps(result, sort_keys=True)) def score_saved(args: argparse.Namespace) -> None: pairs, digest = load_pairs(args.domain, args.dataset) scores = prediction_scores(args.predictions, pairs, args.domain, True) first = json.loads(next(line for line in args.predictions.read_text().splitlines() if line)) result = report(pairs, scores, args.domain, digest, args.model_revision or first.get("model_revision", "unspecified"), args.protocol_id or first.get("protocol_id", "unspecified"), args.threshold) args.report.parent.mkdir(parents=True, exist_ok=True) args.report.write_text(json.dumps(result, indent=2, sort_keys=True) + "\n") print(json.dumps(result, sort_keys=True)) def main() -> None: parser = argparse.ArgumentParser(description=__doc__) sub = parser.add_subparsers(dest="action", required=True) for name in ("run", "score"): command = sub.add_parser(name) command.add_argument("--domain", choices=("bug", "security"), required=True) command.add_argument("--dataset", type=Path, help="Local benchmark.jsonl; default downloads public pairs") command.add_argument("--predictions", type=Path, required=True) command.add_argument("--report", type=Path, required=True) command.add_argument("--threshold", type=float, default=0.5) command.add_argument("--model-revision") command.add_argument("--protocol-id") if name == "run": command.add_argument("--scorer", choices=("jev", "command"), required=True) command.add_argument("--command", help="Persistent NDJSON scorer command") command.add_argument("--api-url", default="https://api.typesafe.ai/v1/systemone") command.add_argument("--limit", type=int, default=0, help="Score at most N new sides, then resume later") args = parser.parse_args() if not 0 <= args.threshold <= 1: parser.error("--threshold must be in [0, 1]") if args.action == "run": if args.limit < 0: parser.error("--limit must be nonnegative") run(args) else: score_saved(args) if __name__ == "__main__": main()