llm-bench

"""Router instrument: how well a model dispatches requests to a menu of worker tiers.

ROUTE (26 items): emit one JSON decision {"target", "reason", "confidence"} for a request.
  correct = target in the item's acceptable set without a privacy violation (a local_only
  request sent to a CLOUD worker); rows also record exact match, format fidelity and the
  cost-ordered escalation error (esc_err > 0 over-, < 0 under-escalated). Category route/<cat>.
ORCH (8 items): split a compound request into a JSON array of steps, each with a `kind`, a
  `worker` and depends_on edges. correct = every required kind covered, every known-kind step on
  a capable worker, every required dependency reachable, no privacy violation. Category orch.
JUDGE (32 items, router_sets.py; suite v3, 2026-10-12): small models as graders of computing work.
  verdict (24): does the candidate (code, command, query, log summary, config, answer) meet the
  task? {"verdict": "pass"|"fail"}; correct = matches gold. Reports false-pass / false-fail.
  pairwise (8): which of two candidates better meets the task? {"better": "A"|"B"}, asked in both
  orders (item ids <id>/ab and <id>/ba); reports position consistency and position bias.
RERANK (16 items): order 7-8 candidates (code, log lines, docs, commands, errors) for a query.
  {"ranking": [ids]}; correct = top-1 is the single grade-3 candidate; rows add MRR of that
  candidate and NDCG@5 over graded relevance (gain 2^rel - 1).
Families run separately (`run --families route,orch,judge,rerank`, default all), one item set
each: router-<family>@<hash>. Categories route/<cat>, orch, judge/<cat>, pairwise/<cat>, rerank/<cat>.
Scoring is deterministic (no model judges another); `validate` proves the dataset offline.
"""
import argparse
import hashlib
import json
import math
import re
import sys

from bench.core import client, lane as lane_mod, results
from bench.tasks.router_sets import JUDGE, RERANK

INSTRUMENT = "router"


# ---------------------------------------------------------------- the worker menu
# cost is a coarse relative $/latency weight used only to score over/under-escalation.
# "local" workers keep data on the LAN; "cloud" workers send it off-box.
WORKERS = {
    "local_small":  {"cost": 1,  "cloud": False,
        "desc": "A small fast local model (~4B). Cheap, low latency. Good at: greetings and "
                "chit-chat, short factual answers, reformatting, simple extraction/classification, "
                "short summaries, trivial arithmetic."},
    "local_large":  {"cost": 3,  "cloud": False,
        "desc": "A capable local reasoning/coding model (~27-35B on the GPU box). Good at: writing "
                "and debugging code, multi-step reasoning, medium analysis, and agentic tool-use "
                "jobs. Slower and pricier than local_small but still on-LAN and free."},
    "cloud_ollama": {"cost": 6,  "cloud": True,
        "desc": "A mid-tier CLOUD model (Ollama Cloud). More headroom than local_large; use as "
                "overflow for medium-hard work or when local is saturated. Sends data off-box; "
                "metered cost."},
    "cloud_claude": {"cost": 10, "cloud": True,
        "desc": "A frontier CLOUD model (Claude). Best at: the hardest novel/open-ended reasoning, "
                "very-long-context synthesis, and high-stakes correctness. Most expensive; sends "
                "data off-box."},
    "clarify":      {"cost": 0,  "cloud": False,
        "desc": "Not a worker — choose this ONLY when the request is too underspecified to route "
                "and you must ask the user a clarifying question first."},
}
CLOUD = {w for w, m in WORKERS.items() if m["cloud"]}
def cost(w): return WORKERS.get(w, {}).get("cost", 99)

