llm-bench

"""Sleuth instrument: troubleshoot a broken Linux machine through a root shell. Scored on reaching
the right conclusion and on how directly the model got there.

Each attempt gets a throwaway container with no network. A live case is a really broken install the
model must fix; afterwards the case's hidden CHECK must pass. A snapshot case is a captured host (its
files under / plus canned output for commands that need its kernel) entered with chroot; diagnose
only. Cases: bench/tasks/sleuth_cases/ (contract in its __init__.py).

Tools: run(command), submit_findings(culprit, root_cause, fix) (ends the attempt).
Gates: culprit (every CULPRIT pattern matches culprit + root_cause, no REJECT pattern matches the
culprit); fix (live: CHECK exits 0; snapshot: a FIX pattern matches the fix); seen (a KEY marker was
in output the model was shown). Rows add checks, first_key_check, expert_checks and investigate_s.
"""
import hashlib
import importlib
import os
import re
import subprocess
import sys
import threading
import time

from bench.core import tools
from bench.tasks import agentic_multitask as harness

HERE = os.path.dirname(os.path.abspath(__file__))
CASES_DIR = os.path.join(HERE, "sleuth_cases")
CACHE_DIR = os.path.join(os.path.dirname(HERE), "data", "sleuth", "cache")

# 1.37.0-musl is a static binary, so it runs inside any snapshot's chroot.
BUSYBOX = "busybox@sha256:5cec3fc171c87218698e85a52af7087de727372aae264a787b8112901a5b0092"
ALPINE = "alpine@sha256:5291449c3df73caf6ed85e649dec1b9e818b39a5d8c871e97afc13e9cd5e8fa8"  # 3.22

CMD_TIMEOUT = 60
MAX_TURNS = 40
MAX_TOKENS = 8000
TEMPERATURE = 0.6
GATES = ("culprit", "fix", "seen")
FINDINGS = ("culprit", "root_cause", "fix")
PATH = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
DOCKER_ERR = re.compile(r"Cannot connect to the Docker daemon|Error response from daemon|"
                        r"OCI runtime exec failed|No such container")

SYSTEM = ("You are troubleshooting a Linux machine for its owner through a root shell on it. The run "
          "tool executes a command there; common tools are the BusyBox versions. {task} When you "
          "are done, call submit_findings.")
TASK_DIAGNOSE = ("Find the root cause of the problem the owner describes. Do not change the system: "
                 "report the cause and the fix for the owner to apply.")
TASK_FIX = ("Find the root cause of the problem the owner describes and fix it on the machine, "
            "keeping its services running, then check that the fix works.")
NUDGE = "Use run to keep investigating, or call submit_findings with your conclusion."


class Case:
    """One sleuth item; the fields are described in sleuth_cases/__init__.py."""

    def __init__(self, *, case_id, category, complaint, context, culprit, key, expert, reference,
                 wrong, reject=(), fix=(), check=None, setup=(), ready=None, docker_args=()):
        self.case_id, self.category, self.complaint = case_id, category, complaint
        self.context, self.culprit, self.reject, self.fix = context, culprit, reject, fix
        self.key, self.expert, self.reference, self.wrong = key, expert, reference, wrong
        self.check, self.setup, self.ready, self.docker_args = check, setup, ready, docker_args
        self.live = check is not None
        self.source_files = ()
        if not wrong:
            raise ValueError(f"{case_id}: needs >= 1 wrong answer to prove the culprit gate bites")
        if not self.live and not fix:
            raise ValueError(f"{case_id}: a snapshot case needs FIX patterns")
        self._ctx = None
        self._lock = threading.Lock()

    def build_context(self):
        with self._lock:
            if self._ctx is None:
                self._ctx = self.context()
            return self._ctx


# ============================================================ snapshot hosts

SHIM = """#!/bin/sh
n=${0##*/}; k="$n $*"
while :; do
  f=/usr/share/sleuth/cmd/$(printf %s "$k" | tr -c 'A-Za-z0-9._=-' _)
  [ -f "$f" ] && exec cat "$f"
  [ "$k" = "${k% *}" ] && exit 1
  k=${k% *}
done
"""

