llm-bench

"""Spend ledger + cap for paid lanes (OpenRouter).

Every paid call appends {ts, lane_id, run_id, item_id, cost_usd, gen_id,
provider} to bench/results/_ledger/<ledger>.jsonl. Before each call the client asks
`check()` whether spent-so-far + a worst-case estimate for this call would
cross the cap; if so it raises BudgetExceeded and the instrument records the
item as status "budget_stop" (not as a model failure).

The ledger is a plain append-only file guarded by an flock, so several bench
processes (one per lane) share one budget. The cap comes from the lane's
`cost.cap_usd`, overridable with LEDGER_CAP_USD. It is a soft cap: concurrent calls can each
pass check() before any of them is recorded, and overshoot it.
"""
import fcntl
import json
import os
import time

from bench.core.reporting import RESULTS_DIR

LEDGER_DIR = os.path.join(RESULTS_DIR, "_ledger")


class BudgetExceeded(RuntimeError):
    pass


def _path(name):
    os.makedirs(LEDGER_DIR, exist_ok=True)
    return os.path.join(LEDGER_DIR, f"{name}.jsonl")


def spent(name):
    p = _path(name)
    if not os.path.exists(p):
        return 0.0
    total = 0.0
    with open(p) as f:
        fcntl.flock(f, fcntl.LOCK_SH)
        for line in f:
            if line.strip():
                total += float(json.loads(line).get("cost_usd") or 0.0)
        fcntl.flock(f, fcntl.LOCK_UN)
    return total


def cap_for(cost_cfg):
    env = os.environ.get("LEDGER_CAP_USD")
    if env:
        return float(env)
    return float(cost_cfg.get("cap_usd", 0.0))


def estimate(cost_cfg, prompt_chars, max_tokens):
    """Worst-case $ for one call: ~3.5 chars/token in, full max_tokens out."""
    in_m = float(cost_cfg.get("in_per_m", 0.0))
    out_m = float(cost_cfg.get("out_per_m", 0.0))
    return (prompt_chars / 3.5) * in_m / 1e6 + (max_tokens or 0) * out_m / 1e6


def check(cost_cfg, prompt_chars, max_tokens):
    """Raise BudgetExceeded if this call could push the ledger past the cap."""
    name = cost_cfg.get("ledger", "default")
    cap = cap_for(cost_cfg)
    if cap <= 0:
        return
    now = spent(name)
    est = estimate(cost_cfg, prompt_chars, max_tokens)
    if now + est > cap:
        raise BudgetExceeded(
            f"ledger {name!r}: spent ${now:.4f} + worst-case ${est:.4f} > cap ${cap:.2f}")


def record(cost_cfg, *, lane_id, run_id, item_id, cost_usd, gen_id, provider):
    name = cost_cfg.get("ledger", "default")
    row = {"ts": time.strftime("%Y-%m-%dT%H:%M:%S"), "lane_id": lane_id, "run_id": run_id,
           "item_id": item_id, "cost_usd": cost_usd, "gen_id": gen_id, "provider": provider}
    with open(_path(name), "a") as f:
        fcntl.flock(f, fcntl.LOCK_EX)
        f.write(json.dumps(row) + "\n")
        fcntl.flock(f, fcntl.LOCK_UN)