llm-bench

"""Offline tests for bench.tasks.reasoning. Run: python3 -m unittest discover -s tests"""
import gzip
import json
import os
import tempfile
import unittest

import _util  # noqa: F401
from bench.core import results
from bench.core.mockserver import MockServer, chat  # noqa: E402
from bench.tasks import reasoning as R  # noqa: E402


class LetterExtraction(unittest.TestCase):
    def test_cases(self):
        f = R.extract_letter
        self.assertEqual(f("blah\nANSWER: C"), "C")
        self.assertEqual(f("ANSWER: (C)"), "C")
        self.assertEqual(f("ANSWER:(J)"), "J")
        self.assertEqual(f("answer: c"), "C")
        self.assertEqual(f("**ANSWER: B**"), "B")
        self.assertEqual(f("ANSWER: A\nmore\nANSWER: D"), "D")  # last wins
        self.assertEqual(f("ANSWER: B\n\n(D)\n"), "B")  # explicit ANSWER beats a stray lone letter
        self.assertIsNone(f("I could not decide."))
        self.assertIsNone(f(""))
        self.assertIsNone(f("The reasoning is long and gets cut off in the mid"))  # truncated
        self.assertEqual(f("so the answer is\nc"), "C")  # lone-letter fallback
        self.assertIsNone(f("ANSWER: a long story about it"))  # lowercase word, not a letter
        self.assertIsNone(f("ANSWER: K"))  # out of A-J

    def test_grade(self):
        item = {"item_id": "mmlu-pro-cs/1", "answer_index": 8}
        self.assertTrue(R.grade(item, "ANSWER: I")["correct"])
        self.assertEqual(R.grade(item, "ANSWER: I")["gold"], "I")
        self.assertFalse(R.grade(item, "nothing")["correct"])


def fake_rows():
    """Fixed fake raw rows for selection tests."""
    return {"test": [{"question_id": i, "question": f"q{i}", "options": ["a", "b"],
                      "answer": "A", "answer_index": 0, "category": "computer science" if i % 2 else "law",
                      "src": "s"} for i in range(40)]}


class Selection(unittest.TestCase):
    def setUp(self):
        self._n, R.MMLU_CS_N = R.MMLU_CS_N, 3

    def tearDown(self):
        R.MMLU_CS_N = self._n

    def test_deterministic_hash_ordered_cs_only(self):
        a = R.build_items("mmlu-pro-cs", fake_rows())
        rows = fake_rows()
        rows["test"].reverse()
        b = R.build_items("mmlu-pro-cs", rows)
        self.assertEqual(sorted(i["item_id"] for i in a), sorted(i["item_id"] for i in b))
        self.assertEqual({i["category"] for i in a}, {"cs"})
        want = sorted((str(i) for i in range(40) if i % 2), key=lambda n: R.sel_key("mmlu-pro-cs", n))[:3]
        self.assertEqual(sorted(i["native_id"] for i in a), sorted(want))
        with self.assertRaises(ValueError):
            R.build_items("aime26", fake_rows())

    def test_manifest_and_validate(self):
        old = (R.DATA_DIR, R.CACHE_DIR)
        R.DATA_DIR = tempfile.mkdtemp()
        R.CACHE_DIR = os.path.join(R.DATA_DIR, "cache")
        try:
            items = R.build_items("mmlu-pro-cs", fake_rows())
            m = R.write_set("mmlu-pro-cs", items)
            self.assertEqual(m["n"], 3)
            self.assertEqual(m["items"][0]["sha256"], R.item_sha(items[0]))
            loaded, m2 = R.load_items("mmlu-pro-cs")
            self.assertEqual(len(loaded), 3)
            self.assertEqual(R.cmd_validate(["mmlu-pro-cs"]), 0)
            # tamper
            p = os.path.join(R.CACHE_DIR, "mmlu-pro-cs.jsonl")
            with open(p) as fh:
                lines = fh.read().splitlines()
            d = json.loads(lines[0])
            d["question"] = "changed"
            lines[0] = json.dumps(d)
            with open(p, "w") as fh:
                fh.write("\n".join(lines) + "\n")
            with self.assertRaises(ValueError):
                R.load_items("mmlu-pro-cs")
            self.assertEqual(R.cmd_validate(["mmlu-pro-cs"]), 1)
        finally:
            R.DATA_DIR, R.CACHE_DIR = old


