llm-bench

"""Offline tests for bench/tasks/needle.py (MockServer only)."""
import io
import re
import unittest
from contextlib import redirect_stdout

from _util import run_dir, run_main
from bench.core import lane as lane_mod, results
from bench.core.mockserver import MockServer, chat  # noqa: E402
from bench.tasks import needle as nd  # noqa: E402


class Generator(unittest.TestCase):
    def test_deterministic(self):
        for v in nd.VARIANTS:
            self.assertEqual(nd.build_item(1000, 0.5, 3, v), nd.build_item(1000, 0.5, 3, v))
        self.assertNotEqual(nd.build_item(1000, 0.5, 0, "plain")["prompt"],
                            nd.build_item(1000, 0.5, 1, "plain")["prompt"])

    def test_item_id_stable_across_depth_order_and_position_subset(self):
        a = {nd.item_id(*k) for k in nd.grid([1000, 4000, 16000], nd.POSITION_GRID, nd.VARIANTS, 1)}
        b = {nd.item_id(*k) for k in nd.grid([16000, 1000, 4000], nd.POSITION_GRID[::-1], nd.VARIANTS[::-1], 1)}
        self.assertEqual(a, b)
        sub = {nd.item_id(*k) for k in nd.grid([4000], [0.5], ["decoy"], 1)}
        self.assertTrue(sub <= a)
        self.assertEqual(len(a), 3 * 5 * 3)  # no collisions
        # id does not depend on the chars-per-token estimate
        self.assertEqual(nd.build_item(1000, 0.5, 0, "plain", cpt=3.0)["item_id"],
                         nd.build_item(1000, 0.5, 0, "plain", cpt=5.0)["item_id"])

    def test_decoy_same_place_and_both_codes_present(self):
        for seed in range(6):
            it = nd.build_item(4000, 0.5, seed, "decoy")
            p = it["prompt"]
            old = it["others"][0]
            cur_s = [m for m in re.findall(r"[^\n]*Maintenance note[^\n]*", p) if it["gold"] in m][0]
            old_s = [m for m in re.findall(r"[^\n]*Maintenance note[^\n]*", p) if old in m][0]
            self.assertIn("for the %s " % it["place"], cur_s)
            self.assertIn("for the %s " % it["place"], old_s)
            self.assertIn("rotated out", old_s)
            self.assertNotIn("rotated", cur_s)
            self.assertIn("CURRENT", p.split("QUESTION:")[1])
            self.assertEqual(sorted(nd.CODE_RE.findall(p)), sorted([it["gold"], old]))
        orders = {nd.build_item(4000, 0.5, s, "decoy")["decoy_order"] for s in range(12)}
        self.assertEqual(orders, {"old_first", "old_last"})

    def test_multikey_has_k_keys_and_asks_one(self):
        it = nd.build_item(4000, 0.7, 0, "multikey")
        codes = nd.CODE_RE.findall(it["prompt"])
        self.assertEqual(len(codes), nd.MULTIKEY_K)
        self.assertGreaterEqual(nd.MULTIKEY_K, 4)
        self.assertIn(it["gold"], codes)
        self.assertEqual(len(it["others"]), nd.MULTIKEY_K - 1)
        self.assertEqual(it["prompt"].count(it["place"]), 2)  # the key line + the question

    def test_filler_has_no_code_like_tokens_and_size_tracks_depth(self):
        it = nd.build_item(16000, 0.5, 0, "plain")
        self.assertEqual(nd.CODE_RE.findall(it["prompt"]), [it["gold"]])
        self.assertAlmostEqual(it["est_tokens"], 16000, delta=800)

    def test_validate_passes(self):
        with redirect_stdout(io.StringIO()):
            self.assertTrue(nd.validate())


