#!/usr/bin/env python3 """Exercise paired benchmark ordering, readiness, quality and secret handling.""" import http.server from importlib.machinery import SourceFileLoader import json import pathlib import stat import subprocess import tempfile import threading TOKEN = "fixture-token-do-not-log" HEALTH_CHECKS = 0 class Handler(http.server.BaseHTTPRequestHandler): def do_GET(self): global HEALTH_CHECKS HEALTH_CHECKS += 1 self.reply({"loaded": True, "max_context": 0 if HEALTH_CHECKS == 1 else 262144}) def do_POST(self): if self.headers.get("Authorization") != "Bearer " + TOKEN: self.send_error(401) return body = json.loads(self.rfile.read(int(self.headers["Content-Length"]))) if "tools" in body: message = {"role": "assistant", "content": None, "tool_calls": [{"function": {"name": "get_weather", "arguments": '{"city":"Paris"}'}}]} finish = "tool_calls" else: question = body["messages"][0]["content"] message = {"role": "assistant", "content": "323" if "17 * 19" in question else "Cora"} finish = "stop" self.reply({"choices": [{"message": message, "finish_reason": finish}], "usage": {"prompt_tokens": 20, "completion_tokens": 2}, "timings": {"prompt_n": 20, "prompt_per_second": 200.0, "predicted_n": 2, "predicted_per_second": 50.0}}) def reply(self, payload): data = json.dumps(payload).encode() self.send_response(200) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(data))) self.end_headers() self.wfile.write(data) def log_message(self, *_args): pass def main(): root = pathlib.Path(__file__).resolve().parent.parent benchmark = SourceFileLoader("chat_benchmark", str(root / "scripts/bench-chat-paired.py")).load_module() quality = json.loads((root / "benchmarks/fixtures/chat/quality-v1.json").read_text()) long_case = next(case for case in quality["cases"] if case["id"] == "long-retrieval") prompt = benchmark.materialize_messages(long_case["messages"])[0]["content"] assert prompt.count("filler row:") == 4400 assert prompt.count("VALID AUDIT CODE: amber-731") == 1 failed = [{"arm": arm, "case_id": "broken", "repeat": 0, "warmup": False, "wall_seconds": 1.0, "http_status": 500, "response": {}, "quality": {"passed": False}} for arm in ("baseline", "candidate")] assert benchmark.summarize(failed, True)["paired"]["same_normalized_output"] == 0 server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) thread = threading.Thread(target=server.serve_forever, daemon=True) thread.start() try: with tempfile.TemporaryDirectory() as directory: private = pathlib.Path(directory) config = private / "config.json" config.write_text(json.dumps({"api_key": TOKEN})) report = private / "report.json" url = f"http://127.0.0.1:{server.server_port}" subprocess.run([ "python3", str(root / "scripts/bench-chat-paired.py"), "--suite", str(root / "benchmarks/fixtures/chat/paired-smoke.json"), "--baseline-url", url + "/chat", "--candidate-url", url + "/chat", "--baseline-ready-url", url + "/health", "--candidate-ready-url", url + "/health", "--baseline-auth-config", str(config), "--model", "mock", "--repeats", "1", "--output", str(report), ], check=True, capture_output=True, text=True) data = report.read_text() assert TOKEN not in data assert stat.S_IMODE(report.stat().st_mode) == 0o600 summary = json.loads(data)["summary"] assert summary["baseline"]["quality_passed"] == 3 assert summary["candidate"]["quality_passed"] == 3 assert summary["paired"]["pairs"] == 3 assert summary["paired"]["same_normalized_output"] == 3 assert HEALTH_CHECKS >= 3 solo = [] for name in ("baseline", "candidate"): path = private / f"{name}.json" subprocess.run([ "python3", str(root / "scripts/bench-chat-paired.py"), "--suite", str(root / "benchmarks/fixtures/chat/paired-smoke.json"), "--baseline-url", url + "/chat", "--baseline-auth-config", str(config), "--model", "mock", "--repeats", "1", "--output", str(path), ], check=True, capture_output=True, text=True) solo.append(path) compared = private / "sequential-comparison.json" subprocess.run([ "python3", str(root / "scripts/compare-chat-reports.py"), str(solo[0]), str(solo[1]), "--output", str(compared), ], check=True, capture_output=True, text=True) assert stat.S_IMODE(compared.stat().st_mode) == 0o600 assert TOKEN not in compared.read_text() sequential = json.loads(compared.read_text())["summary"] assert sequential["pairs"] == 3 assert sequential["same_normalized_output"] == 3 assert sequential["candidate_quality_passed"] == 3 assert sequential["decode"]["pairs"] == 3 assert sequential["prefill"]["candidate_over_baseline_median_ratio"] == 1.0 finally: server.shutdown() server.server_close() print("paired benchmark harness: OK") if __name__ == "__main__": main()