# ---------------------------------------------------------------- ROUTE dataset
# gold = the single best (cheapest capable, constraint-respecting) target.
# ok   = the acceptable set (includes gold + genuine ties); anything outside is wrong.
# local_only=True => request carries sensitive data / an explicit keep-on-LAN rule,
#                    so ANY cloud_* target is a hard privacy violation regardless of skill fit.
ROUTE = [
 # --- trivial / chit-chat -> local_small ---
 {"id":"r-greet","cat":"trivial","gold":"local_small","ok":{"local_small"},
  "request":"Hey! Good morning — how's it going?"},
 {"id":"r-thanks","cat":"trivial","gold":"local_small","ok":{"local_small"},
  "request":"Thanks, that's all I needed. Have a good one!"},
 {"id":"r-reformat","cat":"trivial","gold":"local_small","ok":{"local_small"},
  "request":"Turn this into a bulleted list: eggs, milk, bread, coffee."},
 {"id":"r-arith","cat":"trivial","gold":"local_small","ok":{"local_small"},
  "request":"What's 18% of 250?"},
 # --- simple factual / extraction / classify -> local_small ---
 {"id":"r-fact","cat":"simple","gold":"local_small","ok":{"local_small"},
  "request":"What's the capital of Australia?"},
 {"id":"r-extract","cat":"simple","gold":"local_small","ok":{"local_small","local_large"},
  "request":"Pull the name and email out of this line: 'Contact: Dana Lee <dana.lee@corp.io>'."},
 {"id":"r-classify","cat":"simple","gold":"local_small","ok":{"local_small","local_large"},
  "request":"Is this review positive or negative? 'Honestly the best purchase I made this year.'"},
 {"id":"r-shortsum","cat":"simple","gold":"local_small","ok":{"local_small","local_large"},
  "request":"Give me a one-sentence summary of this paragraph: 'The meeting covered Q3 hiring, the "
            "office move, and the new expense policy. No decisions were finalized.'"},
 # --- medium coding / debug -> local_large ---
 {"id":"r-code-fn","cat":"code","gold":"local_large","ok":{"local_large"},
  "request":"Write a Go function that returns the median of a []float64, handling the even-length case."},
 {"id":"r-debug","cat":"code","gold":"local_large","ok":{"local_large"},
  "request":"This Python raises 'dict changed size during iteration' when I delete keys in the loop. Fix it."},
 {"id":"r-regex","cat":"code","gold":"local_large","ok":{"local_large","local_small"},
  "request":"Write a regex that matches an ISO-8601 date like 2026-08-17 and explain each part briefly."},
 {"id":"r-refactor","cat":"code","gold":"local_large","ok":{"local_large","cloud_ollama"},
  "request":"Refactor this 60-line Python module into three functions with type hints and docstrings."},
 # --- multi-step reasoning (medium-hard) -> local_large, cloud_ollama a fair tie ---
 {"id":"r-reason","cat":"reason","gold":"local_large","ok":{"local_large","cloud_ollama"},
  "request":"Given a 3-tier pricing table, compute the cheapest plan for a customer using 1.2M "
            "requests/mo with 40GB egress, and show the arithmetic."},
 {"id":"r-plan","cat":"reason","gold":"local_large","ok":{"local_large","cloud_ollama"},
  "request":"Draft a step-by-step migration plan to move a Postgres 14 DB to 18 with minimal downtime."},
 # --- hard / novel / high-stakes -> cloud_claude ---
 {"id":"r-hard-algo","cat":"hard","gold":"cloud_claude","ok":{"cloud_claude","cloud_ollama"},
  "request":"Design and prove the correctness of a lock-free MPMC ring buffer with wraparound, "
            "including the memory-ordering argument for each atomic."},
 {"id":"r-hard-novel","cat":"hard","gold":"cloud_claude","ok":{"cloud_claude"},
  "request":"We're being sued over an ambiguous SLA clause. Analyze the legal exposure, argue both "
            "sides, and recommend a settlement posture. This goes to our board."},
 {"id":"r-hard-arch","cat":"hard","gold":"cloud_claude","ok":{"cloud_claude","cloud_ollama"},
  "request":"Critique the trade-offs of event-sourcing vs CRUD for a fintech ledger that must pass a "
            "SOC 2 audit, and recommend one with justification."},
 # --- very-long-context synthesis -> cloud_claude (context, not just difficulty) ---
 {"id":"r-longdoc","cat":"longdoc","gold":"cloud_claude","ok":{"cloud_claude","cloud_ollama"},
  "request":"Here are five 40-page vendor contracts. Synthesize every conflicting indemnification "
            "clause across all of them into one comparison table."},
 {"id":"r-longcode","cat":"longdoc","gold":"cloud_claude","ok":{"cloud_claude","cloud_ollama"},
  "request":"Read this entire 12,000-line legacy codebase and produce an architecture overview plus "
            "the three riskiest coupling points."},
 # --- overflow / mid-cloud is the intended tier -> cloud_ollama ---
 {"id":"r-overflow","cat":"overflow","gold":"cloud_ollama","ok":{"cloud_ollama","local_large"},
  "request":"local_large is currently saturated with a long job. I need a medium-difficulty code "
            "review done now on a 200-line PR. Where should this go?"},
 # --- privacy: must stay local regardless of difficulty ---
 {"id":"r-priv-secret","cat":"privacy","gold":"local_large","ok":{"local_large","local_small"},"local_only":True,
  "request":"Here is our production database password and connection string. Write a script to rotate "
            "it. Do NOT send any of this off our network."},
 {"id":"r-priv-pii","cat":"privacy","gold":"local_small","ok":{"local_small","local_large"},"local_only":True,
  "request":"This spreadsheet has 500 customers' SSNs and home addresses. Just tell me how many rows "
            "have a missing ZIP code. Keep it on-prem — compliance rule."},
 {"id":"r-priv-hard","cat":"privacy","gold":"local_large","ok":{"local_large"},"local_only":True,
  "request":"Analyze this internal, unreleased financial model (highly confidential, must not leave "
            "the building) and find the three biggest risks in the assumptions."},
 # --- ambiguous / underspecified -> clarify ---
 {"id":"r-amb-vague","cat":"clarify","gold":"clarify","ok":{"clarify"},
  "request":"Can you help me with the thing from yesterday?"},
 {"id":"r-amb-it","cat":"clarify","gold":"clarify","ok":{"clarify"},
  "request":"Fix it."},
 {"id":"r-amb-empty","cat":"clarify","gold":"clarify","ok":{"clarify"},
  "request":"?"},
]

