llm-bench

"""Per-lane conformance preflight. NOT a benchmark: it rules out non-model problems (lane settings,
chat template, reasoning and tool-call parsing, a provider that eats output) before a run.

  LANE=<id> python3 bench.py conformance [--checks a,b,...] [--list]

Every `run` of a scoring instrument calls require() first (results.run_attempts): the PREFLIGHT
checks run unless they passed for the same lane settings in the last 24 h; any FAIL stops the run.
BENCH_PREFLIGHT=0 skips it (tests, deliberate reruns); --resume never re-checks.

Verdicts: PASS; FAIL = a non-model problem (blocks a run); WARN = the model got a probe wrong
but the pipeline delivered it intact (recorded, does not block); INFO. One row per check
(category "conformance", item_id = check name, correct True / False / None for WARN and INFO).
Output tokens stay small: every call passes override={"max_tokens": ...}.

Checks
  sampler_card      no request: the sampler the lane sends (lane.request + extra_body, as the client
                    builds it) vs its card's block for its thinking mode in lanes/cards.json. FAIL on
                    a missing or different value unless lane.sampler_overrides pins the sent value
                    with a reason; FAIL if the lane names no card
  basic_reply       the lane answers a trivial arithmetic question with non-empty content
                    (shared response also feeds the thinking checks below)
  max_tokens        override max_tokens=64 is honoured (completion_tokens <= 70)
  reasoning_field   thinking-on lanes: records WHICH field carries the reasoning
                    (reasoning_content / reasoning / reasoning_details / inline <think>) and whether
                    reasoning_tokens is reported or None. FAIL if no reasoning is observed.
  no_reasoning      thinking-off lanes: zero reasoning chars AND reasoning_tokens in {None, 0}
  system_messages   two system messages + a user message succeed (the client merges them when the
                    lane sets merge_system_messages; INFO note if the lane lacks it)
  tool_roundtrip    the model calls a provided tool with valid JSON-object arguments, then answers
                    after a tool result
  tc-*              the 8 tool-call / JSON probes (toolcall_probes.py, from coding-suite). FAIL when
                    the pipeline lost the answer: a tool call that came back as text, output the
                    provider swallowed (stripped), no answer and no call at finish=stop; WARN when
                    a well-formed answer is just wrong
  think_tags        over every response above: <think>/</think> left in the content or inside the
                    reasoning field, a <think> that never closed, the basic answer found only in
                    the reasoning. FAIL on any
  determinism       INFO only, not in the preflight: two runs at temperature 0 / top_k 1, identical
                    content? (never part of a run: temperature 0 loops Qwen)
  provider_pin      openrouter lanes: every response's `provider` equals the pinned provider
                    (extra_body.provider.order[0], case-insensitive); FAIL otherwise
  server_snapshot   INFO: n_ctx / total_slots / model ids from the RunStore's run.json
"""
import argparse
import hashlib
import json
import os
import re
import sys
import time

from bench.core import client, lane as lane_mod, results
from bench.tasks import toolcall_probes

INSTRUMENT = "conformance"
CAP_ON, CAP_OFF = 2048, 256          # trivial answers: reasoners need room, non-reasoners do not
CAP_TOOL_ON, CAP_TOOL_OFF = 4096, 512
CAP_SMALL = 64
CHECKS = ["sampler", "basic", "maxtok", "thinking", "system", "tools", "toolcalls", "think_tags",
          "determinism", "provider", "server"]
PREFLIGHT = ["sampler", "basic", "maxtok", "thinking", "system", "tools", "toolcalls", "think_tags",
             "provider"]
PREFLIGHT_TTL = 24 * 3600
ITEM_SET = "conformance@2"
CARDS = os.path.join(lane_mod.LANES_DIR, "cards.json")
TOOL_TEXT = re.compile(r"<tool_call>|<function[=>]|\"name\"\s*:\s*\"(get_weather|calculator|web_search|set_timer)\"")
THINK_TAG = re.compile(r"</?think>")

TOOL = [{"type": "function", "function": {
    "name": "get_weather", "description": "Get the current weather for a city.",
    "parameters": {"type": "object", "properties": {"city": {"type": "string"}},
                   "required": ["city"]}}}]


