llm-bench

"""OpenAI-compatible chat-completions client (urllib + json) used by every instrument.

call_model builds each body from the active lane (bench.core.lane), later wins:
  {model, messages[, tools]} <- instrument defaults (max_tokens=, temperature= kwargs)
  <- lane.request <- override= kwarg <- lane.extra_body (deep merge) <- lane no-think mechanism

History hygiene (so no lane gets a template 500 from our own echo): assistant tool_call
`arguments` that are not a JSON object become "{}", dict arguments are serialized, and
reasoning fields are dropped from prior turns unless the lane sets reasoning_echo=true.

Failures raise CallError, labelled for result rows: http_<code> | oom | ctx_overflow | timeout
| conn_error | budget_stop | guard_refused | bad_response. 429/502/503/504/529 and connection
resets are retried with backoff (Retry-After honored); 500/4xx and timeouts are not.
"""
import copy
import hashlib
import http.client
import json
import os
import random
import re
import socket
import time
import urllib.error
import urllib.request

from bench.core import lane as lane_mod
from bench.core import ledger

RETRY_STATUS = {429, 502, 503, 504, 529}
OOM_MARKERS = ("out of memory", "failed to allocate", "cudamalloc", "insufficient memory")
CTX_MARKERS = ("context size", "context length", "exceeds the available context", "maximum context",
               "too many tokens", "context_length_exceeded")
THINK_PREFILL = "<think>\n\n</think>\n\n"
BACKOFF_SCALE = float(os.environ.get("BENCH_BACKOFF_SCALE", "1"))  # tests set ~0


def _backoff(attempt):
    return BACKOFF_SCALE * 3 * 2 ** (attempt - 1)


class CallError(RuntimeError):
    def __init__(self, kind, detail="", code=None, attempts=1):
        super().__init__(f"{kind}{'' if code is None else ' ' + str(code)}: {detail[:300]}")
        self.kind = kind
        self.code = code
        self.detail = detail[:500]
        self.attempts = attempts

    def label(self):
        if self.kind == "http":
            low = self.detail.lower()
            if self.code == 507 or any(m in low for m in OOM_MARKERS):
                return "oom"
            if self.code == 400 and any(m in low for m in CTX_MARKERS):
                return "ctx_overflow"
            return f"http_{self.code}"
        return {"timeout": "timeout", "conn": "conn_error", "budget": "budget_stop",
                "guard": "guard_refused"}.get(self.kind, "bad_response")


def _deep_merge(dst, src):
    for k, v in src.items():
        if isinstance(v, dict) and isinstance(dst.get(k), dict):
            _deep_merge(dst[k], v)
        else:
            dst[k] = copy.deepcopy(v)
    return dst


def _sanitize_history(messages, keep_reasoning):
    out = []
    for m in messages:
        m = dict(m)
        if m.get("role") == "assistant":
            if not keep_reasoning:
                m.pop("reasoning_content", None)
                m.pop("reasoning", None)
                m.pop("reasoning_details", None)
            if m.get("tool_calls"):
                fixed = []
                for tc in m["tool_calls"]:
                    tc = copy.deepcopy(tc)
                    fn = tc.setdefault("function", {})
                    args = fn.get("arguments")
                    if isinstance(args, dict):
                        fn["arguments"] = json.dumps(args)
                    else:
                        try:
                            ok = isinstance(json.loads(args or ""), dict)
                        except (TypeError, ValueError):
                            ok = False
                        if not ok:
                            fn["arguments"] = "{}"
                    fixed.append(tc)
                m["tool_calls"] = fixed
        out.append(m)
    return out


def _merge_system(messages):
    sys_parts = [m.get("content") or "" for m in messages if m.get("role") == "system"]
    if len(sys_parts) <= 1 and (not sys_parts or messages[0].get("role") == "system"):
        return messages
    rest = [m for m in messages if m.get("role") != "system"]
    return [{"role": "system", "content": "\n\n".join(sys_parts)}] + rest


