llm-bench

"""Offline tests for the sleuth instrument. Docker-backed tests skip when no daemon answers."""
import contextlib
import io
import json
import os
import subprocess
import unittest

from _util import TMP
from bench.core import tools
from bench.core.mockserver import MockServer, chat, tool_call
from bench.tasks import agentic_multitask as harness
from bench.tasks import sleuth


def _docker_up():
    try:
        return subprocess.run(["docker", "info"], capture_output=True, timeout=20).returncode == 0
    except (OSError, subprocess.TimeoutExpired):
        return False


DOCKER = _docker_up()


def case(**kw):
    args = dict(case_id="t", category="sleuth/t", complaint="", context=dict, culprit=[r"pstate"],
                reject=[r"thermal"], fix=[r"=y"], key=["k"], expert=[], reference={},
                wrong=[{"culprit": "x"}])
    args.update(kw)
    return sleuth.Case(**args)


class Grade(unittest.TestCase):
    def test_grade_table(self):
        snap, live = case(), case(check="true")
        for c, f, want in [
            (snap, ("intel_pstate missing", "", "CONFIG_X86_INTEL_PSTATE=y"), {"culprit": True, "fix": True}),
            (snap, ("kernel config", "the pstate driver is gone", "rebuild"), {"culprit": True, "fix": False}),
            (snap, ("pstate, or thermal", "", "=y"), {"culprit": False, "fix": True}),
            (snap, ("pstate", "not thermal", "=y"), {"culprit": True, "fix": True}),
            (live, ("pstate", "", "anything"), {"culprit": True}),
        ]:
            self.assertEqual(sleuth.grade(c, dict(zip(sleuth.FINDINGS, f))), want, f)

    def test_ramsleuth_channel_needs_the_directory_read(self):
        """Offhand "raw" mentions no longer pass (Opus 2026-10-12, samples 0 and 1); answers
        naming the directory read still do."""
        c = [x for x in sleuth.load_cases() if x.case_id == "ramsleuth-channel"][0]
        offsets = "intel_smbios.rs parse_type17() reads the Device Locator from 0x06/0x0C, not 0x10"
        for f, want in [
            ((offsets, "string_at assumes an empty first string, which the kernel's raw file does not have",
              "use offset 0x10"), {"culprit": False, "fix": False}),
            ((offsets, "", "add a test using this board's real Type 17 bytes from "
                           "/sys/firmware/dmi/entries/17-{0,1}/raw"), {"culprit": False, "fix": False}),
            (("collect_from() calls std::fs::read() on each dmi/entries/17-N path, but the kernel exposes "
              "each of those as a directory", "", 'read path.join("raw") for each 17-* entry'),
             {"culprit": True, "fix": True}),
            (("collect_from does fs::read on /sys/firmware/dmi/entries/17-0, which fails with EISDIR", "",
              "read 17-0/raw instead of 17-0"), {"culprit": True, "fix": True}),
        ]:
            self.assertEqual(sleuth.grade(c, dict(zip(sleuth.FINDINGS, f))), want, f)

    def test_snapshot_needs_bare_command_keys(self):
        with self.assertRaises(ValueError):
            sleuth.snapshot({}, {"uname -r": "7.3.0\n"})


@unittest.skipUnless(DOCKER, "no Docker daemon")
class Docker(unittest.TestCase):
    def setUp(self):
        tools.WORK_ROOT = os.path.join(TMP, "work")

    def run_case(self, script, case_id="cpufreq-driver"):
        (c,) = [c for c in sleuth.load_cases() if c.case_id == case_id]
        with MockServer() as srv:
            srv.script = script
            d = harness.run_instrument("unit-sleuth", "sleuth", [sleuth.task(c)], lane=srv.lane(),
                                       log=lambda *a, **k: None, max_turns=6)
            reqs = [r["body"] for r in srv.requests]
        with open(os.path.join(d, "items.jsonl")) as f:
            rows = [json.loads(line) for line in f]
        return rows[-1], reqs

    def test_end_to_end_with_mock(self):
        (c,) = [c for c in sleuth.load_cases() if c.case_id == "cpufreq-driver"]
        drv = "cat /sys/devices/system/cpu/cpufreq/policy0/scaling_driver"
        row, reqs = self.run_case([
            chat("", tool_calls=[tool_call("run", {"command": "uptime"})]),
            chat("", tool_calls=[tool_call("run", {"command": drv})]),
            chat("", tool_calls=[tool_call("submit_findings", {"culprit": "x"})]),
            chat("", tool_calls=[tool_call("submit_findings", c.reference, "c9")]),
        ])
        self.assertEqual(reqs[0]["temperature"], sleuth.TEMPERATURE)
        self.assertEqual(reqs[0]["messages"][1]["content"], c.complaint)
        tool_out = [m["content"] for m in reqs[2]["messages"] if m["role"] == "tool"]
        self.assertTrue(tool_out[1].startswith("exit=0\nacpi-cpufreq"), tool_out[1])
        self.assertIn("needs `root_cause`", reqs[3]["messages"][-1]["content"])
        self.assertEqual(row["gates"], {"culprit": True, "fix": True, "seen": True})
        self.assertIs(row["correct"], True)
        self.assertEqual((row["checks"], row["first_key_check"], row["expert_checks"]), (2, 2, 2))
        self.assertEqual(row["findings"], c.reference)
        self.assertIsNotNone(row["investigate_s"])
        names = subprocess.run(["docker", "ps", "-a", "--format", "{{.Names}}"], capture_output=True,
                               text=True).stdout
        self.assertNotIn("llm-bench-sleuth-", names)

    def test_unseen_evidence_fails_seen(self):
        (c,) = [c for c in sleuth.load_cases() if c.case_id == "cpufreq-driver"]
        row, _ = self.run_case([chat("", tool_calls=[tool_call("submit_findings", c.reference)])])
        self.assertEqual(row["gates"], {"culprit": True, "fix": True, "seen": False})
        self.assertIs(row["correct"], False)
        self.assertEqual((row["checks"], row["first_key_check"]), (0, None))

    def test_lost_container_is_infra_not_a_grade(self):
        def kill_then_run(_body):
            for n in subprocess.run(["docker", "ps", "--format", "{{.Names}}"], capture_output=True,
                                    text=True).stdout.split():
                if n.startswith("llm-bench-sleuth-"):
                    subprocess.run(["docker", "rm", "-f", n], capture_output=True)
            return chat("", tool_calls=[tool_call("run", {"command": "uptime"})])
        row, _ = self.run_case([kill_then_run])
        self.assertEqual((row["status"], row["correct"]), ("harness_error", None))
        self.assertIn("docker exec failed", row["error"])

    def test_cases_validate(self):
        buf = io.StringIO()
        with contextlib.redirect_stdout(buf):
            ok = harness.run_validate([sleuth.task(c) for c in sleuth.load_cases()], log=print)
        self.assertTrue(ok, buf.getvalue()[-3000:])


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