class Result:
    def __init__(self, name, verdict, detail, meta=None):
        self.name, self.verdict, self.detail, self.meta = name, verdict, detail, meta or {}


def reasoning_fields(resp):
    """Which fields of the message carry reasoning text."""
    msg = resp["choices"][0].get("message") or {}
    found = [k for k in ("reasoning_content", "reasoning") if msg.get(k)]
    det = msg.get("reasoning_details")
    if isinstance(det, list) and any((d.get("text") or d.get("summary")) for d in det if isinstance(d, dict)):
        found.append("reasoning_details")
    c = msg.get("content")
    if isinstance(c, str) and c.lstrip().startswith("<think>"):
        found.append("inline_think")
    return found


def load_cards(path=CARDS):
    with open(path) as f:
        return json.load(f)


def _same(a, b):
    if isinstance(a, (int, float)) and isinstance(b, (int, float)):
        return abs(a - b) < 1e-9
    return a == b


def sampler_check(lane, cards):
    """The sampler this lane sends vs its model card's recommendation for its thinking mode."""
    name = "sampler_card"
    card_id = lane.raw.get("card")
    if not card_id:
        return Result(name, "FAIL", 'lane names no model card (set "card" to a key of lanes/cards.json)')
    mode = "thinking" if lane.thinking == "on" else "non_thinking"
    card = cards.get(card_id) or {}
    if mode not in card:
        return Result(name, "FAIL", "lanes/cards.json has no %s sampler for %s" % (mode, card_id),
                      {"card": card_id})
    sent = client.build_body([{"role": "user", "content": "."}], lane=lane)
    overrides = lane.raw.get("sampler_overrides") or {}
    bad, notes = [], []
    for key, want in sorted(card[mode].items()):
        got, ov = sent.get(key), overrides.get(key)
        if got is None:
            bad.append("%s not sent (card %s)" % (key, want))
        elif ov is None:
            if not _same(got, want):
                bad.append("%s=%s (card %s)" % (key, got, want))
        elif not _same(got, ov.get("value")):
            bad.append("%s=%s but sampler_overrides pins %s" % (key, got, ov.get("value")))
        elif not ov.get("reason"):
            bad.append("%s=%s override has no reason" % (key, got))
        else:
            notes.append("%s=%s overridden (card %s): %s" % (key, got, want, ov["reason"]))
    where = "%s@%s %s" % (card_id, card.get("revision", "?")[:7], mode)
    meta = {"card": card_id, "card_revision": card.get("revision"), "card_mode": mode,
            "mismatches": bad, "overridden": sorted(k for k in overrides if k in card[mode])}
    if bad:
        return Result(name, "FAIL", "%s: %s" % (where, "; ".join(bad + notes)), meta)
    return Result(name, "PASS", "; ".join([where + ": matches"] + notes), meta)


