"""Offline tests for bench.core (lane, client, ledger, results) against MockServer. Run from llm-bench/: python3 -m unittest discover -s tests -v """ import json import os import unittest import _util # noqa: F401 from bench.core import client, ledger, results from bench.core.lane import Lane, LaneError # noqa: E402 from bench.core.mockserver import MockServer, chat, tool_call # noqa: E402 class BodyMerge(unittest.TestCase): def lane(self, **kw): raw = {"lane_id": "t", "endpoint": "http://x/v1/chat/completions", "model": "m"} raw.update(kw) return Lane(raw, "test") def test_lane_request_wins_over_instrument_defaults(self): lane = self.lane(request={"temperature": 1.0, "top_k": 20, "max_tokens": 32768}) body = client.build_body([{"role": "user", "content": "q"}], max_tokens=2000, temperature=0.0, lane=lane) self.assertEqual(body["temperature"], 1.0) self.assertEqual(body["max_tokens"], 32768) self.assertEqual(body["top_k"], 20) def test_override_wins_over_lane(self): lane = self.lane(request={"temperature": 1.0}) body = client.build_body([{"role": "user", "content": "q"}], override={"temperature": 0}, lane=lane) self.assertEqual(body["temperature"], 0) def test_extra_body_deep_merges(self): lane = self.lane(extra_body={"provider": {"order": ["deepinfra"]}, "usage": {"include": True}}) body = client.build_body([{"role": "user", "content": "q"}], lane=lane, override={"provider": {"allow_fallbacks": False}}) self.assertEqual(body["provider"], {"allow_fallbacks": False, "order": ["deepinfra"]}) def test_nothink_mechanisms(self): msgs = [{"role": "user", "content": "q"}] b = client.build_body(msgs, lane=self.lane(thinking="off", nothink={"mechanism": "reasoning_effort_none"})) self.assertEqual(b["reasoning_effort"], "none") b = client.build_body(msgs, lane=self.lane(thinking="off", nothink={"mechanism": "openrouter_reasoning_off"})) self.assertFalse(b["reasoning"]["enabled"]) b = client.build_body(msgs, lane=self.lane(thinking="off", nothink={"mechanism": "template_kwargs"})) self.assertFalse(b["chat_template_kwargs"]["enable_thinking"]) b = client.build_body(msgs, lane=self.lane(thinking="off", nothink={"mechanism": "think_prefill"})) self.assertEqual(b["messages"][-1]["role"], "assistant") with self.assertRaises(LaneError): self.lane(thinking="off") # no mechanism def test_thinking_on_lane_never_gets_nothink(self): b = client.build_body([{"role": "user", "content": "q"}], lane=self.lane()) self.assertNotIn("reasoning_effort", b) self.assertEqual(len(b["messages"]), 1) def test_forbid_guard(self): lane = self.lane(request={"reasoning_effort": "high"}, forbid={"reasoning_effort": ["high"]}) with self.assertRaises(client.CallError) as cm: client.build_body([{"role": "user", "content": "q"}], lane=lane) self.assertEqual(cm.exception.label(), "guard_refused") def test_history_sanitized(self): hist = [{"role": "user", "content": "q"}, {"role": "assistant", "content": "", "reasoning_content": "long thoughts", "tool_calls": [tool_call("write_file", '{"path": "a.go", "content": "unterm'), tool_call("list_files", "", "c1"), {"id": "c2", "type": "function", "function": {"name": "x", "arguments": {"a": 1}}}]}, {"role": "tool", "tool_call_id": "call_0", "content": "ERROR"}] b = client.build_body(hist, lane=self.lane()) a = b["messages"][1] self.assertNotIn("reasoning_content", a) self.assertEqual(a["tool_calls"][0]["function"]["arguments"], "{}") self.assertEqual(a["tool_calls"][1]["function"]["arguments"], "{}") self.assertEqual(json.loads(a["tool_calls"][2]["function"]["arguments"]), {"a": 1}) self.assertIn("unterm", hist[1]["tool_calls"][0]["function"]["arguments"]) # caller untouched keep = client.build_body(hist, lane=self.lane(reasoning_echo=True)) self.assertIn("reasoning_content", keep["messages"][1]) def test_merge_system_messages(self): msgs = [{"role": "user", "content": "q"}, {"role": "system", "content": "A"}, {"role": "system", "content": "B"}] b = client.build_body(msgs, lane=self.lane(merge_system_messages=True)) self.assertEqual(b["messages"][0], {"role": "system", "content": "A\n\nB"}) self.assertEqual([m["role"] for m in b["messages"]], ["system", "user"]) class Extraction(unittest.TestCase): def test_reasoning_fields(self): self.assertEqual(client.reasoning(chat("a", reasoning="r1")), "r1") self.assertEqual(client.reasoning(chat("a", reasoning="r2", reasoning_field="reasoning")), "r2") inline = chat("hmm\n\nANSWER: 4") self.assertEqual(client.reasoning(inline), "hmm") self.assertEqual(client.content(inline), "ANSWER: 4") unclosed = chat("still going", finish="length") self.assertEqual(client.content(unclosed), "") self.assertEqual(client.status(unclosed), "truncated") def test_usage_none_is_not_zero(self): u = client.usage(chat("a")) self.assertIsNone(u["reasoning_tokens"]) self.assertIsNone(u["cost_usd"]) u = client.usage(chat("a", reasoning_tokens=0, cost=0.001)) self.assertEqual(u["reasoning_tokens"], 0) self.assertEqual(u["cost_usd"], 0.001) def test_status_empty(self): self.assertEqual(client.status(chat("")), "empty") self.assertEqual(client.status(chat("", tool_calls=[tool_call("f", "{}")])), "ok") class Transport(unittest.TestCase): def test_retry_then_success_and_auth(self): with MockServer() as srv: srv.script = [(429, {"error": "slow"}), (503, {"error": "busy"}), chat("ok")] os.environ["T_KEY"] = "sekrit" lane = srv.lane(auth={"env": "T_KEY"}) resp, _ = client.call_model([{"role": "user", "content": "q"}], lane=lane) self.assertEqual(client.content(resp), "ok") self.assertEqual(resp["_bench"]["attempts"], 3) self.assertEqual(srv.requests[-1]["auth"], "Bearer sekrit") self.assertNotIn("sekrit", json.dumps(lane.record())) def test_500_not_retried(self): with MockServer() as srv: srv.script = [(500, {"error": "template raised"}), chat("never")] with self.assertRaises(client.CallError) as cm: client.call_model([{"role": "user", "content": "q"}], lane=srv.lane()) self.assertEqual(cm.exception.label(), "http_500") self.assertEqual(len(srv.requests), 1) def test_oom_label(self): with MockServer() as srv: srv.script = [(507, {"error": "out of memory"})] with self.assertRaises(client.CallError) as cm: client.call_model([{"role": "user", "content": "q"}], lane=srv.lane()) self.assertEqual(cm.exception.label(), "oom") def test_openrouter_200_with_error(self): with MockServer() as srv: srv.script = [{"error": {"code": 502, "message": "provider down"}}, chat("ok")] resp, _ = client.call_model([{"role": "user", "content": "q"}], lane=srv.lane()) self.assertEqual(client.content(resp), "ok") def test_timeout_label(self): import time as _t with MockServer() as srv: srv.script = [lambda body: (_t.sleep(1.5), chat("late"))[1]] with self.assertRaises(client.CallError) as cm: client.call_model([{"role": "user", "content": "q"}], lane=srv.lane(http_timeout=1)) self.assertEqual(cm.exception.label(), "timeout") class Budget(unittest.TestCase): def test_cap_stops_before_overspend(self): cost = {"ledger": "unittest-cap", "cap_usd": 0.05, "in_per_m": 1.0, "out_per_m": 10.0} with MockServer() as srv: srv.default = chat("ok", cost=0.008) # actual <= worst case, as with real pricing lane = srv.lane(cost=cost, request={"max_tokens": 1000}) # worst case ~$0.01/call n_ok = 0 for i in range(10): try: client.call_model([{"role": "user", "content": "q"}], lane=lane, item_id=f"i{i}") n_ok += 1 except client.CallError as e: self.assertEqual(e.label(), "budget_stop") break # spent 0.008*k; call k+1 allowed while spent + ~0.01 <= 0.05 -> 5 calls, then stop self.assertEqual(n_ok, 5) self.assertLessEqual(ledger.spent("unittest-cap"), 0.05) def test_missing_provider_cost_is_estimated(self): cost = {"ledger": "unittest-est", "cap_usd": 1.0, "in_per_m": 1.0, "out_per_m": 2.0} with MockServer() as srv: srv.default = chat("ok", prompt_tokens=1000, completion_tokens=500) resp, _ = client.call_model([{"role": "user", "content": "q"}], lane=srv.lane(cost=cost)) self.assertAlmostEqual(resp["_bench"]["cost_usd"], 0.002) self.assertTrue(resp["_bench"]["cost_estimated"]) class Store(unittest.TestCase): def test_run_layout_and_rows(self): with MockServer() as srv: lane = srv.lane(lane_id="store-test", auth={"env": "T_KEY"}) st = results.RunStore("unit", item_set="set@1", args={"k": 1}, lane=lane) resp, dt = client.call_model([{"role": "user", "content": "q"}], lane=lane) st.add(item_id="a", category="go", correct=True, **client.meta(resp, dt)) st.add(item_id="b", category="go", correct=False, status="http_500") d = st.finish({"n": 2}) run = json.load(open(os.path.join(d, "run.json"))) self.assertTrue(run["complete"]) self.assertEqual(run["lane"]["lane_id"], "store-test") self.assertNotIn("auth", run["lane"]) self.assertIn("chat_template_sha256", run["server"]["props"]) rows = results.load_rows("unit", "store-test") self.assertEqual({r["item_id"]: r["correct"] for r in rows}, {"a": True, "b": None}) st2 = results.RunStore("unit", lane=lane) self.assertNotEqual(st2.run_id, st.run_id) self.assertEqual(len(results.load_rows("unit", "store-test")), 2) # st2 incomplete def test_resume_and_sidecar(self): with MockServer() as srv: lane = srv.lane(lane_id="resume-test") st = results.RunStore("unit-resume", lane=lane) st.add(item_id="a", sample_idx=0, correct=True) st.add(item_id="a", sample_idx=1, status="timeout") name = st.sidecar("a-0.turns", {"turns": [1, 2]}) self.assertTrue(os.path.exists(os.path.join(st.dir, name))) again = results.RunStore.resume(st.dir, lane=lane) self.assertEqual(again.run_id, st.run_id) self.assertEqual(again.done_keys(), {("a", 0)}) # the timeout gets retried again.add(item_id="a", sample_idx=1, correct=False) again.finish() rows = results.load_rows("unit-resume", "resume-test") # the retry replaces the timeout self.assertEqual([(r["sample_idx"], r["status"]) for r in rows], [(0, "ok"), (1, "ok")]) with self.assertRaises(ValueError): results.RunStore.resume(st.dir, lane=srv.lane(lane_id="other")) if __name__ == "__main__": unittest.main()