llm-bench

"""Language runners: compile + run model code against a task's hidden test.

run_<lang>(task, code, workdir) -> (passed, detail): passed is True / False, or None when the
check could not run for infra reasons (toolchain missing; callers record status "skipped");
detail is the tail of the toolchain output. Work dirs are work/<run_id>/<item>-<sample>/
(BENCH_WORK_DIR overrides work/); every subprocess runs in its own session and the whole
process group is killed on timeout, so a runaway test binary cannot outlive the run.
Supported: Go, Rust, TypeScript (bun), Swift (macOS with xcrun), Python (python3), shell (bash;
items stay bash-3.2-safe for macOS), SQL (sqlite3: the task's fixture, then the model's query; CSV
output compared to task["expect"], as sorted lines unless task["ordered"]); register new ones in
RUNNERS.
"""
import os
import re
import shutil
import signal
import subprocess

WORK = os.environ.get("BENCH_WORK_DIR") or os.path.join(
    os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "work")
RUN_TIMEOUT = 120  # seconds per compile / run step
AGENT_ENV = ("CLAUDECODE", "AGENT", "REPL_ID")  # stripped from every run, see tools.AGENT_ENV

_TOOLS = {"go": "go", "rust": "rustc", "ts": "bun", "python": "python3", "sh": "bash", "sql": "sqlite3"}


def work_dir(run_id, item_id, sample_idx=0):
    """work/<run_id>/<item_id>-<sample_idx>/ (not created)."""
    safe = re.sub(r"[^A-Za-z0-9._-]", "_", str(item_id))
    return os.path.join(WORK, str(run_id), "%s-%s" % (safe, sample_idx))


def _freshdir(task_id, workdir=None):
    d = workdir or os.path.join(WORK, task_id)
    shutil.rmtree(d, ignore_errors=True)
    os.makedirs(d, exist_ok=True)
    return d


def _write(path, text):
    with open(path, "w") as f:
        f.write(text)


def _sh(cmd, cwd, env=None, timeout=None):
    """Run in a new session; on timeout kill the whole process group, then raise
    subprocess.TimeoutExpired."""
    timeout = RUN_TIMEOUT if timeout is None else timeout
    env = {k: v for k, v in (os.environ if env is None else env).items() if k not in AGENT_ENV}
    p = subprocess.Popen(cmd, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                         text=True, start_new_session=True)
    try:
        out, err = p.communicate(timeout=timeout)
    except subprocess.TimeoutExpired:
        try:
            os.killpg(p.pid, signal.SIGKILL)
        except (ProcessLookupError, PermissionError):
            pass
        try:
            p.communicate(timeout=10)
        except Exception:  # noqa: BLE001 — pipes may be held by orphans; we already killed the group
            pass
        raise
    return p.returncode, (out + "\n" + err).strip()


def _missing(lang):
    tool = _TOOLS.get(lang)
    if tool and shutil.which(tool) is None:
        return "SKIP: %s not found on PATH" % tool
    return None


def run_go(task, code, workdir=None):
    miss = _missing("go")
    if miss:
        return None, miss
    d = _freshdir(task["id"], workdir)
    code = re.sub(r'^\s*package\s+\w+', 'package solution', code, count=1, flags=re.M)
    if not re.search(r'^\s*package\s+', code, flags=re.M):
        code = "package solution\n\n" + code
    _write(os.path.join(d, "solution.go"), code)
    _write(os.path.join(d, "solution_test.go"), task["test"])
    _write(os.path.join(d, "go.mod"), "module bench\n\ngo 1.26\n")
    try:
        rc, out = _sh(["go", "test", "./..."], d)
    except subprocess.TimeoutExpired:
        return False, "TIMEOUT"
    return rc == 0, out[-1500:]


def run_rust(task, code, workdir=None):
    miss = _missing("rust")
    if miss:
        return None, miss
    d = _freshdir(task["id"], workdir)
    src = code + "\n\n" + task["test"]
    _write(os.path.join(d, "solution.rs"), src)
    try:
        rc, out = _sh(["rustc", "--edition", "2021", "--test", "solution.rs", "-o", "tb"], d)
        if rc != 0:
            return False, "COMPILE:\n" + out[-1500:]
        rc, out = _sh([os.path.join(d, "tb")], d)
    except subprocess.TimeoutExpired:
        return False, "TIMEOUT"
    return rc == 0, out[-1500:]