SNAPSHOT_DOCKERFILE = f"""FROM {BUSYBOX}
COPY snap/ /snap/
COPY shims/ /snap/usr/bin/
RUN cp /bin/busybox /snap/usr/bin/busybox && /bin/busybox --install -s /snap/usr/bin \\
 && mkdir -p /snap/dev /snap/root /snap/run /snap/tmp /snap/var/tmp \\
 && chmod 1777 /snap/tmp /snap/var/tmp && chmod 700 /snap/root \\
 && mknod -m 666 /snap/dev/null c 1 3 && mknod -m 666 /snap/dev/zero c 1 5 \\
 && mknod -m 444 /snap/dev/urandom c 1 9 \\
 && find /snap/usr/bin /snap/usr/sbin /snap/etc/init.d -type f -exec chmod 755 {{}} + 2>/dev/null; true
CMD ["sleep", "2147483647"]
"""


def cmd_key(command):
    """File name of a canned command output (the shim's `tr -c` mapping)."""
    return re.sub(r"[^A-Za-z0-9._=-]", "_", command)


def snapshot(files, commands):
    """Build context of a snapshot host: `files` land under its / (merged /usr), each `commands` key
    ("uname -r") prints its text; other argument lists fall back to the longest matching key prefix,
    so every command needs a bare-name key."""
    ctx = {"Dockerfile": SNAPSHOT_DOCKERFILE, "snap/bin": tools.Symlink("usr/bin"),
           "snap/sbin": tools.Symlink("usr/sbin"), "snap/lib": tools.Symlink("usr/lib"),
           "snap/lib64": tools.Symlink("usr/lib64")}
    for path, content in files.items():
        ctx["snap/" + path.lstrip("/")] = content
    for name in sorted({k.split()[0] for k in commands}):
        if name not in commands:
            raise ValueError(f"command {name!r} needs a bare-name key")
        ctx["shims/" + name] = SHIM
    for k, text in commands.items():
        ctx["snap/usr/share/sleuth/cmd/" + cmd_key(k)] = text
    return ctx


# ============================================================ containers

_image_lock = threading.Lock()


def _docker(args, timeout):
    try:
        return subprocess.run(["docker", *args], capture_output=True, text=True, timeout=timeout)
    except (OSError, subprocess.TimeoutExpired) as e:
        raise tools.InfraError(f"docker {args[0]}: {e!r}; is Docker Desktop running?")


def _digest(ctx):
    h = hashlib.sha256()
    for path in sorted(ctx):
        c = ctx[path]
        kind = b"L" if isinstance(c, tools.Symlink) else b"B" if isinstance(c, bytes) else b"T"
        h.update(path.encode() + b"\0" + kind + (c if isinstance(c, bytes) else c.encode()) + b"\0")
    return h.hexdigest()[:12]


def image(case):
    """The case's image tag, built once per context digest."""
    ctx = case.build_context()
    tag = f"llm-bench-sleuth/{case.case_id}:{_digest(ctx)}"
    with _image_lock:
        if _docker(["image", "inspect", tag], 60).returncode != 0:
            d = tools.materialize(ctx, os.path.join(tools.WORK_ROOT, "_sleuth-build", case.case_id))
            r = _docker(["build", "-q", "-t", tag, d], 1800)
            if r.returncode != 0:
                raise tools.InfraError(f"docker build {case.case_id} failed: {r.stderr[-600:]}")
    return tag


def exec_in(ws, case, cmd, timeout=CMD_TIMEOUT):
    """One shell command on the case's host -> tools.RunResult, stdout and stderr merged in .out."""
    script = "cd /root 2>/dev/null; exec 2>&1\n" + cmd
    shell = ["sh", "-c", script] if case.live else ["chroot", "/snap", "/bin/sh", "-c", script]
    r = ws.run(["docker", "exec", "-e", "PATH=" + PATH, "-e", "HOME=/root", "-e", "TERM=dumb",
                ws.state["container"], "timeout", "-s", "KILL", str(timeout), *shell], timeout + 30)
    if r.timed_out or DOCKER_ERR.search(r.err):
        raise tools.InfraError(f"docker exec failed: {(r.err or 'timed out')[-300:]}")
    return r