def build_body(messages, tools=None, *, max_tokens=None, temperature=None, override=None,
               lane=None):
    """Return the exact request body for this lane (exposed for tests/mocks)."""
    lane = lane or lane_mod.current()
    msgs = _sanitize_history(list(messages), bool(lane.raw.get("reasoning_echo")))
    if lane.raw.get("merge_system_messages"):
        msgs = _merge_system(msgs)
    body = {"model": lane.model, "messages": msgs}
    if max_tokens is not None:
        body["max_tokens"] = max_tokens
    if temperature is not None:
        body["temperature"] = temperature
    body.update(copy.deepcopy(lane.request))
    if override:
        body.update(copy.deepcopy(override))
    _deep_merge(body, lane.extra_body)
    if lane.thinking == "off":
        mech = lane.nothink["mechanism"]
        if mech == "reasoning_effort_none":
            body["reasoning_effort"] = "none"
        elif mech == "openrouter_reasoning_off":
            body.pop("reasoning_effort", None)
            _deep_merge(body, {"reasoning": {"enabled": False, "exclude": False}})
        elif mech == "template_kwargs":
            _deep_merge(body, {"chat_template_kwargs": {"enable_thinking": False}})
        elif mech == "think_prefill":
            body["messages"] = body["messages"] + [{"role": "assistant", "content": THINK_PREFILL}]
    if tools:
        body["tools"] = tools
    for field, bad in lane.forbid.items():
        if body.get(field) in bad:
            raise CallError("guard", f"lane {lane.lane_id} forbids {field}={body.get(field)!r}")
    return body


def request_profile(body):
    """The settings part of a body (no messages/tools) + a short hash, for result rows."""
    prof = {k: v for k, v in body.items() if k not in ("messages", "tools")}
    h = hashlib.sha256(json.dumps(prof, sort_keys=True).encode()).hexdigest()[:12]
    return prof, h


def _post(url, data, headers, timeout):
    req = urllib.request.Request(url, data=data, headers=headers)
    with urllib.request.urlopen(req, timeout=timeout) as r:
        return json.load(r)