def run_ts(task, code, workdir=None):
    miss = _missing("ts")
    if miss:
        return None, miss
    d = _freshdir(task["id"], workdir)
    _write(os.path.join(d, "solution.ts"), code)
    _write(os.path.join(d, "runtests.ts"), task["test"])
    try:
        rc, out = _sh(["bun", "run", "runtests.ts"], d)
    except subprocess.TimeoutExpired:
        return False, "TIMEOUT"
    return rc == 0, out[-1500:]


_SWIFT_SDK = None


def _swift_env():
    """(env, sdk_path); sdk is "" when xcrun/Swift is unavailable."""
    global _SWIFT_SDK
    env = {k: v for k, v in os.environ.items() if k != "SDKROOT"}
    if _SWIFT_SDK is None:
        try:
            p = subprocess.run(["xcrun", "--sdk", "macosx", "--show-sdk-path"],
                               capture_output=True, text=True, env=env, timeout=60)
            _SWIFT_SDK = p.stdout.strip() if p.returncode == 0 else ""
        except (FileNotFoundError, subprocess.TimeoutExpired):
            _SWIFT_SDK = ""
    return env, _SWIFT_SDK


def run_swift(task, code, workdir=None):
    env, sdk = _swift_env()
    if not sdk:
        return None, "SKIP: xcrun/Swift not available on this platform"
    d = _freshdir(task["id"], workdir)
    _write(os.path.join(d, "solution.swift"), code)
    _write(os.path.join(d, "main.swift"), task["test"])
    try:
        rc, out = _sh(["xcrun", "swiftc", "solution.swift", "main.swift", "-sdk", sdk,
                       "-o", "bin"], d, env=env)
        if rc != 0:
            return False, "COMPILE:\n" + out[-1500:]
        rc, out = _sh([os.path.join(d, "bin")], d, env=env)
    except subprocess.TimeoutExpired:
        return False, "TIMEOUT"
    return rc == 0, out[-1500:]


def run_python(task, code, workdir=None):
    miss = _missing("python")
    if miss:
        return None, miss
    d = _freshdir(task["id"], workdir)
    _write(os.path.join(d, "solution.py"), code)
    _write(os.path.join(d, "test_solution.py"), task["test"])
    try:
        rc, out = _sh(["python3", "-B", "test_solution.py"], d)
    except subprocess.TimeoutExpired:
        return False, "TIMEOUT"
    return rc == 0, out[-1500:]


def run_sh(task, code, workdir=None):
    miss = _missing("sh")
    if miss:
        return None, miss
    d = _freshdir(task["id"], workdir)
    _write(os.path.join(d, "solution.sh"), code)
    _write(os.path.join(d, "test.sh"), task["test"])
    try:
        rc, out = _sh(["bash", "test.sh"], d)
    except subprocess.TimeoutExpired:
        return False, "TIMEOUT"
    return rc == 0, out[-1500:]


def run_sql(task, code, workdir=None):
    miss = _missing("sql")
    if miss:
        return None, miss
    d = _freshdir(task["id"], workdir)
    _write(os.path.join(d, "fixture.sql"), task["fixture"])
    try:
        rc, out = _sh(["sqlite3", "-batch", "-bail", os.path.join(d, "db.sqlite"), ".read fixture.sql"], d)
        if rc != 0:
            return False, "FIXTURE:\n" + out[-1500:]
        p = subprocess.run(["sqlite3", "-batch", "-bail", "-csv", os.path.join(d, "db.sqlite")],
                           input=code, capture_output=True, text=True, cwd=d, timeout=RUN_TIMEOUT)
    except subprocess.TimeoutExpired:
        return False, "TIMEOUT"
    if p.returncode != 0:
        return False, "SQL ERROR:\n" + (p.stdout + p.stderr)[-1500:]
    got = [ln for ln in p.stdout.replace("\r", "").split("\n") if ln.strip()]
    want = [ln for ln in task["expect"].strip().split("\n") if ln.strip()]
    if not task.get("ordered"):
        got, want = sorted(got), sorted(want)
    if got == want:
        return True, "OK"
    return False, "got:\n%s\nwant:\n%s" % ("\n".join(got)[:700], "\n".join(want)[:700])


RUNNERS = {
    "go": run_go,
    "rust": run_rust,
    "ts": run_ts,
    "swift": run_swift,
    "python": run_python,
    "sh": run_sh,
    "sql": run_sql,
}


def extract_code(content):
    """Return the most plausible code block from a chat content string (longest fenced
    block, else the whole text)."""
    if not content:
        return ""
    blocks = re.findall(r"```[a-zA-Z0-9_+#.-]*\n(.*?)```", content, re.DOTALL)
    if blocks:
        return max(blocks, key=len).strip()
    return content.strip()