benchmark-results / benchmark.py
jfbrown95's picture
Use configured bug and security floors and 70% semantic lint cutoff
b861a3e verified
Raw History Blame
20.6 kB
#!/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.
Current scan mode uses question-pack.json exported from public Perch scan.yaml.
"""
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")
}
LEGACY_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 load_pack(path: Path) -> dict:
pack = json.loads(path.read_text())
body = {key: pack[key] for key in ("schema_version", "source", "source_sha256", "domains")}
digest = hashlib.sha256(json.dumps(body, separators=(",", ":"), ensure_ascii=False).encode()).hexdigest()
if (pack.get("schema_version") != 1 or pack.get("pack_sha256") != digest
or pack.get("protocol_id") != f"perch-scan-{digest[:12]}"
or pack.get("binary_protocol_id") != f"perch-scan-binary-{digest[:12]}"):
raise ValueError("Question pack checksum or protocol ID does not match its contents")
for domain in ("bug", "security"):
if not pack["domains"].get(domain):
raise ValueError(f"Question pack has no {domain} questions")
for question in pack["domains"][domain]:
if question["where"] != "**/*":
raise ValueError(f"Benchmark does not yet support path selector {question['where']}")
return pack
def scan_questions(pack: dict, domain: str, language: str) -> list[dict]:
if not language:
raise ValueError("Benchmark pair has no language for question selection")
normalized = {"csharp": "c_sharp"}.get(language, language)
return [q for q in pack["domains"][domain]
if q["language"] is None or normalized in ([q["language"]] if isinstance(q["language"], str) else q["language"])]
def detection_questions(questions: list[dict], domain: str) -> list[dict]:
issue_type = "defect" if domain == "bug" else "security"
return [q for q in questions if q["type"] == "noul" and q["issue"] and q["issue"]["type"] == issue_type]
def raised_score(question: dict, true_probability: object) -> float:
score = probability(true_probability)
return 1 - score if question["issue"].get("on") is False else score
def scan_result(question_scores: dict[str, float], questions: list[dict], domain: str, threshold: float) -> tuple[float, bool]:
relevant = detection_questions(questions, domain)
expected = {q["name"] for q in relevant}
if set(question_scores) != expected:
raise ValueError(f"Question scores differ from selected scan pack: {expected ^ set(question_scores)}")
score = max(question_scores.values(), default=0.0)
# Use the same per-question floor as a Perch scan. --threshold can only
# raise that floor for the whole run.
alert = any(question_scores[q["name"]] > max(threshold, (q.get("min") or 0) / 100)
for q in relevant)
return score, alert
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], dict]:
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}")
row["score"] = probability(row["score"])
scores[key] = row
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], dict], domain: str,
digest: str, model_revision: str, protocol_id: str,
threshold: float, pack: dict | None = None) -> dict:
items = []
for pair in pairs:
for role in ("before", "after"):
row = scores[pair["pair_id"], role]
if pack and protocol_id in (pack["protocol_id"], pack["binary_protocol_id"]):
if row.get("pack_sha256") != pack["pack_sha256"]:
raise ValueError("Prediction was made with a different question pack")
questions = scan_questions(pack, domain, pair["language"])
score, alert = scan_result(row.get("question_scores", {}), questions, domain, threshold)
if abs(score - row["score"]) > 1e-9:
raise ValueError("Prediction's aggregate score does not match its question scores")
else:
score, alert = row["score"], row["score"] >= threshold
items.append((pair[role]["labels"][domain], score, alert))
tp = sum(label == 1 and alert for label, _, alert in items)
fp = sum(label == 0 and alert for label, _, alert in items)
fn = sum(label == 1 and not alert for label, _, alert in items)
tn = sum(label == 0 and not alert for label, _, alert 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"]["score"], scores[pair["pair_id"], "after"]["score"]
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,
"alert_rule": "any issue score > max(run threshold, question min)" if pack and protocol_id in (pack["protocol_id"], pack["binary_protocol_id"]) else "score >= threshold",
"question_pack_sha256": pack["pack_sha256"] if pack and protocol_id in (pack["protocol_id"], pack["binary_protocol_id"]) else None,
"benchmark_sha256": digest,
"benchmark_pairs": len(pairs),
"benchmark_methods": len(items),
"average_precision": average_precision([(label, score) for label, score, _ in 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_answers(state: dict, questions: dict, model: str, api_url: str) -> dict:
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")
payload = json.dumps({"model": model, "state": state, "questions": questions}).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 answer["answers"]
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 command_score(command: subprocess.Popen, request: dict) -> float:
assert 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")
return probability(json.loads(line)["score"])
def run(args: argparse.Namespace) -> None:
pairs, digest = load_pairs(args.domain, args.dataset)
pack = load_pack(args.question_pack)
scan_protocols = (pack["protocol_id"], pack["binary_protocol_id"])
mode = args.mode or ("broad" if args.protocol_id == "perch-broad-v1" else
"native" if args.protocol_id and args.protocol_id not in scan_protocols else "scan")
if args.scorer == "jev":
if mode == "native":
raise ValueError("Jev requires scan or broad question mode")
revision = args.model_revision or "jev-1.13.0"
protocol = pack["protocol_id"] if mode == "scan" else "perch-broad-v1"
if args.protocol_id and args.protocol_id != protocol:
raise ValueError("Jev protocol ID does not match the selected question mode")
else:
if not args.command or not args.model_revision:
raise ValueError("Command scorer requires --command and --model-revision")
revision = args.model_revision
protocol = args.protocol_id or (pack["binary_protocol_id"] if mode == "scan" else "perch-broad-v1")
if mode == "scan" and protocol != pack["binary_protocol_id"]:
raise ValueError("Scan protocol ID must match the question pack")
if mode == "native" and not args.protocol_id:
raise ValueError("Native scorer requires its own --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")
if mode == "scan" and row.get("pack_sha256") != pack["pack_sha256"]:
raise ValueError("Existing predictions use another scan question pack")
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 mode == "scan":
selected = scan_questions(pack, args.domain, pair["language"])
if args.scorer == "jev":
answers = jev_answers(state, {q["name"]: q["question"] for q in selected}, revision, args.api_url)
question_scores = {q["name"]: raised_score(q, answers[q["name"]]["noul"])
for q in detection_questions(selected, args.domain)}
else:
question_scores = {}
for q in detection_questions(selected, args.domain):
request = {"domain": args.domain, "pair_id": pair["pair_id"], "role": role,
"language": pair["language"], "source": pair[role]["source"],
"state": state, "question": q["question"], "question_name": q["name"]}
question_scores[q["name"]] = raised_score(q, command_score(command, request))
score, alert = scan_result(question_scores, selected, args.domain, args.threshold)
else:
question = LEGACY_QUESTION[args.domain]
if args.scorer == "jev":
name = "bug_any" if args.domain == "bug" else "security_any"
score = probability(jev_answers(state, {name: question}, revision, args.api_url)[name]["noul"])
else:
request = {"domain": args.domain, "pair_id": pair["pair_id"], "role": role,
"language": pair.get("language"), "source": pair[role]["source"],
"state": state, "question": question}
score = command_score(command, request)
result = {"domain": args.domain, "pair_id": pair["pair_id"], "role": role,
"score": score, "model_revision": revision, "protocol_id": protocol}
if mode == "scan":
result.update(question_scores=question_scores, alert=alert,
threshold=args.threshold,
alert_rule="any issue score > max(run threshold, question min)",
pack_sha256=pack["pack_sha256"])
output.write(json.dumps(result) + "\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, pack)
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))
pack = load_pack(args.question_pack)
revision = args.model_revision or first.get("model_revision", "unspecified")
protocol = args.protocol_id or first.get("protocol_id", "unspecified")
if any((row.get("model_revision", revision) != revision or row.get("protocol_id", protocol) != protocol)
for row in scores.values()):
raise ValueError("Predictions mix model revisions or protocols")
result = report(pairs, scores, args.domain, digest,
revision, protocol, args.threshold, pack)
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("--question-pack", type=Path, default=Path(__file__).with_name("question-pack.json"))
command.add_argument("--model-revision")
command.add_argument("--protocol-id")
if name == "run":
command.add_argument("--mode", choices=("scan", "broad", "native"),
help="Default: scan; old broad/native protocol IDs infer their historical mode")
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()