class Preflight:
    def __init__(self, lane, store):
        self.lane, self.store = lane, store
        self.on = lane.thinking == "on"
        self.cap = CAP_ON if self.on else CAP_OFF
        self.cap_tool = CAP_TOOL_ON if self.on else CAP_TOOL_OFF
        self.providers = []
        self.seen = []  # (check name, response) for think_tags
        self.out_tokens = 0
        self.basic_resp = None
        self.budget_stop = False

    def call(self, name, messages, tools=None, cap=None, extra=None):
        ov = {"max_tokens": cap or self.cap}
        ov.update(extra or {})
        resp, dt = client.call_model(messages, tools, override=ov, item_id="conformance-" + name,
                                     run_id=self.store.run_id, lane=self.lane)
        u = client.usage(resp)
        self.out_tokens += u["completion_tokens"]
        self.providers.append(resp.get("provider"))
        self.seen.append((name, resp))
        return resp, dt

    def guard(self, name, fn, info_on_error=False):
        """Run a check; an error becomes FAIL (INFO for informational checks)."""
        try:
            return fn()
        except client.CallError as e:
            if e.label() == "budget_stop":
                self.budget_stop = True
            return Result(name, "INFO" if info_on_error else "FAIL", "request failed: %s" % e,
                          client.error_meta(e))
        except Exception as e:  # noqa: BLE001
            return Result(name, "FAIL", "harness error: %r" % (e,), client.error_meta(e))

    # ---- checks -----------------------------------------------------------
    def sampler(self):
        return sampler_check(self.lane, load_cards())

    def basic(self):
        resp, dt = self.call("basic_reply", [{"role": "user", "content":
                                              "What is 17 * 23? Answer with just the number."}])
        self.basic_resp = resp
        meta = client.meta(resp, dt)
        text = client.content(resp).strip()
        if meta["status"] == "truncated":
            return Result("basic_reply", "FAIL", "truncated at the %d-token cap (content=%r)" % (self.cap, text[:60]), meta)
        if not text:
            return Result("basic_reply", "FAIL", "empty content", meta)
        return Result("basic_reply", "PASS", "content=%r%s" % (text[:40], "" if "391" in text else " (not 391)"), meta)

    def maxtok(self):
        resp, dt = self.call("max_tokens", [{"role": "user", "content": "Count from 1 to 500, one number per line."}],
                             cap=CAP_SMALL)
        meta = client.meta(resp, dt)
        ct, fin = meta["completion_tokens"], meta["finish"]
        sent = (resp.get("_bench", {}).get("request") or {}).get("max_tokens")
        if not ct:
            return Result("max_tokens", "INFO", "server reported no completion_tokens (finish=%s)" % fin, meta)
        if ct > 70:
            return Result("max_tokens", "FAIL", "asked max_tokens=%s, got completion_tokens=%d (finish=%s)" % (sent, ct, fin), meta)
        return Result("max_tokens", "PASS", "max_tokens=%s -> completion_tokens=%d finish=%s" % (sent, ct, fin), meta)

    def thinking(self):
        resp = self.basic_resp
        if resp is None:
            resp, dt = self.call("reasoning_field", [{"role": "user", "content":
                                                      "What is 17 * 23? Answer with just the number."}])
            meta = client.meta(resp, dt)
        else:
            meta = client.meta(resp)
        chars = len(client.reasoning(resp))
        rt = client.usage(resp)["reasoning_tokens"]
        fields = reasoning_fields(resp)
        rts = "None (not reported)" if rt is None else str(rt)
        if self.on:
            name = "reasoning_field"
            if chars > 0:
                return Result(name, "PASS", "field=%s reasoning_chars=%d reasoning_tokens=%s"
                              % ("+".join(fields) or "?", chars, rts), meta)
            if rt:
                return Result(name, "INFO", "reasoning_tokens=%s reported but no reasoning text returned" % rt, meta)
            return Result(name, "FAIL", "lane is thinking=on but no reasoning observed "
                          "(reasoning_tokens=%s)" % rts, meta)
        name = "no_reasoning"
        if chars == 0 and rt in (None, 0):
            return Result(name, "PASS", "reasoning_chars=0 reasoning_tokens=%s mechanism=%s"
                          % (rts, (self.lane.nothink or {}).get("mechanism")), meta)
        return Result(name, "FAIL", "thinking=off lane leaked reasoning: chars=%d reasoning_tokens=%s fields=%s"
                      % (chars, rts, "+".join(fields) or "-"), meta)

    def system(self):
        merged = bool(self.lane.raw.get("merge_system_messages"))
        resp, dt = self.call("system_messages", [
            {"role": "system", "content": "You are a terse assistant."},
            {"role": "system", "content": "Always answer in lowercase."},
            {"role": "user", "content": "Say hello."}])
        meta = client.meta(resp, dt)
        note = "client merges system messages" if merged else "NOTE: lane lacks merge_system_messages (sent as two messages)"
        if meta["status"] in ("empty", "truncated"):
            return Result("system_messages", "FAIL", "accepted but status=%s; %s" % (meta["status"], note), meta)
        return Result("system_messages", "PASS", note, meta)

    def tools(self):
        msgs = [{"role": "user", "content": "What is the weather in Paris right now? Use the get_weather tool."}]
        resp, dt = self.call("tool_roundtrip", msgs, tools=TOOL, cap=self.cap_tool)
        meta = client.meta(resp, dt)
        tcs = client.tool_calls(resp)
        if not tcs:
            why = pipeline_fault(resp, {"tools": TOOL}, meta)
            return Result("tool_roundtrip", "FAIL" if why else "WARN", "%sno tool call (content=%r)" % (
                why + " | " if why else "model: ", client.content(resp)[:80]), meta)
        fn = tcs[0].get("function") or {}
        try:
            args = json.loads(fn.get("arguments") or "")
        except ValueError:
            args = None
        if fn.get("name") != "get_weather" or not isinstance(args, dict):
            return Result("tool_roundtrip", "FAIL", "bad tool call name=%r arguments=%r"
                          % (fn.get("name"), str(fn.get("arguments"))[:80]), meta)
        msgs.append(resp["choices"][0]["message"])
        msgs.append({"role": "tool", "tool_call_id": tcs[0].get("id") or "call_0",
                     "content": json.dumps({"city": "Paris", "temp_c": 18, "sky": "cloudy"})})
        resp2, dt2 = self.call("tool_roundtrip", msgs, tools=TOOL, cap=self.cap_tool)
        text = client.content(resp2).strip()
        meta["turn2_status"] = client.status(resp2)
        if not text:
            return Result("tool_roundtrip", "FAIL", "valid call args=%s but no answer after the tool result "
                          "(status=%s, tool_calls=%d)" % (args, client.status(resp2), len(client.tool_calls(resp2))), meta)
        return Result("tool_roundtrip", "PASS", "args=%s; answer mentions 18: %s" % (args, "18" in text), meta)

    def probe(self, p):
        resp, dt = self.call(p["id"], p["messages"], tools=p["tools"], cap=self.cap_tool)
        meta = client.meta(resp, dt)
        res = p["validator"](resp)
        meta.update(res[2] if len(res) > 2 else {})
        if res[0]:
            return Result(p["id"], "PASS", res[1], meta)
        why = pipeline_fault(resp, p, meta)
        return Result(p["id"], "FAIL" if why else "WARN", (why + " | " if why else "model: ") + res[1], meta)

    def think_tags(self):
        if not self.seen:
            return Result("think_tags", "INFO", "no responses to check")
        issues = []
        for name, resp in self.seen:
            msg = resp["choices"][0].get("message") or {}
            raw = client._raw_content(resp)
            if THINK_TAG.search(client.content(resp)):
                issues.append(f"{name}: think tag left in the content")
            field = msg.get("reasoning_content") or msg.get("reasoning")
            if isinstance(field, str) and THINK_TAG.search(field):
                issues.append(f"{name}: think tag inside the reasoning field")
            if raw.lstrip().startswith("<think>") and "</think>" not in raw \
                    and client.finish_reason(resp) != "length":
                issues.append(f"{name}: <think> never closed (finish={client.finish_reason(resp)})")
            if name == "basic_reply" and "391" in client.reasoning(resp) and "391" not in client.content(resp) \
                    and client.finish_reason(resp) != "length":
                issues.append("basic_reply: the answer is only in the reasoning")
        inline = sum(1 for _, r in self.seen if client._raw_content(r).lstrip().startswith("<think>"))
        if issues:
            return Result("think_tags", "FAIL", "; ".join(issues)[:480])
        return Result("think_tags", "PASS", "clean across %d responses%s" % (len(self.seen), (
            "; reasoning arrives inline in the content on %d (the client splits it)" % inline) if inline else ""))

    def determinism(self):
        outs = []
        for _ in range(2):
            resp, dt = self.call("determinism", [{"role": "user", "content": "Write one sentence about the sea."}],
                                 extra={"temperature": 0, "top_k": 1})
            outs.append(client.content(resp))
        same = outs[0] == outs[1]
        return Result("determinism", "INFO", "temperature=0 top_k=1: %s%s" % (
            "identical content" if same else "content DIFFERS between runs",
            "" if outs[0].strip() else " (empty content)"), {"identical": same})

    def provider(self):
        order = ((self.lane.extra_body.get("provider") or {}).get("order") or [])
        if not order:
            return Result("provider_pin", "FAIL", "openrouter lane has no extra_body.provider.order pin")
        pinned = str(order[0])
        seen = [p for p in self.providers]
        if not seen:
            return Result("provider_pin", "FAIL", "no responses to check")
        bad = sorted({str(p) for p in seen if not p or str(p).lower() != pinned.lower()})
        if bad:
            return Result("provider_pin", "FAIL", "pinned %r but responses came from %s" % (pinned, bad))
        return Result("provider_pin", "PASS", "all %d responses from %r" % (len(seen), pinned))

    def server(self):
        with open(os.path.join(self.store.dir, "run.json")) as f:
            srv = json.load(f).get("server") or {}
        parts = ["kind=%s" % srv.get("kind")]
        props = srv.get("props") or {}
        if props:
            parts.append("n_ctx=%s" % (props.get("default_generation_settings") or {}).get("n_ctx"))
            parts.append("total_slots=%s" % props.get("total_slots"))
            if props.get("build_info"):
                parts.append("build=%s" % props.get("build_info"))
        models = srv.get("models") or {}
        ids = [m.get("id") for m in (models.get("data") or []) if isinstance(m, dict)]
        if ids:
            parts.append("models=%s" % ",".join(str(i) for i in ids))
        ep = (srv.get("endpoints") or {}).get("data") or {}
        if isinstance(ep, dict) and ep.get("endpoints"):
            parts.append("endpoints=%s" % ",".join(str(e.get("provider_name") or e.get("tag")) for e in ep["endpoints"]))
        errs = [k for k, v in srv.items() if isinstance(v, dict) and "_error" in v]
        if errs or "_error" in props:
            parts.append("snapshot errors in %s" % (errs or ["props"]))
        return Result("server_snapshot", "INFO", " ".join(parts))