ITEMS = [
    {"item_id": "mmlu-pro-cs/1", "native_id": "1", "category": "cs", "question": "q1",
     "options": ["x", "y", "z"], "answer": "B", "answer_index": 1},
    {"item_id": "mmlu-pro-cs/2", "native_id": "2", "category": "cs", "question": "q2",
     "options": ["x", "y", "z"], "answer": "C", "answer_index": 2},
    {"item_id": "mmlu-pro-cs/3", "native_id": "3", "category": "cs", "question": "q3",
     "options": ["x", "y", "z"], "answer": "A", "answer_index": 0},
]
MANIFEST = {"manifest_hash": "abc123def456"}


class EndToEnd(unittest.TestCase):
    def test_run_http500_and_resume(self):
        def responder(body):
            q = body["messages"][-1]["content"]
            if q.startswith("q1"):
                return (500, {"error": "template raised"})
            if q.startswith("q2"):
                return chat("hmm\nANSWER: C", reasoning="thinking " * 100)
            return chat("it is probably ANSWER: B", finish="length", reasoning="r")
        with MockServer() as srv:
            srv.default = responder
            lane = srv.lane(lane_id="reasoning-e2e", max_concurrency=2)
            store, summary = R.run_set("mmlu-pro-cs-test", ITEMS, MANIFEST, lane=lane, samples=2,
                                       concurrency=4, keep_reasoning=True)
            self.assertEqual(len(srv.requests), 6)
            rows = [json.loads(l) for l in open(store.items_path)]
            self.assertEqual(len(rows), 6)
            by = {}
            for r in rows:
                by.setdefault(r["item_id"], []).append(r)
            self.assertTrue(all(r["status"] == "http_500" and r["correct"] is None for r in by["mmlu-pro-cs/1"]))
            q2 = by["mmlu-pro-cs/2"][0]
            self.assertTrue(q2["correct"])
            self.assertEqual((q2["extracted"], q2["gold"]), ("C", "C"))
            self.assertEqual(len(q2["reasoning_head"]), 400)
            self.assertTrue(os.path.exists(os.path.join(store.dir, q2["reasoning_file"])))
            with gzip.open(os.path.join(store.dir, q2["reasoning_file"]), "rt") as f:
                self.assertTrue(f.read().startswith("thinking"))
            a = by["mmlu-pro-cs/3"][0]
            self.assertEqual(a["status"], "truncated")
            self.assertIs(a["correct"], False)  # B != A, still graded
            self.assertIn("ANSWER", a["content_tail"])
            cat = summary["by_category"]["cs"]
            self.assertEqual((cat["infra"], cat["graded"], cat["truncated"]), (2, 4, 2))
            self.assertIsNone(summary["stopped"])
            # resume: only the two http_500 attempts re-run
            srv.requests.clear()
            srv.default = lambda body: chat("ANSWER: B")
            store2, summary2 = R.run_set("mmlu-pro-cs-test", ITEMS, MANIFEST, lane=lane, samples=2,
                                         concurrency=2, resume_dir=store.dir)
            self.assertEqual(len(srv.requests), 2)
            self.assertEqual(store2.run_id, store.run_id)
            rows = [json.loads(l) for l in open(store.items_path)]
            ok = [r for r in rows if r["item_id"] == "mmlu-pro-cs/1" and r["status"] == "ok"]
            self.assertEqual(len(ok), 2)
            self.assertTrue(all(r["correct"] for r in ok))
            # the summary counts each (item, sample) once: retried rows replace the http_500s
            cs = summary2["by_category"]["cs"]
            self.assertEqual((cs["n"], cs["graded"], cs["infra"]), (6, 6, 0))

    def test_budget_stop(self):
        cost = {"ledger": "reasoning-unittest-cap", "cap_usd": 0.001, "in_per_m": 1.0, "out_per_m": 10.0}
        with MockServer() as srv:
            srv.default = chat("ANSWER: B", cost=0.0005)
            lane = srv.lane(lane_id="reasoning-budget", cost=cost, request={"max_tokens": 5000})
            store, summary = R.run_set("mmlu-pro-cs-test", ITEMS[:2], MANIFEST, lane=lane, samples=1,
                                       concurrency=1)
            self.assertEqual(summary["stopped"], "budget_stop")
            self.assertEqual(len(results.load_rows(INSTR, "reasoning-budget")), 0)  # incomplete


INSTR = "reasoning"

if __name__ == "__main__":
    unittest.main()