Metadata-Version: 2.4
Name: margin-referee
Version: 0.1.12
Summary: Can you ship this AI change? A verdict on a model, prompt, tool or host change from your own eval cases, with a receipt anyone can verify.
License: MIT
Keywords: llm,evals,model-selection,agents,promptfoo,langfuse,braintrust
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: dev
Requires-Dist: pytest>=7; extra == "dev"
Provides-Extra: verify
Requires-Dist: cryptography>=42; extra == "verify"
Dynamic: license-file

# margin-referee

The verdict on an AI change, from your own eval cases: holds up, got worse, or too close to call. A
free CLI your agent or CI can call; Margin is the hosted version with receipts, agent keys and spend
caps.

A new model, prompt or tool can pass your evals and still break a customer, and two scores side by
side cannot tell a real change from noise. Eval platforms now label their own compares better or
worse; this is a second opinion from a tool that sells no model and no eval platform, with its method
stated (https://trymargin.io/methods).

`margin-referee` sits on top of the eval tool you already use. It reads the cases you have (a
promptfoo results file, a Braintrust, LangSmith or Langfuse dataset export, or JSONL) and tests a
change on them: a new model, a new system prompt, a changed tool list, or the same model on another
endpoint. It runs what you use today and the candidate, grades both with each case's own check, and
answers holds up, got worse, or too close to call when there are too few cases to tell. `check` gives
the same verdict on two experiments you already scored (Braintrust, LangSmith, Inspect or MLflow),
and runs nothing. `noise` shows how often your own "it scored 3 points higher" rule fires between
two runs of the same system. What the change does to
cost is one line of the answer. No account, no backend, no telemetry.

Published on PyPI (https://pypi.org/project/margin-referee/) and GitHub
(https://github.com/trymargin/margin-referee).

The JSON keeps a `decision` field for scripts (`ship`, `ship_if_worth_the_cost`, `do_not_ship`,
`not_enough_evidence`); `answer` says the same in the words used everywhere else: holds up (at a
higher cost), got worse, too close to call.

```
pip install margin-referee
margin-referee fit cases.jsonl
OPENROUTER_API_KEY=... margin-referee replay cases.jsonl \
    --baseline openai/gpt-4.1 --candidate openai/gpt-6-luna --cap 1
```

## Why another eval tool

Because "the candidate scored higher on our evals" is how most bad switches start. Three things
make it unreliable, and this tool corrects for each:

- **Small sets lie.** The verdict is a paired test on the cases both models ran. Only the cases
  they disagree on carry evidence, and a clean sweep on 20 cases proves nothing. `fit` tells you,
  for free and before anything runs, how many cases you need: about 100 against a current model
  that passes everything, and more as its pass rate falls.
- **The best of several looks better than it is.** Try four models on the same cases and keep the
  winner, and you have mostly found noise. The 0.97 bar stays put, but the confidence it must be
  shown at rises with every candidate you try on overlapping cases (remembered in
  `~/.margin-referee/ledger.json`), so renaming or trimming the
  cases does not reset it. To confirm a winner, replay it alone on cases none of them saw.
- **Half-graded cases flatter the candidate.** A case with a check this tool cannot run (an LLM
  rubric, say) is left out and counted, never half-graded. An answer cut off by the output limit,
  or a call that errored, is unanswered, not a fail, and any unanswered case stops it holding up.
  It does not hide a loss: if the change is still worse than the bar allows with every unanswered
  case counted as a win for the candidate, the answer is got worse, not too close to call.

## What the bound covers

The bound is a paired test on the cases, so by default it covers which cases were drawn and
nothing else. It does not cover variation from running the system again (a judge, rubric, harness
or sampler that gives a different answer the second time), and that part does not shrink as you add
cases. Give it repeated runs (`replay --repeats 2` or more) and it measures that spread: it takes
each side's pass rate in each run, estimates the variance between runs, and adds it to the case
variance before taking the one-sided 95% bound. The verdict then carries `rerun_variance` with the
runs per side and the size in points, and the receipt says so. With one run per side nothing about
the verdict changes. It still does not cover anything that was the same in every run, such as a
grader that is wrong the same way each time, and the estimate from two or three runs is rough.

## What `replay` also does

- **It stops paying once the answer is clear.** From 40 cases on, the replay stops as soon as the
  answer is already got worse: even the reading most favourable to the candidate misses the
  bar. Each look is held to a stricter test (Bonferroni across the planned looks), so looking often
  cannot manufacture a loss. It never stops early for ship; `stopped_early` says when it stopped,
  and `--no-early-stop` runs every case. (Borrowed from VERDICT, `verdict-gate`.)
- **Reliability, with `--repeats 3`** (1 to 5). Each case runs that many times per side and passes
  only if every run passed (pass^k); the paired test reads that strict result. `reliability` gives
  pass@1 and pass^k per side, the cases that flipped between runs, and an estimate of the repeats
  needed to see a 1-point gap. Spend scales with the repeats.
- **Traffic weights.** Give a case a `weight` (or `metadata.weight`: its share of traffic, or a
  count) and `weighted` reports the same cases weighted by traffic, including the share of traffic
  on the cases that got worse. It is a weighting of the same cases, not a new test: the decision
  stays on the unweighted paired test.
- **The verdict explains itself.** On too close to call, `settle` repeats the plan's case counts
  (how many cases would show it holds or is worse at the observed rates) and, with repeats, says
  whether the gap is smaller than the share of cases that flipped between runs. `capped_failures`
  lists the candidate's cases cut off by the output limit; those cases are left unanswered, never
  graded as fails, and `why` says to re-run with a higher `--max-tokens`. Neither field changes
  the decision.

## Runs that cannot reach a verdict are refused before they spend

A paid replay that ends too close to call for a reason you could have known first is wasted
money. `replay` checks for those reasons in order and stops at the first one it finds. The
decision is then `refused_before_spend`, the reason is the first line printed, and the exit
code is 3.

1. **Size, free.** If you have fewer gradable cases than the gate needs (`cases_needed`, 100
   for one candidate), no result could be `ship`, so nothing runs. `--anyway` runs it as a
   check that can only find a loss, and the output says so.
2. **Smoke, a few cents.** The first two cases run on both models. If a call errors (a model
   id that does not exist, a 4xx or 5xx, a schema the endpoint rejects, an answer the check
   cannot read), the run stops with the exact error and what it spent. An answer cut off by
   the output limit is retried once at double the limit, up to 32768 tokens. If it is still
   cut off, the run stops and names the limit. Set the limit with `--max-tokens`.
3. **Budget.** The full run is estimated from the two smoke cases plus 20%. If that is more
   than `--cap`, the run stops and names the cap it would need. On OpenRouter it also reads
   what your key can still spend. If the estimate is more than that, the run stops. If the
   balance cannot be read, the output says `balance not checked` and the run goes on.

The two smoke cases are the first two cases of the full run, so a run that goes ahead pays
for nothing twice.

Three more guards work during the run:

- A 402 (out of credit) stops the run at once. Every later call would fail the same way.
- A case lost to a 429, a 5xx, a timeout or a dropped connection is tried once more when the
  run ends. So is an answer cut off by the output limit, at double the limit. A 400, 401, 403,
  404 or 422 is not retried: the same call would fail again.
- If so many cases have no answer that the rest cannot reach `cases_needed`, the run stops
  and says so. No later case could have made the verdict `ship`.

Every verdict carries a `preflight` block: `size`, `smoke`, `budget`, `estimate_usd`,
`balance_usd` and the `max_tokens` the run ended up using.

Exit codes for `replay`: 0 holds up (and costs no more), 1 got worse, too close to call, or
holds up at a higher cost, 2 no case can be graded, 3 refused before spend.

### Per-case results: `--cases-out`

`replay --cases-out runs.jsonl` writes one JSONL row for every case, side and run: `id`,
`segment`, `side` (`baseline` or `candidate`), `model`, `run` (1 to `--repeats`), `passed` and
`cost` in USD. A case a side could not answer has `passed: null` and an `error`. With `--models`,
each model gets its own file, `runs.<model>.jsonl`.

`noise` and `check` read that file as it is, so you never write a runner:

```
margin-referee replay cases.jsonl --baseline openai/gpt-4.1 --candidate openai/gpt-6-luna \
    --cap 1 --repeats 2 --cases-out runs.jsonl
margin-referee noise runs.jsonl                      # the baseline's two runs (--side candidate for the other)
margin-referee check runs.jsonl runs.jsonl --scorer passed
margin-referee fit cases.jsonl --results runs.jsonl
```

`noise` needs two runs of one side, so replay with `--repeats 2` or more. `check` takes the file
twice: its first argument reads the baseline rows and its second the candidate rows.


## Case file format

A case file is JSONL, one case a line. Every case needs an `id`, an `input` (a string, or `messages`
in the OpenAI shape) and a deterministic check. `segment`, `group`, `weight` and `tags` are
optional. A case with free-text expected output and no check is left out and counted as ungraded,
because a string compare cannot grade it.

```
{"id": "t1", "input": "Is claim 4471 covered, denied or needs_review? One word.", "check": "equals", "expected": "covered", "segment": "triage"}
{"id": "t2", "input": "Extract claim 4471 as JSON with claim_id, status, peril. No code fences.", "expected": {"claim_id": "4471", "status": "covered", "peril": "burst pipe"}, "segment": "extraction"}
{"id": "t3", "input": "Look up claim 4471.", "tools": [{"type": "function", "function": {"name": "lookup_claim", "description": "Fetch a claim.", "parameters": {"type": "object", "properties": {"claim_id": {"type": "string"}}}}}], "check": "tool-call", "expected": "name=lookup_claim;args.claim_id=4471", "segment": "tools"}
```

An `expected` object with two or more fields and no `check` is a `json-match`. A bare `expected`
string and no `check` is an `equals` label of up to 80 characters. Every check the package grades:

| `check` | `expected` | passes when |
| --- | --- | --- |
| `equals` | the label | the answer equals it, ignoring case, spaces and surrounding quotes or full stops |
| `contains` | text | the answer contains it, case sensitive |
| `icontains` | text | the answer contains it, ignoring case |
| `regex` | a Python regex | the regex matches somewhere in the answer |
| `is-json` | none | the answer parses as JSON |
| `json-field` | `field=value` | that field of a JSON answer equals the value, ignoring case |
| `json-match` | a JSON object | every field of the object equals the answer's field, ignoring case |
| `tool-call` | `tool` or `name=tool;args.field=value` | the model's first tool call is that tool with those arguments |

The JSON checks parse the answer as it comes. An answer wrapped in a code fence is a fail, so say
"no code fences" in the prompt your cases use, or the check will grade the fence.

`examples/cases.example.jsonl` has one case for each check above (eight, so you can copy the line
you need). `margin-referee fit examples/cases.example.jsonl` runs on it.

## Testing a tool change

A tool description is a prompt the model reads on every call. Rewrite one, or add or remove a
tool, and the agent may start calling the wrong tool. To test that before it ships, give each
JSONL case the tools the call offers and say which tool it should call:

```
{"id": "refund-policy", "input": "How long do I have to return shoes?",
 "tools": [{"type": "function", "function": {"name": "search_kb", "description": "Search.",
            "parameters": {"type": "object", "properties": {"query": {"type": "string"}}}}}],
 "check": "tool-call", "expected": "search_kb"}
```

- `tools` is an OpenAI-style function tool list, and `tool_choice` is optional. Both are sent
  with every call, as they are.
- `check: "tool-call"` passes when the model's first tool call is the `expected` tool. To check
  arguments too, write pairs separated by `;`, such as
  `name=lookup_order;args.order_id=A1042`. Values compare as text, ignoring case.
- No tool call is a fail. A call whose arguments cannot be read, or an endpoint that does not
  report tool calls, leaves the case unanswered. It is never counted as a pass.

Then put the new tool list in a file and replay with `--candidate-tools`. The candidate gets
that list in place of each case's tools; the baseline keeps the case's own. The model can stay
the same:

```
cd examples/tool_change
OPENROUTER_API_KEY=... margin-referee replay cases.jsonl \
    --baseline openai/gpt-4.1 --candidate openai/gpt-4.1 \
    --candidate-tools candidate_tools.json --cap 1 --anyway
```

`examples/tool_change` has three cases and a `candidate_tools.json` that rewrites two vague
descriptions. Three cases show the format and prove nothing: without `--anyway` the replay is
refused before it spends, with it the verdict is `not_enough_evidence`, and `fit` says how many
cases you need. Each tool list you try counts as
a candidate, the same as a prompt. Tool cases run on OpenRouter and on OpenAI-compatible, Azure
OpenAI and Vertex AI endpoints; a Bedrock endpoint leaves them unanswered for now. A promptfoo
results file carries no tool list, so write tool cases as JSONL.

## For MCP and tool vendors

You publish a tool list. Other teams' agents read it on every call, so a rewritten description
or a renamed tool changes how those agents behave, and you do not hold their eval cases. You do
hold your own logs: what was asked, and which tool was called. That is enough to gate a change.

**1. Draft cases from your log.** Give `draft-tool-cases` the tool list callers get today and a
JSONL file with one real request per line:

```
{"request": "Where is my order A1042?", "tool": "lookup_order", "args": {"order_id": "A1042"}}
{"request": "Do you ship to Canada?"}
```

```
cd examples/tool_vendor
margin-referee draft-tool-cases requests.jsonl --tools tools_list.json
```

It calls no model and costs nothing. It writes two files:

- `draft_cases.jsonl`: one `tool-call` case for each request whose log line names the tool that
  was called. The case expects that tool, plus the arguments the log recorded.
- `needs_review.jsonl`: the requests with no recorded tool, or with a tool that is not in the
  list. These rows have no check. The drafter never picks a tool for them, and a replay grades
  none of them.

The request can be under `request`, `input`, `messages`, `prompt`, `query` or `question`. The
call can be `tool` with `args`, or `tool_call` / `tool_calls` in the OpenAI shape. A line that
is not JSON is read as the request text. `segment` and `group` are kept: set `group` to the
user or conversation when one sent many requests, because the gate counts those as one.

Every row carries `draft: true` and `source_line`, the line of your log it came from. Read each
case against that line before you rely on it. A logged call is what the agent did, which is
not always what it should have done. Delete an argument from `expected` when it is free text
(a search query, say), since no two runs word it the same way. `replay` warns while any case
is still marked as a draft.

The output says how many drafts are gradable and how many the gate needs (100 for one
candidate, more for each extra one; pass `--candidates`). It exits 0 when you have enough and
2 when you do not. The files are written either way.

**2. Use your MCP `tools/list` response as the tool list.** `--tools` and `--candidate-tools`
both take OpenAI function tools or an MCP `tools/list` response: the JSON-RPC reply, its
`result`, or the bare `tools` array. Each `{name, description, inputSchema}` becomes a function
tool with `inputSchema` as its `parameters`. A tool with no name, an `inputSchema` that is not
a JSON Schema object, more than 64 tools, or one page of a paged list (`nextCursor`) is refused
with the reason. Nothing is repaired or trimmed.

**3. Get one verdict per caller model.** Your callers run different models, and a description
that reads well to one can mislead another. `--models` runs the same change on each:

```
OPENROUTER_API_KEY=... margin-referee replay draft_cases.jsonl \
    --models openai/gpt-4.1,anthropic/claude-haiku-4.5,google/gemini-2.5-flash \
    --candidate-tools tools_list_new.json --cap 3
```

Each model is its own baseline: the model with the tools in the cases, against the same model
with the new list. The output is one JSON object with a verdict for each model and a summary
line, such as `2 of 3 caller models: ship; not: google/gemini-2.5-flash`.

- `--cap` is the limit for the whole command. It is split evenly between the models.
- Every verdict is held to all the models in the run. Three models are three tries at the same
  change, so each verdict carries `candidates_tried: 3` and needs more cases than one model
  alone would. Earlier tool lists tried against a model on these cases are added on top.
- Exit codes: 0 when every model's answer is holds up, 1 when any model's is not (got worse or too close to call), 3 when a
  model was refused before spend and none said no, 2 when no case can be graded. With
  `--models` the exit code follows `decision`. A tool change on the same model costs the same,
  so the single-model exit code, which also asks for a lower cost, would never be 0.
- `--receipt out.json` writes one unsigned receipt per model, named `out.<model>.json`.

`--models` needs `--candidate-tools` or `--candidate-system`, and it runs on OpenRouter. For a
model in your own account, run `replay` once with `--baseline-endpoint` and
`--candidate-endpoint`.

## A second opinion on a comparison you already ran

Ran the baseline and a cheaper model as two Braintrust experiments (by hand, or with Loop)?
`check` reads both, pairs the cases, and gives the same verdict, without calling a model:

```
margin-referee check baseline.jsonl candidate.jsonl --scorer correct
BRAINTRUST_API_KEY=... margin-referee check bt:<baseline id> bt:<candidate id> --scorer correct
```

A pass is the named score at or above `--threshold` (default 1.0, full credit only). Pass
`--candidates N` when several models were tried on the same cases. A case one experiment lacks
stops it holding up. With no `metrics.estimated_cost` in the exports, it says whether quality
held but claims no saving. Exit code 0 means it holds up.

The same command covers a change the referee cannot make itself: a new version of your agent
framework, harness or SDK. Run your suite once on each version, write one JSON line per case
with the same `input` on both sides and the score under `scores`, and compare the two files:

```
{"input": {"task": "refund-17"}, "scores": {"correct": 1}, "metrics": {"estimated_cost": 0.004}}
margin-referee check before_upgrade.jsonl after_upgrade.jsonl --scorer correct
```

## Testing the eval itself: a new judge, rubric or parser

The judge is part of the instrument. A new judge model, a cheaper judge, or a reworded rubric moves
scores even when the system under test did not change, and scores across the swap then compare two
graders, not two setups. Grade the same saved outputs with the old grader and the new one, and
`judge` puts the two gradings through the same paired test as `check`, in both directions:

```
margin-referee judge old_judge.jsonl new_judge.jsonl --scorer pass
margin-referee judge results.jsonl --old-scorer judge_v1 --new-scorer judge_v2   # one file, both scores
```

It answers that the judge change alone moves scores (stricter or more lenient), no proven effect,
or not enough evidence (too few cases, or a case only one grader scored). Exit code 0 means scores
are comparable across the two graders, 1 that the grader moved them, 2 that it cannot tell. Run the
old judge twice on the same outputs to measure how often it disagrees with itself.

A planted regression is the other half: score a deliberately worse system and run
`check baseline.jsonl degraded.jsonl --scorer pass`. If it does not say got worse, the suite cannot
see a drop that size, and `fit` says how many cases it would need.

## Judging a LangSmith Engine fix or a SmithTune model

LangSmith Engine proposes a fix as a pull request and "can test that fix against an eval set
before your team ever sees it". SmithTune fine-tunes a model, then "compares it against the base
model in LangSmith" ([The Agent Lake](https://www.langchain.com/blog/the-agent-lake), LangChain,
November 2026). In both, the tool that proposed the change also graded it. `check` reads the two
experiments LangSmith already holds, the baseline and the candidate, and gives the same verdict
it gives everywhere else. It calls no model.

```
LANGSMITH_API_KEY=... margin-referee check ls:<baseline experiment> ls:<candidate experiment> --key correctness
margin-referee check baseline.json candidate.json --source langsmith --key correctness
```

`ls:` takes an experiment id or its name. Use a read-only key. Set `LANGSMITH_ENDPOINT` for the
EU region or a self-hosted install (the default is `https://api.smith.langchain.com`). `--key` is
the feedback key that decides pass or fail, and `--threshold` is the score a pass needs (default
1.0, so a 0/1 score passes at 1).

How an experiment is read:

- Cases are paired by `reference_example_id`, the dataset example a run answered. A root run
  with no example is left out and counted under `counts.unlinked`.
- A run passes only on a numeric or boolean `score` for the key, at or above the threshold.
- A run with no feedback for the key, feedback with only a category label, a run that errored
  and a run that did not finish are unanswered. Each is listed with its reason. Unanswered is not
  a fail, and it stops it holding up.
- With repetitions, a case passes only if every repeat passed. One failed repeat fails the case.
- Cost is the runs' recorded `total_cost`. A run with none, or with zero, has no recorded cost.
  A fine-tune LangSmith has no price for is not free, so the verdict then says whether quality
  held and claims no saving (`cost: not_recorded`).
- Segments come from a run's `metadata.segment` or `metadata.category`, else from the example's
  dataset split when it has exactly one.

An exported file is one JSON object, `{"runs": [...], "feedback": [...], "examples": [...]}`, or
JSONL with one run or feedback row per line. Only the root runs and their feedback rows are
needed. `examples` is optional and only supplies the splits. From the LangSmith Python SDK:

```python
runs = [r.dict() for r in client.list_runs(project_name="my-experiment", is_root=True)]
feedback = [f.dict() for f in client.list_feedback(run_ids=[r["id"] for r in runs])]
json.dump({"runs": runs, "feedback": feedback}, open("candidate.json", "w"), default=str)
```

Not yet confirmed against a live LangSmith account (the reader was built from LangSmith's
published OpenAPI document and tested against responses shaped like it):

- that `POST /api/v2/runs/query` with `include_subtree_usage` puts the whole trace's cost on the
  root run. If it does not, cost reads as not recorded and no saving is claimed.
- what `total_cost` holds for a model LangSmith has no price for (the reader treats zero and
  null the same way: not recorded).
- that every evaluator's feedback row carries the root run's id in `run_id`. Feedback written to
  a child run would leave the case unanswered.
- self-hosted installs older than v0.16, which do not serve the v2 endpoints. Export to a file
  there.

## Judging two Inspect eval logs

Ran an [Inspect](https://inspect.aisi.org.uk/) task (UK AISI's `inspect_ai`) on the model you use
and on the one you want to try? `check` reads the two logs and gives the same verdict. It calls no
model.

```
margin-referee check logs/baseline.eval logs/candidate.eval --source inspect --scorer match
margin-referee check baseline.json candidate.json --source inspect --scorer model_graded_qa
```

`--scorer` is the scorer's name as it appears in each sample's `scores`. How a log is read
(field names from `inspect_ai` 0.3.292's own source):

- A `.json` log is one `EvalLog`; a `.eval` log is the zip Inspect writes (`header.json` plus one
  `samples/<id>_epoch_<n>.json` per sample and epoch). Inspect compresses `.eval` with zstd.
  Python reads that from 3.14; on older Pythons it is read through `zipfile_zstd` when installed
  (`inspect_ai` installs it). Otherwise the error says to run `inspect log convert --to json`.
- Samples are paired by `id`. A sample one log has and the other lacks is unanswered.
- A score value is read the way Inspect reads it: `C` is 1, `P` is 0.5, `I` and `N` (no answer)
  are 0, `yes`/`true` 1, `no`/`false` 0. A pass is a value at or above `--threshold` (default 1,
  so partial credit is not a pass).
- With several epochs, a case passes only if every epoch passed. Inspect itself reports the mean
  over epochs; the referee is stricter.
- A sample with no score for the scorer, a list or dict value, or an `error` is unanswered, with
  its reason. Unanswered is never a pass or a fail, and it stops it holding up.
- Cost is each sample's `model_usage` `total_cost`. A model with none leaves no recorded cost, and
  then the verdict says whether quality held and claims no saving.
- A log whose `status` is not `success` is incomplete evidence, and the verdict says so.

## Judging two MLflow evaluation runs

Evaluated two versions with MLflow? `check` reads each run's per-row results from a file and
gives the same verdict:

```
margin-referee check baseline.json candidate.json --source mlflow --scorer correctness
```

The file is either of these (field names from `mlflow` 3.18.0's own source):

- `mlflow.genai.evaluate`: the result's `result_df`, or `mlflow.search_traces(run_id=...)`, saved
  with `df.to_json("run.json", orient="records")` (`orient="split"` also reads). The score is the
  `<scorer>/value` column, else the row's `assessments` of that name.
- `mlflow.evaluate`: the `eval_results_table.json` artifact it logs, with a `<metric>/score`
  column per metric. Pass the metric name as `--scorer`.

Rows are paired as `mlflow.genai.compare_evaluations` pairs them: by the trace's eval request id
(the `mlflow.eval.requestId` tag), else by the row's `inputs` (or `request`). A row with neither is
counted under `counts.unkeyed`. `yes`/`true` is 1 and `no`/`false` is 0. A row with no score, a
score that is not a number or yes/no, a scorer error or a trace in state `ERROR` is unanswered,
never a pass or a fail. Two rows with the same key in one run are repeats: the case passes only if
both passed. MLflow records tokens but not prices, so `check` says whether quality held and claims
no saving (`cost: not_recorded`).

## The verdict on a Hurdle suite

Ran a [Hurdle](https://github.com/togethercomputer/hurdle) suite with and without a skill, or on
two models? `hurdle` reads the runs it saved and says whether the difference is real:

```
margin-referee hurdle .hurdle --compare condition --baseline baseline --candidate with-skill
margin-referee hurdle .hurdle --compare model --baseline <model now> --candidate <model to try>
```

A task passes only if every repeat passed, and `repeats_passed` shows each side's count. A run
Hurdle marked incomplete or unknown leaves its task unanswered, which stops it holding up.

## Judging an ontology layer: NVIDIA ontology-sql-eval

Ran [ontology-sql-eval](https://github.com/NVIDIA/ontology-sql-eval) to compare a schema-only
prompt with the ontology-grounded agent? `ontology-sql` reads the two arms' result files and
says whether to ship the layer. It calls no model and needs nothing of NVIDIA's installed:

```
margin-referee ontology-sql runs
margin-referee ontology-sql runs/full_20261126 --price-in 5 --price-out 25 --price-cached 0.5 --json
```

It reads `<run>/control/<dataset>.jsonl` and `<run>/treatment/<dataset>.jsonl`, pairs the
questions by `task_id`, and applies the referee's rules, which are stricter than the harness's
own report:

- A pass is the verifier's positive verdict. A wrong result, a query that errored or timed out,
  or no SQL in the answer is a fail.
- A gold query that did not run, a run with no model output, an unknown error, or a question
  one arm has no row for is unanswered. It is listed with its reason, counts as neither a pass
  nor a fail, and stops it holding up. The harness scores some of these as misses, so its
  accuracy and this one can differ on the same run.
- Tokens per question come from the per-call capture block on each row when the run recorded
  one, otherwise from the ontology arm's own totals. Cost is those tokens times the
  `--price-in` and `--price-out` you give (USD per million tokens). The files carry no price,
  so without both flags cost reads `not_recorded` and nothing is guessed.
- Cached input is read per call (`cached_tokens` in the capture block, otherwise the ontology
  arm's `agent_cached_input_tokens`) and is part of the input count. Give `--price-cached`
  (USD per million cached input tokens) to price it at its own rate. Without that flag cached
  input is priced as fresh, and the cost basis says so. The cached rate is used only when both
  arms recorded the split; if either did not, the output says `cache split not recorded` and
  all input is priced as fresh. No split is guessed.
- The cache-hit share (cached input over all input) is printed for each arm, and the JSON has
  `cache: {baseline: {fresh_in, cached_in, share}, candidate: {...}, line}`, totals over the
  paired questions. When the two arms differ by ten points or more you get a line such as
  `the candidate's cache-hit share fell from 80% to 12%`, so a change that breaks prompt
  caching shows up. The share changes cost only. It never changes a pass, a fail or the
  quality verdict.
- The ontology arm makes many more calls per question. If the pass rate only holds, the answer
  is `not_enough_evidence`: a layer that is not cheaper ships on a proven gain. If the gain is
  proven it reads `ship_if_worth_the_cost`, with the questions won and lost and the 95% bound
  on the gain, and the decision to pay is yours.
- Results are also read per `difficulty` (or `db_id`; choose with `--segment-by`), so a gain
  overall cannot hide a loss on the hard questions.

`--baseline-arm` and `--candidate-arm` name the two folders, or two rollout files, if yours are
called something else. Swap them to ask the opposite question: can the layer be dropped?

The file layout and field names were read from the harness source at commit `871bb924`
(2026-11-26) and the tests use rows made in that shape. The cached-input field names were read
from one real run's files (WideWorldImporters, 41 questions, 2026-11-27). Prices you pass are
yours: a list price is not what a gateway billed.

## A receipt for the verdict

`replay`, `check`, `hurdle` and `ontology-sql` take `--receipt out.json`. It writes the verdict as an
[in-toto Statement](https://github.com/in-toto/attestation) in a DSSE envelope: the decision, the
bar, the paired counts and gap, how many candidates were tried, cost per case, each segment, and a
list of what the record does not show. A receipt you write this way is **unsigned** and says
`assuranceLevel: self-run`. It is your own claim in a format someone else can read.

A receipt Margin's hosted service issues is signed with Ed25519. Check one with:

```
pip install 'margin-referee[verify]'
margin-referee verify receipt.json --key-url https://trymargin.io/.well-known/margin-receipt-key
```

So the check does not rest only on the issuer's own website, the key's id is printed here too, in a
file published on PyPI and GitHub. Margin's receipt key (2026-11) has keyid
`a89b466ecdb7dbe0eb307b5aaeca8d41e83beef20d3eae19aa77605cf66d5aeb`, the SHA-256 of the raw public key; `verify` prints the keyid it checked against.

Exit 0 means the holder of that key signed it and nobody edited it since. It is a signed record,
not a certification: it does not show the grader is right, that the cases cover production, or
what a person decided to ship.

## What it runs on

- **OpenRouter**, with your own key: any model it serves. To test the same model on another host,
  pass an endpoint with a `provider`: `{"kind": "openrouter", "model": "z-ai/glm-5.3",
  "api_key": "...", "provider": "wafer/fp4"}` sends every call to that one host, with no
  fallback to another seller. Your account's data policy decides which hosts you can reach; a
  host it excludes is refused before anything is spent, and the reason says so.
- **A model in your own account**, with `--candidate-endpoint` or `--baseline-endpoint` and a
  JSON object: `bedrock` (region, model, a Bedrock API key), `vertex_ai` (project, region, model,
  access token), `azure_openai` (resource, deployment, key) or `openai_compatible` (base URL,
  model, key: a fine-tune, vLLM, a self-hosted model). Your credential is used for that run only,
  and you give your own per-token price, so a negotiated discount counts.
- **A prompt change**: `--candidate-system` replays the candidate with a new system prompt. Each
  prompt you try counts as a candidate.
- **A tool change**: `--candidate-tools` replays the candidate with a new tool list (see
  "Testing a tool change").

## What it does not do

It does not open the pull request, watch the change after you merge it, keep the history across
your team, or let your agents call it with a spend limit. That is
[Margin](https://trymargin.io), which runs this same test.

MIT licensed.

## Calling it from a coding agent

An agent can run every command above through its shell; `AGENTS.md` in this repository is written
for it: run `fit` first, branch on the exit code, report the decision word as given, and never
raise `--cap` on its own. For an agent that should call a hosted verdict over MCP instead, with
signed receipts and a spend limit a person sets, add Margin's server:

```
claude mcp add --transport http margin https://trymargin.io/api/mcp \
    --header 'Authorization: Bearer ${MARGIN_INGEST_KEY}'
```

## Release rules, set before the comparison

A pass rate can hide a regression that a release owner would never ship. A cheaper model that
answers empty on two cases, or returns JSON missing a field, can still clear the bar on score.
Rules catch those cases. You write them down before you read any result:

```json
{"rules": [
  {"type": "empty_output"},
  {"type": "json_schema", "name": "answer_shape",
   "schema": {"type": "object", "required": ["answer"]}},
  {"type": "refusal", "phrases": ["I can't help with that", "I'm unable to"]},
  {"type": "malformed_tool_call"},
  {"type": "must_pass", "cases": ["refund-policy-1", "refund-policy-2"]}
]}
```

```
margin-referee replay cases.jsonl --baseline A --candidate B --cap 1 --rules rules.json
margin-referee check base.json cand.json --scorer correct --rules rules.json
```

- **The veto.** The candidate breaks a rule on a case where the baseline did not break it.
  The decision is then `do_not_ship`, whatever the score, and `why` names the rule and the
  case ids. If both sides break a rule on the same case, it is reported and vetoes nothing,
  because the change did not cause it.
- **The types.** `empty_output`: no text and no tool call. `json_schema`: the answer is not
  JSON, or does not match the schema. Only `type`, `properties`, `required`, `items`, `enum`,
  `const`, `additionalProperties`, the min/max length, item and value bounds, and the
  annotations are supported. `refusal`: the answer contains one of your phrases, matched case
  and spacing insensitive. The referee has no refusal detector of its own and does not guess.
  `malformed_tool_call`: a call with no function name, arguments that are not a JSON object,
  or a tool the call was not offered. `must_pass`: the named case must pass on the candidate.
  It reads only the pass or fail, so it works on a scores-only export. A name matches the
  case id, or a `metadata.group` when each repeat of a case is its own row; the case then
  fails on a side if any repeat failed there.
- **Refused, never ignored.** An unknown rule type, an unknown field and an unsupported schema
  keyword are all errors, raised before any case runs or any experiment is read.
- **Fixed in advance.** The verdict carries `rules.sha256`, the SHA-256 of the rules as
  canonical JSON (sorted keys, no spaces), and so does the receipt (`releaseRules`). A rule
  added after the results were seen shows up as a different hash.
- **Unchecked is not passed.** A rule that needs outputs cannot be checked on a paired case
  that has none, for example a LangSmith read that never selects `outputs`. Those cases are
  counted in `rules.unchecked`, and a `ship` becomes `not_enough_evidence`. A must-pass case
  with no answer on both sides does the same.
- **No rules, no change.** Without `--rules`, the verdict is the same as before.

The verdict's `rules` block holds, per rule, how many cases each side broke it on, how many
both broke, and the first ten cases where only the candidate did.

## The evidence plan in every verdict

Every verdict carries a `plan`, including `not_enough_evidence` and `refused_before_spend`. It
says how many cases would settle the gap this run saw, at the bar. The estimate rests on stated
assumptions, and the plan spells them out:

- the observed pass rates, the share of cases where the two sides disagree, and the losses and
  wins;
- the bar (the candidate keeps 97% of the baseline's pass rate), 95% one-sided;
- the candidates tried and the Bonferroni correction for them (the z and the floor it moves);
- that cases are independent (with declared groups it says more may be needed), and that the
  observed rates stay the same as the suite grows.

`cases_to_hold` is the smallest suite at these rates on which the change would be shown to
hold. `cases_to_show_worse` is the same for a proven loss. Both come from `stats.reach`, the
same search every other "how many cases" answer uses. With repeats, `repeats` gives the runs
per case that would keep run-to-run noise under a one-point gap at the measured flip rates.
When the gap sits so close to what the bar allows that no suite up to 2,000 cases settles it,
the plan says so.

It is an estimate, not a promise. New cases may not behave like these, and the plan only
reports what the observed rates imply.

## What blocks a verdict on this suite: the `fit` check-up

`fit` is free and offline, and it answers one question: what, if anything, blocks a verdict on
this suite? It prints a checklist. Every line has a count, its n, and one of three kinds:
`blocker` (a verdict cannot stand until it is fixed), `observation` (measured, does not block)
or `not_measured` (the input lacks the data, and the line says what to supply). Nothing it
cannot measure is shown as a zero. There is no grade and no score.

```
margin-referee fit cases.jsonl                          # the cases alone
margin-referee fit cases.jsonl --results runs.jsonl     # plus the scored runs
margin-referee fit cases.jsonl --clause clause.txt      # plus the buyer's clause
```

The lead line is "nothing blocks a verdict at this size" or "N things block a verdict". Exit 0
when nothing blocks, 2 when something does. The old fields (`graded`, `needed`, `ready`,
`losses_absorbed`, ...) are still there.

| line | blocks when | needs |
|---|---|---|
| run accounting | a case errored, has no usable score, or is missing | results; the case file as the manifest, else "completeness unknown" |
| size against the bar | fewer cases (or declared groups) than a clean result needs at the baseline pass rate | the cases |
| case independence | never; says whether the cases declare groups, and what treating clustered cases as independent costs | the cases |
| saturation | never; at 100% it says only a loss can show | results |
| cases that never fail or never pass | never; each with its run count | results |
| duplicate cases | the exact copies hide a suite under the gate floor | the cases |
| discriminating power | never | results from two or more models |
| judge agreement | the judge's TPR or TNR against people is under 0.8 | `judge_pass` and `human_pass`, 10 of each kind |
| segment coverage | a `--critical` segment is under the cases it needs on its own | segment labels |
| flakiness under repeats | more runs per case are needed than were run | every repeat of each case |
| clause gap | never; it names the clause's concerns (from a fixed list of 16 words such as safety, privacy, bias) that no case id, segment, group or tag mentions | `--clause` |

The clause gap is a keyword match on labels only. It never reads a case's input, and a label that
mentions a concern is not evidence that the cases cover it, so the line says the team should
confirm.

A case that never failed is reported, whatever its run count, as a plain chance: "passed 11 of
11; a 10% failure rate would go unseen about 31% of the time", that is `(1 - 0.1) ** 11`. Under
29 runs, where that chance is still over 5%, it adds "too few runs to say". It never calls a
case fine or broken: a case no model has failed yet may be easy, or may be unable to fail.

Results can be a promptfoo results file, Braintrust or LangSmith events (`scores`, with
`--scorer` when a row has several), or JSONL with `pass`, `passed`, `success` or `score` and
`error`. Optional fields: `model` (or `metadata.model`), `run` or `trial` (or
`--run-suffix '#'` when the ids are `t0#0`, `t0#1`), `judge_pass`, `human_pass`. `fit` counts only
exact copies, because similar prompts are often deliberate boundary tests; `audit` names
near-copies for a person to judge. Nothing
here measures contamination or whether the suite predicts production.

The hosted product's MCP tool `margin_fit_check` returns the same checklist, from the same code.

## Do the cases cover the risk? The `audit` report

A signature shows a result was not edited. A reviewer's next question is whether the cases cover
the risk. `audit` is free and offline and reviews the case set itself, not a model comparison.

```
margin-referee audit cases.jsonl
margin-referee audit cases.jsonl --results a.jsonl --results b.jsonl --clause clause.txt
```

JSON on stdout, one plain line on stderr. Exit 0 when nothing is found, 1 when issues are found,
2 when a file could not be read. It lists:

- cases that never failed (or never passed). Only when the runs can say so: the run floor
  `fit` uses, or two or more models each run on the case. One run of one model is listed, not
  flagged.
- inputs that repeat exactly, and near-copies (input word sets overlapping 85% or more, for
  inputs of five words or more; skipped above 1,000 cases).
- segments with fewer than 10 cases, and a suite under the gate floor.
- whether the suite tells the models apart: it needs results from two or more models, and it is
  flagged when no case was failed by any of them.
- with `--clause`, the words of the clause (five letters or more, common words dropped) that no
  case input, id, segment, group or tag uses. This is a keyword match on the first six letters
  of each word. It cannot see meaning: a word a case mentions is not proof the case tests it.

It does not read a verdict, change one, or call a case fine or broken.

## Does your rule catch noise? The `noise` report

Run the same system twice on the same cases and the pass rate moves anyway: a model samples, an
endpoint changes under you, a flaky check flips. A team that reads "3 points better" as a real
change will act on noise. One published A/A test, ten identical runs on 150 problems, found a
3-point rule fired on 10 of 45 comparisons of identical systems
([Verne Systems](https://blog.vernesystems.com/llm-regression-noise-aa-test), October 2026). `noise` measures that on your own runs, for free:

```
margin-referee noise run1.jsonl run2.jsonl run3.jsonl
margin-referee noise repeats.jsonl --points 2           # rows carry a run (or trial) field
margin-referee noise log.eval --source inspect --scorer match   # Inspect epochs are runs
```

Every pair of runs is one comparison of identical systems. For each, it reports:

- the naive rule: the two pass rates on the cases both runs scored, and whether they differ by
  `--points` or more (default 3, either way);
- how often the naive rule would have BLOCKED the change: it fired and the second run scored
  lower;
- the referee's paired verdict on the same pair, the earlier run as baseline. Its `ship` means
  "not worse at the bar" and never claims better, so on identical systems `ship` and
  `not_enough_evidence` are both right. Its one false alarm is `do_not_ship`, a claim that the
  second run is worse, and that is what is counted. A pair whose bound happens to clear zero is
  shown as it is ("the referee says ship (not worse); it does not claim better"), with the bound.

Runs can be separate files, one file whose rows carry `run`, `trial` or `repeat` (or
`--run-suffix '#'` for ids like `t0#1`), Inspect epochs (`--source inspect`) or MLflow results
tables (`--source mlflow`, one file per run). A case errored in one run is left out of that pair's
rates and is unanswered for the referee. `--json` prints every pair.

It never invents a repeat. One run exits 2 and says a second run is needed. `--split-seed N` is
the one exception: it cuts one run's cases into random halves (seeded, `--splits` times) and
compares their pass rates. The output is labelled `SPLIT, NOT REPEAT RUNS`: halves share no case,
so this measures only which cases were drawn, and the referee has nothing to pair.

Worked examples on public suites: every set of repeat runs in Margin's public bench record (captured
2026-11-01), committed under `examples/noise/`. Three runs of `openai/gpt-4o-mini`, three of
`openai/gpt-4.1-nano` and two of `deepseek/deepseek-v4-flash` on the 164 HumanEval+ problems; two of
`openai/gpt-4o` and three of `openai/gpt-4o-mini` on the 34 Python exercises of Aider's polyglot
benchmark. The output, pasted from the command:

```
$ cd examples/noise
$ margin-referee noise humanevalplus_gpt-4o-mini_3_runs.jsonl
3 runs of the same system, 3 comparisons. A 3-point rule fired on 1 of 3 (33%); 0 of those would have blocked the change. The referee said got worse (do_not_ship), the only false alarm it can raise here, on 0 of 3 (0%). Its answers: too close to call 2, holds up 1 (holds up means not worse at the bar; it never claims better).
  humanevalplus_gpt-4o-mini_3_runs.jsonl#0 vs humanevalplus_gpt-4o-mini_3_runs.jsonl#1: 164 cases, +3.66 points, naive rule FIRES, referee ship
  humanevalplus_gpt-4o-mini_3_runs.jsonl#0 vs humanevalplus_gpt-4o-mini_3_runs.jsonl#2: 164 cases, +1.22 points, naive rule quiet, referee not_enough_evidence
  humanevalplus_gpt-4o-mini_3_runs.jsonl#1 vs humanevalplus_gpt-4o-mini_3_runs.jsonl#2: 164 cases, -2.44 points, naive rule quiet, referee not_enough_evidence
$ margin-referee noise humanevalplus_gpt-4.1-nano_3_runs.jsonl
3 runs of the same system, 3 comparisons. A 3-point rule fired on 0 of 3 (0%); 0 of those would have blocked the change. The referee said got worse (do_not_ship), the only false alarm it can raise here, on 0 of 3 (0%). Its answers: too close to call 3 (holds up means not worse at the bar; it never claims better).
  humanevalplus_gpt-4.1-nano_3_runs.jsonl#0 vs humanevalplus_gpt-4.1-nano_3_runs.jsonl#1: 163 cases, +0.61 points, naive rule quiet, referee not_enough_evidence
  humanevalplus_gpt-4.1-nano_3_runs.jsonl#0 vs humanevalplus_gpt-4.1-nano_3_runs.jsonl#2: 163 cases, -1.84 points, naive rule quiet, referee not_enough_evidence
  humanevalplus_gpt-4.1-nano_3_runs.jsonl#1 vs humanevalplus_gpt-4.1-nano_3_runs.jsonl#2: 164 cases, -2.44 points, naive rule quiet, referee not_enough_evidence
$ margin-referee noise humanevalplus_deepseek-v4-flash_2_runs.jsonl
2 runs of the same system, 1 comparisons. A 3-point rule fired on 0 of 1 (0%); 0 of those would have blocked the change. The referee said got worse (do_not_ship), the only false alarm it can raise here, on 0 of 1 (0%). Its answers: too close to call 1 (holds up means not worse at the bar; it never claims better).
  humanevalplus_deepseek-v4-flash_2_runs.jsonl#0 vs humanevalplus_deepseek-v4-flash_2_runs.jsonl#1: 164 cases, +0.00 points, naive rule quiet, referee not_enough_evidence
$ margin-referee noise aider-polyglot-python_gpt-4o_2_runs.jsonl
2 runs of the same system, 1 comparisons. A 3-point rule fired on 1 of 1 (100%); 1 of those would have blocked the change. The referee said got worse (do_not_ship), the only false alarm it can raise here, on 0 of 1 (0%). Its answers: too close to call 1 (holds up means not worse at the bar; it never claims better).
  aider-polyglot-python_gpt-4o_2_runs.jsonl#0 vs aider-polyglot-python_gpt-4o_2_runs.jsonl#1: 34 cases, -5.88 points, naive rule FIRES, would block, referee not_enough_evidence
$ margin-referee noise aider-polyglot-python_gpt-4o-mini_3_runs.jsonl
3 runs of the same system, 3 comparisons. A 3-point rule fired on 0 of 3 (0%); 0 of those would have blocked the change. The referee said got worse (do_not_ship), the only false alarm it can raise here, on 0 of 3 (0%). Its answers: too close to call 3 (holds up means not worse at the bar; it never claims better).
  aider-polyglot-python_gpt-4o-mini_3_runs.jsonl#0 vs aider-polyglot-python_gpt-4o-mini_3_runs.jsonl#1: 34 cases, +0.00 points, naive rule quiet, referee not_enough_evidence
  aider-polyglot-python_gpt-4o-mini_3_runs.jsonl#0 vs aider-polyglot-python_gpt-4o-mini_3_runs.jsonl#2: 34 cases, +2.94 points, naive rule quiet, referee not_enough_evidence
  aider-polyglot-python_gpt-4o-mini_3_runs.jsonl#1 vs aider-polyglot-python_gpt-4o-mini_3_runs.jsonl#2: 34 cases, +2.94 points, naive rule quiet, referee not_enough_evidence
```

Across the five sets that is 11 comparisons of identical systems. The 3-point rule fired on 2 of
them (18%), and on 1 of those it would have blocked a change that did nothing (gpt-4o on Aider, 34
cases, 5.88 points lower). The referee said `do_not_ship` on none of the 11: it answered
`not_enough_evidence` on 10 and `ship` (not worse) on 1. Eleven comparisons are too few to give
either a false-alarm rate. Run your own system more times before trusting one.