def start(ws, case):
    """Start the attempt's container, run the case's setup and wait for it to be ready."""
    tag = image(case)
    name = "llm-bench-sleuth-" + ws.marker[:12]
    ws.cleanups.append(lambda: _docker(["rm", "-f", name], 60))
    r = _docker(["run", "-d", "--rm", "--name", name, "--network", "none", "--memory", "1g",
                 "--pids-limit", "512", *case.docker_args, tag], 120)
    if r.returncode != 0:
        raise tools.InfraError(f"docker run {case.case_id} failed: {r.stderr[-400:]}")
    ws.state["container"] = name
    for cmd in case.setup:
        s = exec_in(ws, case, cmd, 300)
        if s.rc != 0:
            raise tools.InfraError(f"setup {cmd[:60]!r} exited {s.rc}: {s.out[-300:]}")
    end = time.time() + 180
    while case.ready and exec_in(ws, case, case.ready, 30).rc != 0:
        if time.time() > end:
            raise tools.InfraError(f"{case.case_id}: not ready after 180 s ({case.ready[:60]!r})")
        time.sleep(1)


# ============================================================ tools

def _t_run(ws, args):
    cmd = tools._str_arg(args, "command", "")
    if not cmd.strip():
        raise tools.ToolError("`command` is empty; pass one shell command line")
    st = ws.state
    r = exec_in(ws, st["case"], cmd)
    text = r.text()
    st["checks"].append({"cmd": cmd[:300], "rc": r.rc, "s": round(r.dt, 2),
                         "key": any(k in text[:tools.RESULT_CAP] for k in st["case"].key)})
    return text


def _t_submit(ws, args):
    f = {}
    for k in FINDINGS:
        v = args.get(k)
        if not isinstance(v, str) or not v.strip():
            raise tools.ToolError(f"submit_findings needs `{k}` as a non-empty string")
        f[k] = v.strip()
    ws.state.update(findings=f, t_submit=time.time())
    return tools.ToolResult("findings received", stop=True)


def _toolset(live):
    fix = ("What you changed on the machine to fix it." if live else
           "The exact change or commands the owner should apply to fix it.")
    schema = [
        {"type": "function", "function": {
            "name": "run",
            "description": f"Run one shell command on the machine as root (sh -c, {CMD_TIMEOUT} s "
                           "timeout). Returns the exit code and the combined output; long output is "
                           "truncated, so filter it (grep, head, tail, awk).",
            "parameters": {"type": "object", "properties": {
                "command": {"type": "string"}}, "required": ["command"]},
        }},
        {"type": "function", "function": {
            "name": "submit_findings",
            "description": "Report your conclusion. This ends the session; call it once.",
            "parameters": {"type": "object", "properties": {
                "culprit": {"type": "string", "description": "The single thing at fault, named as "
                            "specifically as you can (a file and function, config option, "
                            "package, process, setting...)."},
                "root_cause": {"type": "string",
                               "description": "How it causes the problem, in 1-3 sentences."},
                "fix": {"type": "string", "description": fix},
            }, "required": list(FINDINGS)},
        }},
    ]
    return tools.Toolset("sleuth-live" if live else "sleuth-snapshot", schema,
                         {"run": _t_run, "submit_findings": _t_submit},
                         commands={"timeout": CMD_TIMEOUT})


TOOLSETS = {True: _toolset(True), False: _toolset(False)}


# ============================================================ grading

