#!/usr/bin/env python3 """Score Perch benchmark methods with TypeLLM's hosted boolean API. Every method side is an independent request. Applicable bug/security questions share that request; a semantic-lint pair uses its same ensure rule on both sides. The JSONL predictions are append-only and can be resumed after interruption. """ from __future__ import annotations import argparse from concurrent.futures import ThreadPoolExecutor, as_completed import hashlib import importlib.util import json import math import os from pathlib import Path import random import sys import threading import time from urllib.error import HTTPError, URLError from urllib.request import Request, urlopen MODEL = "typellm-latest" API = "https://api.typellm.ai/v1/generate" PROTOCOL = "typellm-boolean-v1" LINT_PROTOCOL = "perch-semantic-ensure-v1" DEFAULT_INTERVAL = 0.62 # Below the documented account cap of 100 requests/minute. def module_at(name: str, path: Path): spec = importlib.util.spec_from_file_location(name, path) if spec is None or spec.loader is None: raise ValueError(f"Cannot import {path}") module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module def probability(value: object) -> float: if isinstance(value, bool): raise ValueError("Boolean is not a probability") score = float(value) if not math.isfinite(score) or not 0 <= score <= 1: raise ValueError("Invalid probability") return score class RateLimiter: def __init__(self, interval: float): self.interval = interval self.lock = threading.Lock() self.next_at = time.monotonic() def wait(self): with self.lock: now = time.monotonic() at = max(now, self.next_at) self.next_at = at + self.interval if at > now: time.sleep(at - now) def back_off(self, seconds: float): with self.lock: self.next_at = max(self.next_at, time.monotonic() + seconds) def type_question(question: dict) -> dict: item = question["question"] true = str(item["criteria"]["true"]).strip() false = str(item["criteria"]["false"]).strip() return { "type": "boolean", "instructions": f'{item["instructions"].strip()}\nTrue: {true}\nFalse: {false}', "return_probabilities": True, } def lint_question(ensure: str) -> dict: rule = " ".join(ensure.split()) return { "type": "boolean", "instructions": f"Is `rule` true of the code below?\nRule: {rule}\nTrue: {rule}\nFalse: Not so: {rule}", "return_probabilities": True, } def true_score(result: dict) -> float: values = result.get("probabilities") if not isinstance(values, dict) or "true" not in values or "false" not in values: raise ValueError("TypeLLM did not return both boolean probabilities") true, false = probability(values["true"]), probability(values["false"]) if abs(true + false - 1) > 1e-5: raise ValueError("Boolean probabilities do not sum to one") return true def invoke(key: str, state: dict, questions: dict, limiter: RateLimiter) -> dict: context = "Perch method context (JSON):\n" + json.dumps(state, ensure_ascii=False, separators=(",", ":")) payload = json.dumps({"model": MODEL, "context": context, "questions": questions, "options": {"temperature": 0}, "timeout": 90}, ensure_ascii=False).encode() headers = {"Authorization": "Bearer " + key, "Content-Type": "application/json"} for attempt in range(8): limiter.wait() started = time.monotonic() request = Request(API, data=payload, headers=headers, method="POST") try: with urlopen(request, timeout=105) as response: data = json.load(response) if data.get("model") != MODEL or set(data.get("result", {})) != set(questions): raise ValueError("TypeLLM returned a different model or incomplete result") data["request_elapsed_s"] = round(time.monotonic() - started, 3) return data except HTTPError as exc: if exc.code not in (429, 502, 503, 504) or attempt == 7: raise RuntimeError(f"TypeLLM HTTP {exc.code}") from None header = exc.headers.get("Retry-After") try: delay = max(1.0, min(90.0, float(header))) except (ValueError, TypeError): delay = min(60.0, 2.0 ** attempt) limiter.back_off(delay) time.sleep(delay + random.random() * 0.2) except URLError: if attempt == 7: raise RuntimeError("TypeLLM transport failed after retries") from None time.sleep(min(30, 2 ** attempt)) raise AssertionError("unreachable") def load_pairs(path: Path, track: str): raw = path.read_bytes() pairs = [json.loads(line) for line in raw.splitlines() if line] if not pairs: raise ValueError("Empty benchmark") seen = set() for pair in pairs: pair_id = pair["pair_id"] if pair_id in seen: raise ValueError("Duplicate pair ID") seen.add(pair_id) if track != "lint" and pair["domain"] != track: raise ValueError("Wrong benchmark domain") if track == "lint" and not pair.get("rule", {}).get("ensure"): raise ValueError("Missing semantic lint rule") return pairs, hashlib.sha256(raw).hexdigest() def saved_predictions(path: Path, pairs: list[dict], digest: str, track: str, pack: dict | None): expected = {(pair["pair_id"], role) for pair in pairs for role in ("before", "after")} rows = {} if not path.exists(): return rows for line in path.open(): row = json.loads(line) key = row["pair_id"], row["role"] if key not in expected or key in rows or row["dataset_sha256"] != digest: raise ValueError("Unexpected or duplicate saved prediction") if track == "lint": if row["protocol"] != LINT_PROTOCOL or row["model"] != MODEL: raise ValueError("Incompatible saved lint prediction") if abs(probability(row["score"]) + probability(row["rule_true_probability"]) - 1) > 1e-8: raise ValueError("Invalid saved lint score") else: if (row["protocol_id"] != pack["protocol_id"] or row.get("interface_id") != PROTOCOL or row["model_revision"] != MODEL or row["pack_sha256"] != pack["pack_sha256"]): raise ValueError("Incompatible saved scan prediction") rows[key] = row return rows def score_one(pair: dict, role: str, track: str, pack: dict | None, core, key: str, digest: str, limiter: RateLimiter, threshold: float) -> dict: state = pair[role]["state"] if track == "lint": questions = {"rule_true": lint_question(pair["rule"]["ensure"])} else: selected = core.detection_questions(core.scan_questions(pack, track, pair["language"]), track) questions = {question["name"]: type_question(question) for question in selected} if not questions: raise ValueError("No applicable detection questions") response = invoke(key, state, questions, limiter) usage = response.get("usage") or {} if track == "lint": true = true_score(response["result"]["rule_true"]) return {"pair_id": pair["pair_id"], "role": role, "domain": pair["domain"], "model": MODEL, "protocol": LINT_PROTOCOL, "dataset_sha256": digest, "rule_true_probability": true, "score": 1 - true, "usage": usage, "elapsed_s": response["request_elapsed_s"]} scores = {name: core.raised_score(question, true_score(response["result"][name])) for question in selected for name in (question["name"],)} score, alert = core.scan_result(scores, selected, track, threshold) return {"pair_id": pair["pair_id"], "role": role, "domain": track, "model_id": "typellm", "model_revision": MODEL, "protocol_id": pack["protocol_id"], "interface_id": PROTOCOL, "pack_sha256": pack["pack_sha256"], "dataset_sha256": digest, "question_scores": scores, "score": score, "alert": alert, "usage": usage, "elapsed_s": response["request_elapsed_s"]} def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--track", choices=("bug", "security", "lint"), required=True) parser.add_argument("--dataset", type=Path, required=True) parser.add_argument("--predictions", type=Path, required=True) parser.add_argument("--question-pack", type=Path, default=Path(__file__).with_name("question-pack.json")) parser.add_argument("--benchmark-script", type=Path, default=Path(__file__).with_name("benchmark.py")) parser.add_argument("--threshold", type=float, default=0.5) parser.add_argument("--workers", type=int, default=8) parser.add_argument("--interval", type=float, default=DEFAULT_INTERVAL) parser.add_argument("--limit", type=int, default=0) args = parser.parse_args() if not 0 <= args.threshold <= 1 or args.workers < 1 or args.interval < 0.6 or args.limit < 0: parser.error("Invalid threshold, workers, interval, or limit") key = os.environ.get("TYPELLM_API_KEY") if not key: raise RuntimeError("Set TYPELLM_API_KEY") core = module_at("perch_benchmark", args.benchmark_script) if args.track != "lint" else None pack = core.load_pack(args.question_pack) if core else None pairs, digest = load_pairs(args.dataset, args.track) existing = saved_predictions(args.predictions, pairs, digest, args.track, pack) 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] if not pending: print(f"{args.track}: already complete", flush=True) return args.predictions.parent.mkdir(parents=True, exist_ok=True) limiter = RateLimiter(args.interval) with args.predictions.open("a") as output, ThreadPoolExecutor(max_workers=args.workers) as pool: futures = [pool.submit(score_one, pair, role, args.track, pack, core, key, digest, limiter, args.threshold) for pair, role in pending] for index, future in enumerate(as_completed(futures), 1): row = future.result() output.write(json.dumps(row, sort_keys=True) + "\n") output.flush() if index % 100 == 0 or index == len(pending): print(f"{args.track}: {len(existing) + index}/{2 * len(pairs)} sides", flush=True) if __name__ == "__main__": main()