def pipeline_fault(resp, probe, meta):
    """Why a failed probe points at the template / parser / provider rather than the model, or ""."""
    tcs, c, r = client.tool_calls(resp), client.content(resp), client.reasoning(resp)
    if results.effective_status(meta) == "stripped":
        return "output swallowed: %s answer tokens, no content, no tool call" % (
            (meta.get("completion_tokens") or 0) - (meta.get("reasoning_tokens") or 0))
    if THINK_TAG.search(c):
        return "think tag in the content"
    if not tcs and TOOL_TEXT.search(c + "\n" + r):
        return "the call came back as text, not as a tool_calls entry (template / parser)"
    if not tcs and not c.strip() and client.finish_reason(resp) != "length":
        return "no answer and no tool call at finish=%s" % client.finish_reason(resp)
    return ""


def run_conformance(lane, store, checks=None, out=print):
    """Run the selected checks; returns the list of Results (rows already stored)."""
    sel = set(checks or CHECKS)
    pf = Preflight(lane, store)
    plan = [("sampler", pf.sampler, "sampler_card", False),
            ("basic", pf.basic, "basic_reply", False),
            ("maxtok", pf.maxtok, "max_tokens", False),
            ("thinking", pf.thinking, "reasoning_field" if pf.on else "no_reasoning", False),
            ("system", pf.system, "system_messages", False),
            ("tools", pf.tools, "tool_roundtrip", False)]
    plan += [("toolcalls", (lambda p=p: pf.probe(p)), p["id"], False) for p in toolcall_probes.TOOLCALL]
    plan += [("think_tags", pf.think_tags, "think_tags", False),
             ("determinism", pf.determinism, "determinism", True)]
    out_results = []
    for key, fn, name, info in plan:
        if key not in sel or pf.budget_stop:
            continue
        out_results.append(pf.guard(name, fn, info_on_error=info))
    if "provider" in sel and lane.snapshot_kind == "openrouter":
        out_results.append(pf.guard("provider_pin", pf.provider))
    if "server" in sel:
        out_results.append(pf.guard("server_snapshot", pf.server, info_on_error=True))
    for r in out_results:
        store.add(item_id=r.name, sample_idx=0, category="conformance",
                  correct={"PASS": True, "FAIL": False}.get(r.verdict), verdict=r.verdict,
                  detail=r.detail[:500], **r.meta)
    out("conformance: lane=%s thinking=%s kind=%s" % (lane.lane_id, lane.thinking, lane.snapshot_kind))
    out("%-18s %-5s %s" % ("check", "", "detail"))
    for r in out_results:
        out("%-18s %-5s %s" % (r.name, r.verdict, r.detail))
    out("total output tokens: %d" % pf.out_tokens)
    return out_results