class Scoring(unittest.TestCase):
    def test_rejects_answer_listing_both_codes(self):
        self.assertTrue(nd.score_answer("EMERALD-1111", "EMERALD-1111", ["COPPER-2222"])["correct"])
        self.assertFalse(nd.score_answer("EMERALD-1111 or COPPER-2222", "EMERALD-1111", ["COPPER-2222"])["correct"])
        self.assertFalse(nd.score_answer("COPPER-2222", "EMERALD-1111", ["COPPER-2222"])["correct"])
        self.assertFalse(nd.score_answer("", "EMERALD-1111", [])["correct"])
        # a longer number is a different token, not a substring hit
        self.assertFalse(nd.score_answer("EMERALD-11112", "EMERALD-1111", [])["correct"])


def run_nd(srv, lane_id, argv, **lane_kw):
    lane_mod.set_current(srv.lane(lane_id=lane_id, **lane_kw))
    rc = run_main(nd, ["run"] + argv)
    return rc, sorted(results.load_rows("needle", lane_id), key=lambda r: r["item_id"])


class Run(unittest.TestCase):
    def test_correct_wrong_and_decoy_rows_and_cache_override(self):
        def answer(body):
            q = body["messages"][-1]["content"]
            # mock model: always returns the FIRST code in the document (the old one when old_first)
            return chat(nd.CODE_RE.findall(q)[0], prompt_tokens=4100, completion_tokens=6,
                        timings={"prompt_per_second": 900.0, "cache_n": 0})

        with MockServer() as srv:
            srv.default = answer
            rc, rows = run_nd(srv, "nd-run", ["--depths", "1000", "--positions", "0.5", "--seeds", "4",
                                              "--variants", "decoy"])
            self.assertEqual(rc, 0)
            self.assertEqual(len(srv.requests), 4)
            self.assertTrue(all(q["body"].get("cache_prompt") is False for q in srv.requests))
        self.assertEqual(len(rows), 4)
        for r in rows:
            first_is_old = r["decoy_order"] == "old_first"
            self.assertEqual(r["correct"], not first_is_old, r["decoy_order"])
            self.assertEqual(r["category"], "needle/1k/decoy")
            self.assertEqual(r["prompt_tokens"], 4100)
            self.assertIn("cached_tokens", r)
            self.assertTrue(r["cache_prompt_off"])

    def test_no_cache_override_for_non_llama_lane(self):
        with MockServer() as srv:
            srv.default = chat("nothing", prompt_tokens=1000)
            run_nd(srv, "nd-or", ["--depths", "1000", "--positions", "0.5", "--variants", "plain"],
                   snapshot="none")
            self.assertNotIn("cache_prompt", srv.requests[0]["body"])

    def test_cached_rows_excluded_from_speed(self):
        rows = [{"category": "needle/1k/plain", "status": "ok", "correct": True, "prompt_tokens": 1000,
                 "prefill_ps": 500.0, "cached_prefill": False},
                {"category": "needle/1k/plain", "status": "ok", "correct": True, "prompt_tokens": 1000,
                 "prefill_ps": 9000.0, "cached_prefill": True}]
        s = results.summarize(rows, nd.SUMMARY)["by_category"]["needle/1k/plain"]
        self.assertEqual(s["mean_prefill_ps_uncached"], 500.0)
        self.assertEqual(s["n_uncached_speed_rows"], 1)

    def test_resume_restores_args_from_run_json(self):
        args = ["--depths", "1000", "--positions", "0.5", "--variants", "plain", "--seeds", "2"]
        with MockServer() as srv:
            srv.script = [(500, {"error": "boom"})]
            srv.default = chat("nothing")
            run_nd(srv, "nd-resume", args)
            srv.requests.clear()
            # CLI defaults differ (all depths/positions/variants, 1 seed): run.json must win
            self.assertEqual(run_main(nd, ["run", "--resume", run_dir("needle", "nd-resume")]), 0)
            self.assertEqual(len(srv.requests), 1)  # only the infra-failed attempt
        rows = results.load_rows("needle", "nd-resume")
        self.assertEqual(sorted(r["seed"] for r in rows), [0, 1])
        self.assertEqual({r["status"] for r in rows}, {"ok"})


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