# ---------------------------------------------------------------- ORCH dataset
# Each compound request must decompose into steps tagged with a `kind` (from KINDS)
# and assigned a `worker`. Scoring is by KIND, not by exact wording:
#   coverage  = every required_kind appears in the plan
#   assign    = every produced step whose kind is known is routed to a capable worker
#   ordering  = for each (a,b) in deps, some kind-b step depends (directly/transitively)
#               on some kind-a step
KINDS = {
 "chat","extract","classify","summarize","math","code","debug","reason",
 "longdoc","draft_message","web_search",
}
# which workers are *capable* of each kind (cheapest-capable-first is the ideal, but
# any capable worker counts as a correct assignment; escalation cost is scored on ROUTE).
CAPABLE = {
 "chat":         {"local_small","local_large"},
 "extract":      {"local_small","local_large"},
 "classify":     {"local_small","local_large"},
 "summarize":    {"local_small","local_large","cloud_ollama","cloud_claude"},
 "math":         {"local_small","local_large"},
 "code":         {"local_large","cloud_ollama","cloud_claude"},
 "debug":        {"local_large","cloud_ollama","cloud_claude"},
 "reason":       {"local_large","cloud_ollama","cloud_claude"},
 "longdoc":      {"cloud_ollama","cloud_claude"},
 "draft_message":{"local_small","local_large"},
 "web_search":   {"local_small","local_large","cloud_ollama"},
}
ORCH = [
 {"id":"o-log-code-msg",
  "request":"Summarize what went wrong in this 2,000-line error log, then write a Python function to "
            "parse that log format, then draft a short Slack message telling the team the root cause.",
  "required_kinds":["summarize","code","draft_message"],
  "deps":[("summarize","draft_message")]},
 {"id":"o-extract-analyze-report",
  "request":"Extract the line items from this invoice, check the arithmetic, and draft an email to "
            "accounts payable flagging any discrepancy.",
  "required_kinds":["extract","math","draft_message"],
  "deps":[("extract","math"),("math","draft_message")]},
 {"id":"o-research-code",
  "request":"Look up the current recommended way to do structured logging in Go, then write a small "
            "logging wrapper using it, then write a unit test for the wrapper.",
  "required_kinds":["web_search","code"],
  "deps":[("web_search","code")]},
 {"id":"o-bigdoc-decide-draft",
  "request":"Read these three 50-page RFP responses, compare them on price and SLA, and draft a "
            "one-paragraph recommendation to leadership.",
  "required_kinds":["longdoc","reason","draft_message"],
  "deps":[("longdoc","reason"),("reason","draft_message")]},
 {"id":"o-classify-route",
  "request":"Classify these 20 support tickets by urgency, summarize the urgent ones, and write a "
            "message assigning them to on-call.",
  "required_kinds":["classify","summarize","draft_message"],
  "deps":[("classify","summarize"),("summarize","draft_message")]},
 {"id":"o-debug-explain",
  "request":"Figure out why this Go service deadlocks under load, fix it, and write a short postmortem "
            "message for the incident channel.",
  "required_kinds":["debug","draft_message"],
  "deps":[("debug","draft_message")]},
 {"id":"o-privacy-chain","local_only":True,
  "request":"Using this confidential internal salary dataset (must stay on-prem), compute the median "
            "pay gap by department and draft an internal memo summarizing it.",
  "required_kinds":["math","draft_message"],
  "deps":[("math","draft_message")]},
 {"id":"o-simple-two",
  "request":"Extract the phone numbers from this contact list and format them as an E.164 list.",
  "required_kinds":["extract"],
  "deps":[]},
]