def grade(case, findings):
    """{culprit[, fix]} for submitted findings; fix is graded here only on snapshot cases."""
    text = findings["culprit"] + "\n" + findings["root_cause"]
    g = {"culprit": all(re.search(p, text, re.I) for p in case.culprit)
         and not any(re.search(p, findings["culprit"], re.I) for p in case.reject)}
    if not case.live:
        g["fix"] = any(re.search(p, findings["fix"], re.I) for p in case.fix)
    return g


def _gates(case):
    def gates(ws, port=None):
        st = ws.state
        f = st.get("findings")
        g, d = grade(case, f) if f else {}, {}
        if case.live and "container" in st:
            r = exec_in(ws, case, case.check, 120)
            g["fix"] = r.rc == 0
            d["check_tail"] = r.text()[-300:]
        g["seen"] = any(c["key"] for c in st.get("checks", ()))
        return {k: g.get(k, False) for k in GATES}, d
    return gates


def _extra(ws):
    st = ws.state
    checks = st.get("checks", [])
    keys = [i for i, c in enumerate(checks, 1) if c["key"]]
    t0, t1 = st.get("t_start"), st.get("t_submit")
    return {"checks": len(checks), "first_key_check": keys[0] if keys else None,
            "expert_checks": len(st["case"].expert) if "case" in st else None,
            "investigate_s": round(t1 - t0, 2) if t0 and t1 else None,
            "findings": st.get("findings")}


def _validate(case):
    """Offline proof of a case: the expert path shows a KEY, the reference passes, every wrong
    answer fails the culprit gate; live cases also fail CHECK broken and pass it after the path."""
    def validate(ws, port=None):
        ws.state.update(case=case, checks=[])
        start(ws, case)
        g = {}
        if case.live:
            g["check_fails_broken"] = exec_in(ws, case, case.check, 120).rc != 0
        outs = [exec_in(ws, case, c).text()[:tools.RESULT_CAP] for c in case.expert]
        g["expert_sees_key"] = any(k in o for o in outs for k in case.key)
        g["reference_passes"] = all(grade(case, case.reference).values())
        blank = dict.fromkeys(FINDINGS, "")
        g["wrong_rejected"] = not any(grade(case, dict(blank, **w))["culprit"] for w in case.wrong)
        if case.live:
            g["expert_fixes"] = exec_in(ws, case, case.check, 120).rc == 0
        return all(g.values()), g, {}
    return validate


# ============================================================ cases + CLI

def load_cases():
    names = sorted(os.listdir(CASES_DIR))
    helpers = [os.path.join(CASES_DIR, f) for f in names if f.startswith("_") and f.endswith(".py")]
    cases = []
    for f in names:
        if f.endswith(".py") and not f.startswith("_"):
            m = importlib.import_module(f"bench.tasks.sleuth_cases.{f[:-3]}")
            for c in m.CASES:
                c.source_files = (os.path.abspath(m.__file__), *helpers)
                cases.append(c)
    ids = [c.case_id for c in cases]
    if len(set(ids)) != len(ids):
        raise ValueError(f"duplicate sleuth case ids: {sorted(i for i in ids if ids.count(i) > 1)}")
    return cases


def task(case):
    def user(ws):
        ws.state.update(case=case, checks=[])
        start(ws, case)
        ws.state["t_start"] = time.time()
        return case.complaint
    return harness.AgenticTask(
        item_id=case.case_id, category=case.category, plan="", starter={},
        toolset=TOOLSETS[case.live], gates=_gates(case), gate_names=GATES,
        validate=_validate(case), system_tmpl=SYSTEM.format(task=TASK_FIX if case.live else TASK_DIAGNOSE),
        user=user, nudge=NUDGE, give_up_after=3, done_word=False, max_tokens=MAX_TOKENS,
        temperature=TEMPERATURE, extra=_extra, source_files=case.source_files, prune=())


def main(argv=None):
    sys.exit(harness.cli_main("sleuth", "sleuth", [task(c) for c in load_cases()],
                              sys.argv[1:] if argv is None else argv, multi=True,
                              default_cmd="--help", max_turns_default=MAX_TURNS))


if __name__ == "__main__":
    main()