#!/usr/bin/env python3 """跑分与判分脚本的自测:全部用假调用,不碰任何真实模型。用法:selftest.py""" import json import pathlib import sys import tempfile sys.path.insert(0, str(pathlib.Path(__file__).parent)) import run_eval # noqa: E402 import score # noqa: E402 BASE = {"model_requested": "m", "setting": "open", "channel": "api", "questions_sha256": "q", "prompts_sha256": "p", "endpoint": "e", "temperature": 0} def mkq(i, same): a = {"1": "GND", "2": "VOUT", "3": "VIN"} b = a if same else {"1": "VIN", "2": "GND", "3": "VOUT"} return {"id": f"t-{i:02d}", "class": "B" if same else "A", "library": "L", "package": "P", "part_a": f"t-{i:02d}", "part_b": "B", "pins_a": a, "pins_b": b, "answer": {"same_pinout": same, "different_pins": [] if same else ["1", "2", "3"]}} QS = [mkq(i, i % 2 == 0) for i in range(8)] GOLD = {q["id"]: json.dumps(q["answer"]) for q in QS} BYPROMPT = {run_eval.user_prompt(q, "open"): q["id"] for q in QS} def lines(path, ev): return [r for r in map(json.loads, open(path)) if r["ev"] == ev] def finals(path): return {r["id"]: r for r in lines(path, "final")} def runit(path, once, workers=4): return run_eval.run(QS, path, {}, "open", BASE, workers, once, sleep=lambda s: None, man=BASE) def ok(qid, **kw): return dict({"status": "ok", "tool_calls": 0, "model_returned": "m", "finish_reason": "stop", "content": GOLD[qid], "usage": None}, **kw) def check(name, cond): print(("通过 " if cond else "失败 ") + name) if not cond: sys.exit(1) def stops(fn): try: fn() return False except SystemExit: return True d = pathlib.Path(tempfile.mkdtemp()) # 1 残尾:上次写到一半,续跑不能把下一条结果吞掉,也不重调已完成的题 p = d / "torn.jsonl" calls = [] runit(p, lambda cfg, u: (calls.append(1), ok(BYPROMPT[u]))[1]) with open(p, "a") as f: f.write('{"ev":"final","id":"t-99"') n0 = len(calls) runit(p, lambda cfg, u: (calls.append(1), ok(BYPROMPT[u]))[1]) check("残尾被截掉,已完成的 8 题不重调", len(calls) == n0 and len(finals(p)) == 8) # 2 中间坏行、不认识的记录、身份对不上的 final:都停 p = d / "bad.jsonl" p.write_text('{"ev":"noresp","id":"t-00","error":"x"}\n这不是 json\n{"ev":"noresp","id":"t-01","error":"x"}\n') check("中间坏行要停", stops(lambda: run_eval.load_done(p))) p.write_text('{"ev":"refund","id":"t-00"}\n') # 旧版才有的记录 check("不认识的记录类型要停", stops(lambda: run_eval.load_done(p))) p.write_text(json.dumps(dict(BASE, ev="final", id="t-00", model_requested="别的模型")) + "\n") check("和 manifest 对不上的 final 要停", stops(lambda: run_eval.load_done(p, BASE))) # 3 每题只取第一份完整返回:拿不到返回的请求重发,拿到之后不再调 p = d / "first.jsonl" turn = {} def once_flaky(cfg, u): qid = BYPROMPT[u] turn[qid] = turn.get(qid, 0) + 1 return run_eval.noresp("HTTP 500") if (qid == "t-01" and turn[qid] <= 2) else ok(qid) new, halt = runit(p, once_flaky) check("两次没返回后第三次拿到:落 final,记 requests_without_response=2", halt is None and finals(p)["t-01"]["requests_without_response"] == 2 and turn["t-01"] == 3) runit(p, once_flaky) check("续跑不再调任何已有 final 的题", turn["t-01"] == 3 and all(v == 1 for k, v in turn.items() if k != "t-01")) # 4 连续 5 次拿不到返回:整轮停,这题不落 final;恢复后补上 p = d / "halt.jsonl" cnt = {"n": 0} def once_dead(cfg, u): if BYPROMPT[u] == "t-03": cnt["n"] += 1 return run_eval.noresp("HTTP 402 usage limit") return ok(BYPROMPT[u]) new, halt = runit(p, once_dead, workers=1) check("连续 5 次没返回:停跑、不落这题的 final", bool(halt) and cnt["n"] == 5 and "t-03" not in finals(p)) check("停跑时每次没返回都记了日志", len([r for r in lines(p, "noresp") if r["id"] == "t-03"]) == 5) runit(p, lambda cfg, u: ok(BYPROMPT[u])) check("恢复后 8 题齐了", len(finals(p)) == 8) # 5 没拿到返回的那几次请求用没用工具都不相干;只有产生 final 的那次算 p = d / "tools.jsonl" runit(p, lambda cfg, u: ok(BYPROMPT[u], tool_calls=2 if BYPROMPT[u] == "t-01" else 0)) check("final 那次请求调了工具:tool_calls 记 2", finals(p)["t-01"]["tool_calls"] == 2 and finals(p)["t-02"]["tool_calls"] == 0) # 5b 进程死在一次请求中间(有 sent、没有结果):续跑记「结果不明」再重发,final 行里报出来 p = d / "dangling.jsonl" p.write_text('{"ev":"sent","id":"t-02"}\n') runit(p, lambda cfg, u: ok(BYPROMPT[u])) check("结果不明的请求:记一行 unknown_outcome,final 里报 1 次", len(lines(p, "unknown_outcome")) == 1 and finals(p)["t-02"]["requests_with_unknown_outcome"] == 1 and finals(p)["t-03"]["requests_with_unknown_outcome"] == 0) with open(p, "a") as f: f.write('{"ev":"sent","id":"t-02"}\n') check("final 之后同一题又有记录:停", stops(lambda: run_eval.load_state(p, BASE))) # 5c 调用函数自己抛异常:当没拿到返回,不崩 p = d / "raise.jsonl" state = {"n": 0} def once_raise(cfg, u): state["n"] += 1 if state["n"] == 1: raise FileNotFoundError("codex") return ok(BYPROMPT[u]) new, halt = runit(p, once_raise, workers=1) check("调用函数抛异常:记 noresp 后重发,8 题齐", halt is None and len(finals(p)) == 8 and len(lines(p, "noresp")) == 1) # 6 判分 NOW = "2026-12-05T10:00:00+0800" def rows_of(f=lambda q: GOLD[q["id"]], **kw): return {q["id"]: dict(dict(BASE, ev="final", id=q["id"], content=f(q), tool_calls=0, called_at=NOW), **kw) for q in QS} def col(rows, qs=QS, man=None): return score.score_column(man or dict(BASE), rows, QS, qs) s = col(rows_of()); check("全对:100 / 100,有效", s["judge_acc"] == 1 and s["full_correct"] == 1 and s["valid"]) s = col(rows_of(tool_calls=1)); check("全部调过工具:零分,格式失败率 0,不作废", s["judge_acc"] == 0 and s["format_fail"] == 0 and not s["void"] and s["tool_violation_questions"] == 8 and s["tool_calls_total"] == 8) r3 = {k: v for k, v in rows_of().items() if k != "t-00"} s = col(r3, qs=[q for q in QS if q["id"] != "t-00"]); check("缺的题被剔除:仍然算没跑完,不进验证性", not s["complete"] and not s["valid"] and not s["confirmatory"]) r4 = rows_of(); r4["t-01"]["content"] = [{"type": "text"}] s = col(r4); check("content 不是字符串:算格式失败,不崩", abs(s["format_fail"] - 1 / 8) < 1e-9) r5 = rows_of(); r5["t-01"]["content"] = '{"same_pinout": false, "different_pins": [1.0, 2, 3]}' s = col(r5); check("脚号写成小数:格式失败", abs(s["format_fail"] - 1 / 8) < 1e-9) s = col(rows_of(), qs=[q for q in QS if q["id"] != "t-01"]); check("剔除一题:同时给出剔除前的数字", s["n"] == 7 and s["before_exclusion"]["n"] == 8) s = col(rows_of()); check("名单外的模型:不进验证性", not s["confirmatory"] and s["valid"]) MAN = dict(BASE, model_requested="deepseek-flash", endpoint="https://api.deepseek.com/v1") def rows_m(at): return {k: dict(v, model_requested="deepseek-flash", endpoint="https://api.deepseek.com/v1", called_at=at) for k, v in rows_of().items()} s = col(rows_m(NOW), man=MAN); check("名单内、截止日前:验证性", s["confirmatory"]) s = col(rows_m("2026-12-19T00:00:01+0800"), man=MAN); check("名单内、截止日后:不进验证性", not s["confirmatory"]) s = col(rows_m(NOW), man=dict(MAN, endpoint="https://openrouter.ai/api/v1")); check("名单内的名字、但接口不是名单写的那个:不进验证性", not s["confirmatory"]) check("接口主机名精确比对:带上游域名的代理地址不算", not score.endpoint_is("https://api.deepseek.com.proxy.example/v1", "api.deepseek.com") and not score.endpoint_is("https://proxy.example/api.deepseek.com/v1", "api.deepseek.com") and score.endpoint_is("https://api.deepseek.com/v1", "api.deepseek.com")) print("全部通过")