# ---------------------------------------------------------------- local helpers
def _first_json(text, opener, closer):
    """The JSON value whose span starts at the first `opener` of text (think blocks removed), or
    None; later spans are never tried."""
    text = re.sub(r"<think>.*?</think>", "", text, flags=re.DOTALL)
    start, span = next(client.json_spans(text, opener, closer), (None, None))
    if start is None or start != text.find(opener):
        return None
    try:
        return json.loads(span)
    except ValueError:
        return None

# ---------------------------------------------------------------- ROUTE phase
MENU_TEXT = "\n".join("  - %s (cost %d, %s): %s" %
                      (w, m["cost"], "CLOUD/off-box" if m["cloud"] else "on-LAN", m["desc"])
                      for w, m in WORKERS.items())
ROUTE_SYSTEM = (
    "You are a dispatch router. Every incoming request must be handled by exactly one worker. "
    "Pick the CHEAPEST worker that can do the job well — keep easy work local, and only escalate "
    "to a bigger or cloud worker when the task genuinely needs it (hard novel reasoning, very long "
    "context, or high-stakes correctness). Hard rule: if the request contains sensitive/confidential "
    "data or says to keep data on-prem/on-LAN, you MUST choose an on-LAN worker (never a CLOUD one), "
    "even if a cloud worker would be more capable. If the request is too vague to route, choose "
    "'clarify'.\n\nWorkers:\n" + MENU_TEXT +
    "\n\nRespond with ONLY a single JSON object and nothing else:\n"
    '{"target": "<one worker name>", "reason": "<short>", "confidence": <0.0-1.0>}')

def score_route(item, resp):
    c = client.content(resp)
    obj = _first_json(c, "{", "}")
    rec = {"gold": item["gold"]}
    if not obj or "target" not in obj:
        rec.update({"format_ok": False, "target": None, "exact": False,
                    "acceptable": False, "detail": ("no JSON target: %r" % c[:140])})
        return rec
    target = str(obj.get("target", "")).strip()
    valid = target in WORKERS
    ok_set = item["ok"]
    exact = target == item["gold"]
    acceptable = target in ok_set
    local_only = item.get("local_only", False)
    priv_violation = bool(local_only and target in CLOUD)
    esc = cost(target) - cost(item["gold"]) if valid and target != "clarify" and item["gold"] != "clarify" else 0
    rec.update({
        "format_ok": valid, "target": target, "confidence": obj.get("confidence"),
        "exact": exact, "acceptable": acceptable and not priv_violation,
        "priv_violation": priv_violation, "esc_err": esc,
        "detail": "" if (acceptable and not priv_violation) else
                  ("PRIVACY: sent local-only to cloud" if priv_violation else
                   "routed %s, ok=%s" % (target, sorted(ok_set))),
    })
    return rec

# ---------------------------------------------------------------- ORCH phase
ORCH_SYSTEM = (
    "You are an orchestrator. Break the user's compound request into an ordered plan of atomic steps. "
    "For EACH step choose a task `kind` and assign the cheapest capable `worker`, and list which "
    "earlier steps it depends on. Same routing rules as dispatch: keep cheap work local, escalate only "
    "when needed, and NEVER assign a CLOUD worker to a step that handles on-prem/confidential data.\n\n"
    "Valid kinds: " + ", ".join(sorted(KINDS)) + "\n"
    "Valid workers: " + ", ".join(w for w in WORKERS if w != "clarify") + "\n\n"
    "Respond with ONLY a JSON array (no prose), each element:\n"
    '{"step": <int, 1-based>, "task": "<what to do>", "kind": "<one kind>", '
    '"worker": "<one worker>", "depends_on": [<earlier step ints>]}')

