llm-bench

"""Lane profiles: one JSON file per (server, model, request settings) under test.

A lane is everything that decides what a model is asked and how: endpoint, model id, full
sampler, max_tokens, thinking on/off and how it is turned off, provider pinning, timeouts and
provenance. Instruments read it through `current()` and the client merges it into every
request, so two lanes are always compared under recorded settings, never server defaults.
LANE=<id> loads lanes/<id>.json, LANE=<path> loads that file; LANE is required.

Lane file keys (all optional except lane_id, endpoint, model):
  lane_id, description, base_model
  card                HF repo id of the model card whose sampler applies (a key of lanes/cards.json;
                      the base model's card for a straight quant). Conformance checks the sampler.
  sampler_overrides   {"<field>": {"value": <sent value>, "reason": "..."}} accepted card deviations
  runner              "claude-cli": agentic attempts run on headless `claude -p` (bench/core/claude_cli.py;
                      model = --model, effort = --effort); no HTTP endpoint, no card, no sampler
  endpoint            chat-completions URL
  model               value of the request "model" field
  auth                {"keychain_service": "<svc>"} | {"env": "<VAR>"[, "required": true]} | null
  thinking            "on" | "off"
  nothink             {"mechanism": "reasoning_effort_none" | "openrouter_reasoning_off"
                                    | "template_kwargs" | "think_prefill"}  (thinking "off" only)
  request             merged into every body; wins over instrument defaults
                      (temperature, top_p, top_k, min_p, presence_penalty,
                       repetition_penalty, max_tokens, seed, reasoning_effort ...)
  extra_body          deep-merged last (provider pinning, usage accounting ...)
  forbid              {"<field>": [bad values]} -> refused client-side
  merge_system_messages, reasoning_echo, retries   client behaviour (see client.py)
  http_timeout        seconds per request (default 1800)
  max_concurrency     upper bound for instruments that run items in parallel
  cost                {"ledger": "<name>", "cap_usd": 5.0, "in_per_m": .., "out_per_m": ..}
  snapshot            "llama-server" | "mtplx" | "openrouter" | "none"
  weights, runtime, context   free-form provenance, copied into every run record
"""
import json
import os
import subprocess
import threading

HERE = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
LANES_DIR = os.path.join(HERE, "lanes")

NOTHINK_MECHANISMS = ("reasoning_effort_none", "openrouter_reasoning_off",
                      "template_kwargs", "think_prefill")

_current = None
_lock = threading.Lock()


class LaneError(ValueError):
    pass


class Lane:
    def __init__(self, raw, source):
        self.raw = raw
        self.source = source
        for key in ("lane_id", "endpoint", "model"):
            if not raw.get(key):
                raise LaneError(f"lane {source}: missing {key!r}")
        self.lane_id = raw["lane_id"]
        self.endpoint = raw["endpoint"]
        self.model = raw["model"]
        self.thinking = raw.get("thinking", "on")
        if self.thinking not in ("on", "off"):
            raise LaneError(f"lane {self.lane_id}: thinking must be 'on' or 'off'")
        self.nothink = raw.get("nothink")
        if self.thinking == "off":
            mech = (self.nothink or {}).get("mechanism")
            if mech not in NOTHINK_MECHANISMS:
                raise LaneError(f"lane {self.lane_id}: thinking 'off' needs nothink.mechanism "
                                f"in {NOTHINK_MECHANISMS}")
        self.request = dict(raw.get("request") or {})
        self.extra_body = dict(raw.get("extra_body") or {})
        self.forbid = dict(raw.get("forbid") or {})
        self.http_timeout = int(raw.get("http_timeout", 1800))
        self.max_concurrency = int(raw.get("max_concurrency", 1))
        self.cost = raw.get("cost")
        self.snapshot_kind = raw.get("snapshot", "none")
        self._key = None

    # ---- auth -------------------------------------------------------------
    def api_key(self):
        """Resolve the bearer token at call time. Never logged or returned in records."""
        if self._key is not None:
            return self._key
        auth = self.raw.get("auth") or {}
        key = ""
        if auth.get("env"):
            key = os.environ.get(auth["env"], "")
            if not key and auth.get("required"):
                raise LaneError(f"lane {self.lane_id}: env {auth['env']} is empty (auth.required)")
        elif auth.get("keychain_service"):
            try:
                p = subprocess.run(["security", "find-generic-password", "-s",
                                    auth["keychain_service"], "-w"],
                                   capture_output=True, text=True, timeout=30)
                key = p.stdout.strip() if p.returncode == 0 else ""
            except (FileNotFoundError, subprocess.TimeoutExpired):
                key = ""
            if not key:
                raise LaneError(f"lane {self.lane_id}: keychain item "
                                f"{auth['keychain_service']!r} not readable")
        self._key = key
        return key

    # ---- provenance ---------------------------------------------------------
    def record(self):
        """The lane block written into every run record (no secrets)."""
        r = {k: v for k, v in self.raw.items() if k != "auth"}
        auth = self.raw.get("auth") or {}
        r["auth_kind"] = next(iter(auth), None)
        r["source"] = self.source
        return r

    def base_url(self):
        """Server root, e.g. http://host:8000 for .../v1/chat/completions."""
        ep = self.endpoint
        for suffix in ("/v1/chat/completions", "/chat/completions"):
            if ep.endswith(suffix):
                return ep[: -len(suffix)]
        return ep.rsplit("/", 1)[0]


def load(spec):
    """Load a lane from an id (lanes/<id>.json) or a path."""
    path = spec if (os.sep in spec or spec.endswith(".json")) else os.path.join(LANES_DIR, spec + ".json")
    if not os.path.isfile(path):
        raise LaneError(f"lane file not found: {path}")
    with open(path) as f:
        raw = json.load(f)
    return Lane(raw, os.path.relpath(path, HERE) if path.startswith(HERE) else path)


def current():
    """The active lane for this process (LANE env)."""
    global _current
    with _lock:
        if _current is None:
            spec = os.environ.get("LANE", "").strip()
            if not spec:
                raise LaneError("LANE is not set; set LANE=<id> to one of the lanes/*.json files.")
            _current = load(spec)
        return _current


def set_current(lane):
    """Tests / multi-lane drivers: replace the active lane."""
    global _current
    with _lock:
        _current = lane