def _lane_hash(lane):
    return hashlib.sha256(json.dumps(lane.record(), sort_keys=True).encode()).hexdigest()[:16]


def _marker(lane):
    return os.path.join(results.RESULTS_DIR, "_preflight", lane.lane_id + ".json")


def require(lane, log=print):
    """The automatic preflight before a run: PREFLIGHT checks, cached 24 h per lane settings. Raises
    SystemExit on any FAIL."""
    if lane.raw.get("runner") or os.environ.get("BENCH_PREFLIGHT", "1") == "0":
        return
    h, path = _lane_hash(lane), _marker(lane)
    try:
        with open(path) as f:
            m = json.load(f)
        if m.get("lane_hash") == h and m.get("ok") and time.time() - m.get("t", 0) < PREFLIGHT_TTL:
            log("preflight: passed %s for these lane settings (%s); skipping" % (m.get("at"), m.get("run_id")))
            return
    except (OSError, ValueError):
        pass
    log("preflight: checking lane %s before the run (BENCH_PREFLIGHT=0 skips)" % lane.lane_id)
    store = results.RunStore(INSTRUMENT, item_set=ITEM_SET, lane=lane, args={"checks": PREFLIGHT, "auto": True})
    res = run_conformance(lane, store, PREFLIGHT, out=log)
    fails = [r for r in res if r.verdict == "FAIL"]
    store.finish(_summary(res), complete=True)
    os.makedirs(os.path.dirname(path), exist_ok=True)
    with open(path, "w") as f:
        json.dump({"lane_hash": h, "ok": not fails, "t": time.time(), "run_id": store.run_id,
                   "at": time.strftime("%Y-%m-%d %H:%M")}, f)
    if fails:
        raise SystemExit("preflight FAILED on %s: %s\nnot a model problem; fix the lane or server, or "
                         "rerun with BENCH_PREFLIGHT=0 to override" % (
                             lane.lane_id, "; ".join("%s: %s" % (r.name, r.detail[:160]) for r in fails)))