def score_orch(item, resp):
    c = client.content(resp)
    plan = _first_json(c, "[", "]")
    rec = {"required_kinds": item["required_kinds"]}
    if not isinstance(plan, list) or not plan:
        rec.update({"format_ok": False, "coverage": False, "assign_ok": 0.0,
                    "ordering_ok": False, "passed": False,
                    "detail": "no JSON array plan: %r" % c[:140]})
        return rec
    # normalize steps
    steps = []
    for s in plan:
        if not isinstance(s, dict):
            continue
        steps.append({
            "step": s.get("step"),
            "kind": str(s.get("kind", "")).strip(),
            "worker": str(s.get("worker", "")).strip(),
            "depends_on": s.get("depends_on") or [],
        })
    kinds_present = {s["kind"] for s in steps}
    coverage = set(item["required_kinds"]) <= kinds_present
    # assignment: fraction of known-kind steps routed to a capable worker (+privacy)
    local_only = item.get("local_only", False)
    known = [s for s in steps if s["kind"] in KINDS]
    def assign_good(s):
        if local_only and s["worker"] in CLOUD:
            return False
        return s["worker"] in CAPABLE.get(s["kind"], set())
    assign_ok = (sum(1 for s in known if assign_good(s)) / len(known)) if known else 0.0
    priv_violation = bool(local_only and any(s["worker"] in CLOUD for s in steps))
    # ordering: build step->kind and a reachability check over depends_on
    by_step = {s["step"]: s for s in steps if isinstance(s["step"], int)}
    def reaches_kind(start_step, target_kind, seen=None):
        seen = seen or set()
        for dep in (by_step.get(start_step, {}).get("depends_on") or []):
            if not isinstance(dep, int) or dep in seen:
                continue
            seen.add(dep)
            d = by_step.get(dep)
            if not d:
                continue
            if d["kind"] == target_kind or reaches_kind(dep, target_kind, seen):
                return True
        return False
    ordering_ok = True
    for a_kind, b_kind in item["deps"]:
        b_steps = [s["step"] for s in steps if s["kind"] == b_kind and isinstance(s["step"], int)]
        if not b_steps or not any(reaches_kind(bs, a_kind) for bs in b_steps):
            ordering_ok = False
            break
    passed = bool(coverage and assign_ok == 1.0 and ordering_ok and not priv_violation)
    rec.update({
        "format_ok": True, "n_steps": len(steps), "kinds": sorted(kinds_present),
        "coverage": coverage, "assign_ok": round(assign_ok, 2),
        "ordering_ok": ordering_ok, "priv_violation": priv_violation, "passed": passed,
        "detail": "" if passed else "cov=%s assign=%.2f order=%s priv=%s" %
                  (coverage, assign_ok, ordering_ok, priv_violation),
    })
    return rec

# ---------------------------------------------------------------- JUDGE phase
JUDGE_SYSTEM = (
    "You are a strict reviewer of technical work. You get a task and a candidate response to it. "
    "Decide whether the candidate fully and correctly accomplishes the task. Judge correctness, not "
    "style: a terse or unusual answer that is correct passes; a polished answer with a real error "
    "fails.\n\nRespond with ONLY a single JSON object and nothing else:\n"
    '{"verdict": "pass" or "fail", "reason": "<short>"}')
PAIRWISE_SYSTEM = (
    "You compare two candidate responses to the same technical task and pick the one that better "
    "accomplishes it. Judge correctness first, then completeness; ignore style, tone and length.\n\n"
    "Respond with ONLY a single JSON object and nothing else:\n"
    '{"better": "A" or "B", "reason": "<short>"}')


def judge_attempts():
    """(attempt id, payload) per verdict item, and per pairwise item in both orders."""
    out = []
    for it in JUDGE:
        if it["kind"] == "verdict":
            out.append((it["id"], dict(it)))
        else:
            out.append((it["id"] + "/ab", dict(it, order="ab")))
            out.append((it["id"] + "/ba", dict(it, order="ba", a=it["b"], b=it["a"],
                                               gold={"a": "b", "b": "a"}[it["gold"]])))
    return out


def judge_messages(it):
    if it["kind"] == "verdict":
        return [{"role": "system", "content": JUDGE_SYSTEM},
                {"role": "user", "content": "TASK:\n%s\n\nCANDIDATE:\n%s" % (it["task"], it["candidate"])}]
    return [{"role": "system", "content": PAIRWISE_SYSTEM},
            {"role": "user", "content": "TASK:\n%s\n\nCANDIDATE A:\n%s\n\nCANDIDATE B:\n%s"
                                        % (it["task"], it["a"], it["b"])}]