def call_model(messages, tools=None, *, max_tokens=None, temperature=None, override=None,
               item_id=None, run_id=None, lane=None):
    """Send one chat-completions request. Returns (resp_dict, elapsed_seconds).

    resp["_bench"] carries per-call metadata (attempts, request profile + hash,
    cost, provider, gen id) for result rows. Raises CallError on failure.
    """
    lane = lane or lane_mod.current()
    if lane.raw.get("runner"):
        raise CallError("guard", f"lane {lane.lane_id} runs through {lane.raw['runner']}, "
                                 "which drives agentic instruments only")
    body = build_body(messages, tools, max_tokens=max_tokens, temperature=temperature,
                      override=override, lane=lane)
    data = json.dumps(body).encode()
    if lane.cost:
        try:
            ledger.check(lane.cost, len(data), body.get("max_tokens"))
        except ledger.BudgetExceeded as e:
            raise CallError("budget", str(e))
    headers = {"Content-Type": "application/json"}
    key = lane.api_key()
    if key:
        headers["Authorization"] = "Bearer " + key
    url = lane.endpoint
    timeout = lane.http_timeout
    retries = int(lane.raw.get("retries", 4))
    attempt = 0
    t0 = time.time()
    while True:
        attempt += 1
        wait = None
        try:
            resp = _post(url, data, headers, timeout)
            err = resp.get("error") if isinstance(resp, dict) else None
            if err and not resp.get("choices"):
                # OpenRouter can return 200 with an error object from the provider.
                code = err.get("code") if isinstance(err.get("code"), int) else 502
                if code in RETRY_STATUS and attempt <= retries:
                    wait = _backoff(attempt)
                else:
                    raise CallError("http", json.dumps(err)[:500], code=code, attempts=attempt)
            elif not isinstance(resp, dict) or not resp.get("choices"):
                raise CallError("bad_response", json.dumps(resp)[:500], attempts=attempt)
            else:
                break
        except urllib.error.HTTPError as e:
            detail = ""
            try:
                detail = e.read().decode("utf-8", "replace")
            except Exception:  # noqa: BLE001 — best effort body read
                pass
            if e.code in RETRY_STATUS and attempt <= retries:
                ra = e.headers.get("Retry-After") if e.headers else None
                wait = min(float(ra), 120.0) * BACKOFF_SCALE \
                    if ra and ra.replace(".", "", 1).isdigit() else _backoff(attempt)
            else:
                raise CallError("http", detail, code=e.code, attempts=attempt)
        except (socket.timeout, TimeoutError) as e:
            raise CallError("timeout", f"no response within {timeout}s ({e})", attempts=attempt)
        except ValueError as e:  # non-JSON body
            raise CallError("bad_response", f"unparseable response: {e}", attempts=attempt)
        except (urllib.error.URLError, ConnectionError, http.client.RemoteDisconnected) as e:
            reason = getattr(e, "reason", e)
            if isinstance(reason, (socket.timeout, TimeoutError)):
                raise CallError("timeout", f"no response within {timeout}s", attempts=attempt)
            if attempt <= retries:
                wait = _backoff(attempt)
            else:
                raise CallError("conn", repr(reason), attempts=attempt)
        time.sleep(wait + random.uniform(0, BACKOFF_SCALE))
    dt = time.time() - t0
    prof, h = request_profile(body)
    u = usage(resp)
    resp["_bench"] = {"attempts": attempt, "request": prof, "request_hash": h,
                      "provider": resp.get("provider"), "gen_id": resp.get("id"),
                      "cost_usd": u["cost_usd"]}
    if lane.cost:
        cost = u["cost_usd"]
        if cost is None:  # provider didn't report: charge the token-priced estimate
            cost = (u["prompt_tokens"] * float(lane.cost.get("in_per_m", 0)) +
                    u["completion_tokens"] * float(lane.cost.get("out_per_m", 0))) / 1e6
            resp["_bench"]["cost_usd"] = cost
            resp["_bench"]["cost_estimated"] = True
        ledger.record(lane.cost, lane_id=lane.lane_id, run_id=run_id, item_id=item_id,
                      cost_usd=cost, gen_id=resp.get("id"), provider=resp.get("provider"))
    return resp, dt


# ---- response extraction (one place for every runtime's quirks) ----------------------

_THINK_RE = re.compile(r"^\s*<think>(.*?)</think>\s*", re.DOTALL)


def _msg(resp):
    return resp["choices"][0].get("message") or {}


def _raw_content(resp):
    c = _msg(resp).get("content")
    if isinstance(c, list):  # content-parts form
        c = "".join(p.get("text", "") for p in c if isinstance(p, dict))
    return c or ""


def content(resp):
    """Answer text with any inline <think>…</think> removed ("" if thinking never closed)."""
    c = _raw_content(resp)
    m = _THINK_RE.match(c)
    if m:
        return c[m.end():]
    if c.lstrip().startswith("<think>"):
        return ""
    return c


def reasoning(resp):
    """Thinking text from reasoning_content (llama-server), reasoning (MLX/OpenRouter),
    reasoning_details (OpenRouter) or an inline <think> block."""
    msg = _msg(resp)
    r = msg.get("reasoning_content") or msg.get("reasoning")
    if not r and isinstance(msg.get("reasoning_details"), list):
        r = "".join(d.get("text", "") or d.get("summary", "") for d in msg["reasoning_details"]
                    if isinstance(d, dict))
    if r:
        return r
    c = _raw_content(resp)
    m = _THINK_RE.match(c)
    if m:
        return m.group(1)
    if c.lstrip().startswith("<think>"):
        return c.lstrip()[len("<think>"):]
    return ""