def _summary(res):
    return {"pass": sum(r.verdict == "PASS" for r in res), "fail": sum(r.verdict == "FAIL" for r in res),
            "warn": sum(r.verdict == "WARN" for r in res), "info": sum(r.verdict == "INFO" for r in res),
            "checks": {r.name: r.verdict for r in res}}


def main(argv=None):
    ap = argparse.ArgumentParser(prog="bench.py conformance")
    ap.add_argument("--checks", default="", help="comma list of: " + ",".join(CHECKS))
    ap.add_argument("--list", action="store_true")
    args = ap.parse_args(sys.argv[1:] if argv is None else argv)
    if args.list:
        print("\n".join(CHECKS))
        return
    checks = [c for c in args.checks.split(",") if c] or None
    if checks and [c for c in checks if c not in CHECKS]:
        print("ERROR: unknown checks; choose from %s" % ",".join(CHECKS))
        sys.exit(2)
    lane = lane_mod.current()
    if lane.raw.get("runner"):
        print("conformance: lane %s runs through %s, not an HTTP endpoint; nothing to check"
              % (lane.lane_id, lane.raw["runner"]))
        sys.exit(2)
    store = results.RunStore(INSTRUMENT, item_set=ITEM_SET, lane=lane,
                             args={"checks": checks or CHECKS})
    res = run_conformance(lane, store, checks)
    fails = [r for r in res if r.verdict == "FAIL"]
    store.finish(_summary(res), complete=True)
    print("\n%s" % ("FAIL: %s" % ", ".join(r.name for r in fails) if fails else "all checks passed"))
    sys.exit(1 if fails else 0)


if __name__ == "__main__":
    main()