def score_judge(it, resp):
    obj = _first_json(client.content(resp), "{", "}")
    if it["kind"] == "verdict":
        v = str((obj or {}).get("verdict", "")).strip().lower()
        ok = v in ("pass", "fail")
        return {"format_ok": ok, "verdict": v if ok else None, "gold": it["gold"],
                "correct": ok and v == it["gold"]}
    b = str((obj or {}).get("better", "")).strip().lower()
    ok = b in ("a", "b")
    return {"format_ok": ok, "pick": b if ok else None, "gold": it["gold"], "order": it["order"],
            "pair": it["id"], "correct": ok and b == it["gold"]}


# ---------------------------------------------------------------- RERANK phase
RERANK_SYSTEM = (
    "You rank search results. Given a query and candidate passages, order ALL candidate ids from most "
    "to least relevant to what the query is looking for.\n\nRespond with ONLY a single JSON object "
    'and nothing else:\n{"ranking": ["<id>", "<id>", ...]}')


def rerank_messages(it):
    cands = "\n\n".join("[%s]\n%s" % (cid, text) for cid, text in it["candidates"].items())
    return [{"role": "system", "content": RERANK_SYSTEM},
            {"role": "user", "content": "QUERY:\n%s\n\nCANDIDATES:\n%s" % (it["query"], cands)}]


def _dcg(grades):
    return sum((2 ** g - 1) / math.log2(i + 2) for i, g in enumerate(grades))


def score_rerank(it, resp):
    obj = _first_json(client.content(resp), "{", "}")
    raw = (obj or {}).get("ranking") if isinstance(obj, dict) else None
    ids = list(it["candidates"])
    seen = []
    for x in raw if isinstance(raw, list) else []:
        x = str(x).strip().strip("[]")
        if x in ids and x not in seen:
            seen.append(x)
    complete = len(seen) == len(ids) and len(raw) == len(ids)
    ranking = seen + [x for x in ids if x not in seen]  # unranked ids count as last, in id order
    rel = it["relevance"]
    top = max(rel, key=rel.get)
    grades = [rel.get(x, 0) for x in ranking]
    ideal = sorted(rel.values(), reverse=True)
    return {"format_ok": bool(seen), "complete": complete, "ranking": seen, "top": top,
            "top1": bool(seen) and seen[0] == top, "mrr": round(1 / (ranking.index(top) + 1), 4),
            "ndcg5": round(_dcg(grades[:5]) / _dcg(ideal[:5]), 4) if seen else 0.0,
            "correct": bool(seen) and seen[0] == top}


# ---------------------------------------------------------------- phases
def validate():
    """Prove the dataset is well-formed before trusting any model score."""
    ok = True
    for it in ROUTE:
        if it["gold"] not in it["ok"]:
            print("BAD route %s: gold %s not in ok %s" % (it["id"], it["gold"], it["ok"])); ok = False
        if it["gold"] not in WORKERS:
            print("BAD route %s: gold %s not a worker" % (it["id"], it["gold"])); ok = False
        if it.get("local_only") and (it["ok"] & CLOUD):
            print("BAD route %s: local_only but ok set includes cloud" % it["id"]); ok = False
    for it in ORCH:
        for k in it["required_kinds"]:
            if k not in KINDS:
                print("BAD orch %s: kind %s unknown" % (it["id"], k)); ok = False
        for a, b in it["deps"]:
            if a not in it["required_kinds"] or b not in it["required_kinds"]:
                print("BAD orch %s: dep (%s,%s) not both required" % (it["id"], a, b)); ok = False
    ids = [it["id"] for it in JUDGE] + [it["id"] for it in RERANK]
    if len(set(ids)) != len(ids):
        print("BAD judge/rerank: duplicate ids"); ok = False
    for it in JUDGE:
        want = {"verdict": ("task", "candidate"), "pairwise": ("task", "a", "b")}.get(it["kind"])
        golds = {"verdict": ("pass", "fail"), "pairwise": ("a", "b")}.get(it["kind"], ())
        if not want or any(not it.get(k) for k in want) or it.get("gold") not in golds:
            print("BAD judge %s: kind/fields/gold" % it["id"]); ok = False
    for it in RERANK:
        cids, rel = list(it["candidates"]), it["relevance"]
        top = [c for c, g in rel.items() if g == max(rel.values())] if rel else []
        if cids != ["c%d" % i for i in range(1, len(cids) + 1)] or not 6 <= len(cids) <= 10:
            print("BAD rerank %s: candidate ids must be c1..cN, 6-10 of them" % it["id"]); ok = False
        if not set(rel) <= set(cids) or len(top) != 1 or rel[top[0]] != 3 or \
                any(g not in (1, 2, 3) for g in rel.values()):
            print("BAD rerank %s: relevance needs grades 1-3 with exactly one 3" % it["id"]); ok = False
    print("ROUTE %d  ORCH %d  JUDGE %d (%d verdict, %d pairwise)  RERANK %d" % (
        len(ROUTE), len(ORCH), len(JUDGE), sum(i["kind"] == "verdict" for i in JUDGE),
        sum(i["kind"] == "pairwise" for i in JUDGE), len(RERANK)))
    print("VALIDATION %s" % ("PASSED" if ok else "FAILED"))
    return ok