def tool_calls(resp):
    """Extract the tool_calls list (empty if none)."""
    return _msg(resp).get("tool_calls") or []


def json_spans(text, opener="{", closer="}"):
    """(start, span) for every balanced opener...closer span of text, left to right, outermost
    only, skipping brackets inside JSON strings. An opener that never closes is skipped."""
    i = 0
    while i < len(text):
        if text[i] == opener:
            depth, in_str, esc = 0, False, False
            for j in range(i, len(text)):
                ch = text[j]
                if in_str:
                    if esc:
                        esc = False
                    elif ch == "\\":
                        esc = True
                    elif ch == '"':
                        in_str = False
                elif ch == '"':
                    in_str = True
                elif ch == opener:
                    depth += 1
                elif ch == closer:
                    depth -= 1
                    if depth == 0:
                        yield i, text[i:j + 1]
                        i = j
                        break
        i += 1


def finish_reason(resp):
    return resp["choices"][0].get("finish_reason")


def usage(resp):
    """Normalized usage. reasoning_tokens / cached_tokens / cost_usd are None when the
    backend doesn't report them (None is not 0)."""
    u = resp.get("usage") or {}
    ctd = u.get("completion_tokens_details") or {}
    ptd = u.get("prompt_tokens_details") or {}
    t = resp.get("timings") or {}
    cached = ptd.get("cached_tokens")
    if cached is None:
        cached = t.get("cache_n")
    return {
        "prompt_tokens": u.get("prompt_tokens") or 0,
        "completion_tokens": u.get("completion_tokens") or 0,
        "reasoning_tokens": ctd.get("reasoning_tokens"),
        "cached_tokens": cached,
        "cost_usd": u.get("cost"),
    }


def timings(resp):
    """llama-server timings (None elsewhere). prefill_ps excludes cached tokens."""
    t = resp.get("timings") or {}
    return {
        "prefill_ps": t.get("prompt_per_second"),
        "decode_ps": t.get("predicted_per_second"),
        "prompt_n": t.get("prompt_n"),
        "prompt_ms": t.get("prompt_ms"),
        "predicted_n": t.get("predicted_n"),
        "predicted_ms": t.get("predicted_ms"),
        "cache_n": t.get("cache_n"),
        "draft_n": t.get("draft_n"),
        "draft_n_accepted": t.get("draft_n_accepted"),
    }


def status(resp):
    """ok | truncated (finish=length) | empty (no answer and no tool call)."""
    if finish_reason(resp) == "length":
        return "truncated"
    if not content(resp).strip() and not tool_calls(resp):
        return "empty"
    return "ok"


def meta(resp, wall_s=None):
    """Standard per-call fields for a result row."""
    u = usage(resp)
    b = resp.get("_bench") or {}
    row = {
        "status": status(resp),
        "finish": finish_reason(resp),
        "prompt_tokens": u["prompt_tokens"],
        "completion_tokens": u["completion_tokens"],
        "reasoning_tokens": u["reasoning_tokens"],
        "cached_tokens": u["cached_tokens"],
        "reasoning_chars": len(reasoning(resp)),
        "content_chars": len(content(resp)),
        "wall_s": None if wall_s is None else round(wall_s, 2),
        "attempts": b.get("attempts"),
        "request_hash": b.get("request_hash"),
        "cost_usd": b.get("cost_usd"),
        "provider": b.get("provider"),
        "gen_id": b.get("gen_id"),
    }
    row.update({k: v for k, v in timings(resp).items() if v is not None})
    return row


def error_meta(err, wall_s=None):
    """Result-row fields for a failed call (CallError or anything else)."""
    if isinstance(err, CallError):
        return {"status": err.label(), "error": str(err)[:300], "attempts": err.attempts,
                "wall_s": None if wall_s is None else round(wall_s, 2)}
    return {"status": "harness_error", "error": repr(err)[:300],
            "wall_s": None if wall_s is None else round(wall_s, 2)}