FAMILIES = ("route", "orch", "judge", "rerank")


def family_items(fam):
    """[(attempt id, payload)] for one family; payload carries its family."""
    pairs = {"route": [(it["id"], it) for it in ROUTE], "orch": [(it["id"], it) for it in ORCH],
             "judge": judge_attempts(), "rerank": [(it["id"], it) for it in RERANK]}[fam]
    return [(i, dict(p, family=fam)) for i, p in pairs]


def item_set(fam):
    defs = {"route": [ROUTE, WORKERS, ROUTE_SYSTEM], "orch": [ORCH, WORKERS, CAPABLE, sorted(KINDS), ORCH_SYSTEM],
            "judge": [JUDGE, JUDGE_SYSTEM, PAIRWISE_SYSTEM], "rerank": [RERANK, RERANK_SYSTEM]}[fam]
    h = hashlib.sha256(json.dumps(defs, sort_keys=True, default=sorted).encode()).hexdigest()
    return "router-%s@%s" % (fam, h[:12])


def _attempt(store, lane, it, k):
    fam = it["family"]
    if fam == "route":
        msgs = [{"role": "system", "content": ROUTE_SYSTEM}, {"role": "user", "content": it["request"]}]
        cat, grade = "route/" + it["cat"], lambda resp: (lambda r: dict(r, correct=r["acceptable"]))(score_route(it, resp))
    elif fam == "orch":
        msgs = [{"role": "system", "content": ORCH_SYSTEM}, {"role": "user", "content": it["request"]}]
        cat, grade = "orch", lambda resp: (lambda r: dict(r, correct=r["passed"]))(score_orch(it, resp))
    elif fam == "judge":
        msgs = judge_messages(it)
        cat = ("judge/" if it["kind"] == "verdict" else "pairwise/") + it["cat"]
        grade = lambda resp: score_judge(it, resp)  # noqa: E731
    else:
        msgs, cat, grade = rerank_messages(it), "rerank/" + it["cat"], (lambda resp: score_rerank(it, resp))
    iid = it["id"] + ("/" + it["order"] if fam == "judge" and it["kind"] == "pairwise" else "")
    results.call_attempt(store, lane, iid, k, cat, msgs, grade)


def report_from(rows):
    """Router axes over graded rows (infra rows are counted apart, never scored as a miss)."""
    graded = [r for r in rows if r.get("correct") is not None]
    route = [r for r in graded if r["category"].startswith("route/")]
    orch = [r for r in graded if r["category"] == "orch"]
    print("\nROUTER: %d graded, %d infra" % (len(graded), len(rows) - len(graded)))
    if route:
        n = len(route)
        acc = sum(1 for r in route if r.get("acceptable"))
        exact = sum(1 for r in route if r.get("exact"))
        fmt = sum(1 for r in route if r.get("format_ok"))
        over = sum(1 for r in route if (r.get("esc_err") or 0) > 0)
        under = sum(1 for r in route if (r.get("esc_err") or 0) < 0)
        mae = sum(abs(r.get("esc_err") or 0) for r in route) / n
        priv = sum(1 for r in route if r.get("priv_violation"))
        print("ROUTE  acceptable %d/%d (%.0f%%)  exact %d/%d  format %d/%d" %
              (acc, n, 100 * acc / n, exact, n, fmt, n))
        print("       over-escalate %d  under-escalate %d  |esc| mean %.2f  privacy-violations %d" %
              (over, under, mae, priv))
    judge = [r for r in graded if r["category"].startswith("judge/")]
    pair = [r for r in graded if r["category"].startswith("pairwise/")]
    rer = [r for r in graded if r["category"].startswith("rerank/")]
    if judge:
        n, acc = len(judge), sum(1 for r in judge if r.get("correct"))
        fails = [r for r in judge if r.get("gold") == "fail"]
        passes = [r for r in judge if r.get("gold") == "pass"]
        print("JUDGE  accuracy %d/%d (%.0f%%)  false-pass %d/%d  false-fail %d/%d  format %d/%d" % (
            acc, n, 100 * acc / n, sum(1 for r in fails if r.get("verdict") == "pass"), len(fails),
            sum(1 for r in passes if r.get("verdict") == "fail"), len(passes),
            sum(1 for r in judge if r.get("format_ok")), n))
    if pair:
        n, acc = len(pair), sum(1 for r in pair if r.get("correct"))
        by = {}
        for r in pair:
            by.setdefault((r.get("pair"), r["sample_idx"]), {})[r.get("order")] = r
        both = [v for v in by.values() if len(v) == 2]
        consistent = sum(1 for v in both if v["ab"].get("correct") and v["ba"].get("correct"))
        picks_a = sum(1 for r in pair if r.get("pick") == "a")
        print("PAIR   accuracy %d/%d (%.0f%%)  right in both orders %d/%d  picked first-shown %d/%d" % (
            acc, n, 100 * acc / n, consistent, len(both), picks_a, n))
    if rer:
        n = len(rer)
        print("RERANK top-1 %d/%d (%.0f%%)  MRR %.2f  NDCG@5 %.2f  complete rankings %d/%d" % (
            sum(1 for r in rer if r.get("top1")), n, 100 * sum(1 for r in rer if r.get("top1")) / n,
            sum(r.get("mrr") or 0 for r in rer) / n, sum(r.get("ndcg5") or 0 for r in rer) / n,
            sum(1 for r in rer if r.get("complete")), n))
    if orch:
        n = len(orch)
        p = sum(1 for r in orch if r.get("passed"))
        cov = sum(1 for r in orch if r.get("coverage"))
        aok = sum(r.get("assign_ok") or 0 for r in orch) / n
        ord_ok = sum(1 for r in orch if r.get("ordering_ok"))
        priv = sum(1 for r in orch if r.get("priv_violation"))
        print("ORCH   pass %d/%d (%.0f%%)  coverage %d/%d  mean-assign %.2f  ordering %d/%d  "
              "privacy-viol %d" % (p, n, 100 * p / n, cov, n, aok, ord_ok, n, priv))


def main(argv=None):
    ap = argparse.ArgumentParser(prog="bench.py router")
    sub = ap.add_subparsers(dest="cmd")
    sub.add_parser("validate")
    sub.add_parser("report")
    rp = sub.add_parser("run")
    results.add_run_args(rp)
    rp.add_argument("--families", default=",".join(FAMILIES), help="comma list of: " + ",".join(FAMILIES))
    a = ap.parse_args(sys.argv[1:] if argv is None else argv)
    if a.cmd == "run":
        fams = [f for f in a.families.split(",") if f]
        if set(fams) - set(FAMILIES):
            raise SystemExit("unknown families: %s" % ",".join(sorted(set(fams) - set(FAMILIES))))
        if a.resume:
            with open(a.resume.rstrip("/") + "/run.json") as f:
                fams = [json.load(f)["item_set"].split("@")[0].replace("router-", "")]
        want = {x for x in a.items.split(",") if x}
        for fam in fams:
            items = family_items(fam)
            sel = want & {i for i, _ in items}
            if want and not sel and not a.resume:
                continue
            plan = lambda _args, fam=fam, items=items: (item_set(fam), items)  # noqa: E731
            store, summary = results.run_attempts(
                INSTRUMENT, dict(results.run_args(a), items=sorted(sel) or None, family=fam), plan,
                _attempt, resume=a.resume)
            report_from(store.rows())
            if summary["stopped"]:
                sys.exit(3)
        sys.exit(0)
    if a.cmd == "report":
        rows = results.load_rows(INSTRUMENT, lane_mod.current().lane_id)
        results.print_summary(results.summarize(rows))
        return report_from(rows)
    sys.exit(0 if validate() else 1)


if __name__ == "__main__":
    main()