Files
AiSOC/scripts/compare_eval_runs.py
T
Beenu Arora 83306e5b6e fix: close the maturity plan's remaining clauses, and say what Stable means (#1105)
* fix(retro-hunt): two cross-tenant defects the E2E found, plus the two missing E2Es

Re-reading the plan against the tree found two of its sub-clauses never
landed: "one E2E that round-trips a tenant-scoped query through POST
/lake/sql", and "one E2E from the real threatintel feed through Kafka to
an alert". Both suites stopped one layer short of the seam.

The retro-hunt one found two real defects on its first run, and both are
invisible as the schema owner — they only appear under aisoc_app, the
role a deployment actually uses.

A tenant's rows were flushed under the next tenant's RLS context.
sweep_tenant deliberately does not commit, so its rows sat pending; the
next iteration rebound app.current_tenant_id, and the first query after
that triggered SQLAlchemy's autoflush, writing the previous tenant's rows
while the current tenant's context was active. RLS refused them,
correctly, and retro-hunt persisted nothing.

And one tenant's failure stopped the rest. The loop's own comment says it
must not. The failed flush left the session needing a rollback, so every
later tenant raised PendingRollbackError and was reported failed.

Both are closed by a SAVEPOINT per tenant, driven explicitly rather than
with `async with` — the context-manager form attempts its release outside
the greenlet the async driver runs in and raises MissingGreenlet.

Proven: reverting the savepoint and the per-tenant flush fails 5 of the
8 tests.

The lake E2E covers what rewrite_for_tenant alone cannot: the caller is
authenticated, the tenant comes from the token rather than an argument,
and errors map onto status codes an operator reads. It also asserts a
write is refused *and* that the table still holds its rows, because a
refusal that reached ClickHouse would be worse than an honest accept.
Reverting the rewrite to a pass-through fails 6 of 7.

Three fixture details that each cost a round, all of them the product
being right: the lake stores IPv4 in its IPv6-mapped form, so a bare
dotted quad raises CannotParseDomainError; retro-hunt is per-tenant
opt-in, so a tenant with no settings row is correctly skipped; and
re-running a sweep collides on uq_alerts_tenant_idempotency, because the
same indicator must not open a second alert. The suite now sweeps once,
which is also what one indicator arriving once looks like.

Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com>

* feat(hunt): give the hunting agent its console and MCP callers (parity 6.1)

The plan's clause was "wire hunt/agent.py to the console and MCP so
something other than its own test imports it". The agents-service route
landed earlier; neither of the two surfaces a user actually reaches did.

POST /api/v1/agents/hunt proxies onto it, for the same reason
/cases/{id}/investigate is a proxy: the console and the MCP server both
reach AiSOC through this API, and the agents service is not published.
The tenant comes from the authenticated principal and is never read from
the body — a caller-supplied tenant on a route like this is the shape
that has gone wrong here before.

aisoc_run_hunt is the nineteenth MCP tool, read-only and annotated as
such: a hunt searches, it never acts. Its payload keeps `checked` and
`matches` apart in words as well as in the boolean, because the next
reader is a language model and a hunt that could not run is not a hunt
that found nothing.

On the console, the agent is now what happens when the ES|QL translator
cannot turn a question into a query. That path previously showed a toast
and left the analyst with an empty editor; it now asks the agent to plan
one, and surfaces the honest result — including the planner's refusals
rather than swallowing them, since a plan the validator would not run is
information.

Two gates did their job. The MCP suite pins the tool *set*, so a new tool
fails until the expected surface is updated. And published-count.test.ts
compares the advertised figure against the registry in both directions
across seven documents — README, the docs portal twice, SYSTEM_DESIGN,
REALITY_REPORT, the claim matrix and the landing-page brief — so 18
became 19 everywhere at once rather than drifting in six of them.

Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com>

* test(playbooks): prove http and notify reach a socket, and fix two honesty defects

Parity 5.3's "steps that do something" had suites covering the SSRF
guard's decisions, the step models' bounds and the engine's control flow.
None proved a step ever left the process.

That distinction has a history here: _handle_block_ip and
_handle_isolate_host once returned {"simulated": True} and reached no
executor at all, under a comment claiming playbooks dispatched through
the actions service. A step returning a plausible dict is
indistinguishable from one that acted, and every test asserting on the
dict passes either way.

So this drives the real handlers against a real HTTPServer and asks the
only question that separates them: did a request arrive. Proven by
replacing the http handler's call with a plausible dict — 2 of 7 fail.

The guard is tested from both sides, because a step that always calls out
is as wrong as one that never does. The refusal tests assert the refusal
*and* that nothing arrived, since a refusal that still made the request
is a refusal in name only.

Two defects found along the way.

The module header said AISOC_SSRF_ALLOW_PRIVATE relaxes the
"private/loopback" check. It does not relax loopback, and
_is_disallowed_address's own docstring two hundred lines below has always
said so. The code is the correct half — a playbook that can reach
127.0.0.1 can reach every unauthenticated service on the host running the
engine — so the header is corrected rather than the behaviour. An
operator reading it would have set the flag and been confused.

And notify's non-delivery reason said "no url" whatever the cause,
including when a url *was* supplied and the channel simply had no sender.
That sends someone debugging a silent playbook to look for a missing
field sitting right in front of them. The reason now names the real case.

Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com>

* docs: say what Stable now means, and what CI proves about each piece

The maturity table had been updated to read Stable on every row without
the README ever saying what changed. A reader seeing fifteen Stable rows
has no way to tell an earned label from a relabelled one, which is the
whole thing this work was about.

The README now states the bar in four lines: no path filter, the real
production path, real infrastructure, and a negative control proven by
breaking the thing and watching the check go red. It links the
definition rather than restating it.

That cost four lines of budget and the 250-line cap is genuinely binding,
so four were displaced: three passages that said the same thing twice
(secrets, `make stats`, the synthetic-data table's closing paragraph) and
one `make doctor` sentence that listed what it checks twice over.

The architecture doc gains the table a reader actually wants: for each
capability, the workflow that grades it and what breaking it looks like —
with the measured failure counts, so the negative controls are stated as
results rather than intentions. Two rows exist because the suite behind
them found a defect no offline test could, and the table says which.

Verified: all 19 external URLs return 200, every local path resolves,
every workflow named in the new table exists, and the attribution gate
passes over both the tree and the commits.

Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com>

* fix: three CI findings on this branch

The OpenAPI spec and llms.txt are regenerated artefacts and this branch
changed both of their sources — a new route at POST /api/v1/agents/hunt,
and the README and architecture edits. Both gates were doing their job.

The retro-hunt E2E failed on psycopg2, which is not in any lockfile. That
is the same mistake this branch already fixed once: every live job now
installs from its service's own lock precisely so a hand-curated
dependency list cannot drift, and adding a second Postgres driver for two
INSERTs of test setup would have walked straight back into it. The
fixture uses asyncpg, which is already there.

Verified against real containers rather than assumed: Postgres with all
93 migrations, ClickHouse with the shipped DDL and Redpanda, running as
the aisoc_app runtime role — 8 of 8 pass.

Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com>

* fix: restore the public HuntRequest schema, and triage two unpatchable advisories

Two failures, one mine and one not.

**The OpenAPI break was mine.** detection_rules.py already exports a
HuntRequest, and FastAPI resolves a name collision by qualifying *both*
models with their full module path. So adding a second HuntRequest in
agents.py deleted the plain HuntRequest schema and renamed the existing
one to app__api__v1__endpoints__detection_rules__HuntRequest — breaking
every generated SDK client, for a route that had not changed. Mine is now
AgentHuntRequest/AgentHuntResponse, which is clearer anyway, and the diff
reports 0 changes against base.

**The security-audit failure is a wave of newly-published advisories, and
main has the same exposure.** main's last security-audit run was green at
180b6cbb with the identical lockfile; the advisories were published
after it, so main is stale-green rather than clean and will go red on its
next run.

Both are genuinely unpatchable, verified against the registry rather than
assumed:

- GHSA-ch52-4w7c-c8xp, http-cache-semantics. npm's latest is 4.2.0 and
  the advisory affects <=4.2.0. Reached only through the docs site's
  update check; no Dockerfile builds apps/docs and @docusaurus/core
  appears in no other package.json, so it is in no shipped image.
- GHSA-vfj7-8cjw-p6xm, braces. npm's latest is 3.0.3 and the advisory
  affects <=3.0.3. Stack-exhaustion DoS from expanding a deeply nested
  glob, reached transitively through chokidar and micromatch; the
  patterns they expand come from this repository's own build config, and
  no runtime route accepts a glob.

Both entries expire 2026-12-31 so they come back for re-triage rather
than becoming permanent. pnpm now reports 0 high/critical; python and go
report 0 findings.

Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com>

* feat(evidence): signed, replayable evidence bundles (parity 3.7)

An auditor asks what this thing decided, on what evidence, and whether
anyone edited the answer afterwards. The Investigation Ledger already
held the answer; a bundle makes it portable and tamper-evident.

Three properties, each a decision rather than a default.

Byte-for-byte replayable. Two exports of one run produce identical bytes,
so a bundle can be diffed, re-hashed and checked by someone who does not
trust the exporter. That rules out everything making JSON
non-deterministic: sorted keys, fixed separators, the ledger's own
timestamps rather than now(), nothing naming the host. Events are sorted
so a ledger read returning rows in a different order cannot change the
digest — otherwise the signature becomes a property of the query plan.

Prompts travel as hashes. A prompt carries the customer's hostnames,
usernames and addresses, and a bundle is the artefact most likely to
leave their control. The digest still proves which prompt ran. A step
with no prompt gains no hash field, because a hash of nothing reads as a
prompt that existed.

Absent is not zero. A run with no cost telemetry exports null, not 0.0,
with cost_provenance saying which it was.

The OCSF mapping declares 1.9.0, and that is deliberate. Each object was
checked against schema.ocsf.io before use: ai_agent 404s on 1.1.0 and
1.8.0 and exists only in 1.9.0; ai_operation exists from 1.8.0;
record_integrity exists in 1.9.0 under that exact spelling. The ingest
spine stays at the 1.1.0 its normalizer emits — that is its contract with
connectors — but a bundle declaring 1.1.0 while carrying an ai_agent
would be a false claim about a public standard. Field names come from the
schema rather than invented: ai_model nested inside ai_agent,
attestation_list carrying fingerprint and signatures.

The signature is HMAC-SHA256 and the bundle says what that is worth:
tamper-evidence, not non-repudiation. Anyone holding the deployment key
can forge one. An auditor who assumes public-key signing from the word
"signed" has been misled by us rather than by the format.

GET /investigations/{run_id}/bundle serves it as a download so what gets
verified is the byte sequence that was signed; a client re-serialising a
parsed body would break the signature for a reason nobody could see.

29 tests. The live suite found what a dict-based one cannot: UUIDs,
tz-aware datetimes, Numeric and JSONB all have reprs JSON cannot
serialise. Tenant scoping was measured in both directions — removing the
explicit predicate leaves the test passing because RLS refuses the row
anyway, and only removing the predicate *and* connecting as the schema
owner makes it fail. Both facts are in the test, so nobody concludes from
a green run that the predicate alone is doing the work.

Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com>

* feat(copilot): cite every factual claim, or say it is uncited (parity 3.6)

The copilot answers questions about a customer's own estate. An answer
naming a host, an IP or a CVE is making a claim about their network, and
the analyst has no way to tell a claim drawn from the evidence from one
the model produced because it sounded right.

Every checkable claim now either cites the record it came from or is
listed as citing nothing. A citation is a ledger coordinate —
ledger:<run>#<seq> — or an alert id: things an analyst can open. Pointing
one at a paragraph of page context would be unfalsifiable, so context
without an identifier is context for the model and nothing more.

What counts as checkable is imported from app.confidence.groundedness
rather than re-implemented, for the reason aisoc_benchmark.replay records
about its own reuse: a second definition would drift from the first and
the two numbers would stop being comparable while still looking like they
were. A test asserts the two are literally the same function object.

Three outcomes, not two. "Asserted nothing concrete" and "asserted things
and supported all of them" get different labels, or the label goes silent
on exactly the prose answers where it should be. And an answer with one
supported claim and one invented one reads "partially uncited" rather
than "cited", which would be the worst possible rounding.

The ungrounded answer is returned, not suppressed. Hiding the
unsupported half would show the analyst a different answer than the model
gave, edited by something that cannot reliably tell which half was wrong.
The console appends the warning above the reply for the same reason.

A template reply is not graded: it asserts nothing about this estate, and
labelling generic guidance "uncited" would put a warning where there is
no claim to warn about.

Also corrects a stale comment that called the conversation store
"in-memory (demo: resets on restart)" long after it took both a tenant
and a database — the kind of thing that makes a reader distrust the
comments that are true.

15 tests.

Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com>

* feat(eval): grade the shipped model, and refuse the numbers that flatter (parity 3.2, 3.4)

3.2 asks for verdict accuracy, per-class precision and recall, malicious
recall with a confidence interval, and false-negative counts. The scoring
for every one of those already existed in aisoc_benchmark.replay. What
did not exist is the thing standing in front of it, and building that
turned up the finding.

Every labelled corpus in this repository is entirely malicious by
construction. synthetic_incidents.json and adversary_incidents.json are
200 incidents each and every one is a real attack; response_class says
which action to take, not whether the finding was true. There is no
benign case and no false positive anywhere in eval_data/.

Score an agent against that and an agent answering "true positive" to
everything, without reading anything, posts 100% accuracy and 100%
malicious recall. That is the exact mirror of the failure replay.py
already guards against at the other end, where it withholds headline
accuracy below 30 malicious cases because 98% on a corpus of three is
misleading in the direction that sells.

So score_replay_set.py refuses: no labels, one class, or a minority class
under 5% and it stops and names the counts. A test asserts this tree's
own two corpora are refused, because that is the finding rather than a
bug to route around. There is no --force.

benchmark.md now carries the table with every accuracy cell reading "not
measured" and the reason, rather than a number nobody should trust.
Filling it needs a customer replaying their own closed findings, or a
balanced corpus built here.

What *is* measurable got measured: live-agent-eval.yml is now a matrix
over qwen2.5:0.5b and llama3.2:3b-instruct-q4_K_M, the model
docker-compose.yml actually pulls. The small one stays because the floor
in live_agent_floor.json was measured on it and removing it would orphan
the floor. fail-fast is off, because one model failing is a result about
that model and cancelling the other throws away the comparison.

3.4 is compare_eval_runs.py, and most of its work is refusing:

- an axis measured before and not after reports "not comparable", not a
  regression. The arithmetic says 0.62 - 0 = -0.62 and claims the agent
  got much worse when nobody asked it.
- two runs over different datasets are refused outright, because that
  delta measures the corpus.
- a mean whose support changed materially carries both counts: a
  precision of 1.00 over two predictions and over two hundred are the
  same number and different facts.
- latency is reported and never graded, because it measures the machine.

It is wired into live-agent-eval.yml against the previous successful run,
so the delta is published rather than available. With no previous report
it says so instead of diffing against a baseline of zeros.

Three gates caught things while building this, all fixed rather than
exempted: check_gate_contract refused an exception claiming the wrong
disposition and then one naming a script it had not classified;
check_gate_coverage refused the comparator until a workflow reached it;
and check_ledger_replay_contract refused the 3.7 bundle route because
nothing in the console called it. That last one is now a download control
on the investigation timeline, writing the server's bytes to disk
unmodified so the signature still verifies.

33 new tests, 351 script tests green.

Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com>

* docs: publish the four new capabilities, and fix three stale counts

The README gains one paragraph for the two capabilities a reader can
see — the copilot's citations and the signed evidence bundle — and the
detail goes to docs/architecture/evidence-bundles.md, because the 250-line
cap is binding and new content has to displace something true rather
than be squeezed in. Four paragraphs were tightened to make room; every
fact in them survives.

benchmark.md gains the section that matters more than a number: why
verdict accuracy is *not measured* here. Every labelled corpus in this
repository is entirely malicious by construction, so an agent answering
"true positive" to everything would post 100%. The table reads "not
measured" in every accuracy cell with the reason beside it, and the
hosted column says no provider has ever been exercised rather than
showing a zero that would read as the model getting everything wrong.

Seven claim-matrix rows, all GATED, naming the gate that proves each.

Three stale figures the gates caught, each fixed at the source:

- ROADMAP.md claimed 278 matrix rows against a real 285 — and carried
  the same paragraph **four times**, byte-identical and adjacent, which
  was already true on main. Collapsed to one.
- apps/docs/docs/compliance/evidence-pack.md claimed 278 GATED.
- The matrix's own summary block had drifted from its parser. It is now
  recomputed by running the gate rather than by editing a number, and
  says so, because a count copied into prose goes stale silently.

The matrix also demonstrated its documented trap while being edited:
seven rows appended past the Summary heading left the parser stopping at
the first blank line, so it reported 278 while the file held 285 and
nothing failed. The rows are inside the table now and the summary is
derived from the gate's own output.

No tool or assistant attribution anywhere: check_attribution passes
tree-wide and across every commit on this branch.

Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com>

* fix(ci): install the api lockfile for the bundle suite, allowlist its fixture key

Two failures on this branch, both mine.

The evidence-bundle live suite drives the **API** service through a real
ASGI client, so it pulls in that service's import chain rather than the
agents one the job already installed, and died on `bcrypt` reached
through app.core.security. The fix is the one the step's own comment
already argues for: install from the service's lockfile rather than
adding the missing name to a hand-curated list, which only works until
the next import.

The secret scan flagged the suite's signing-key fixture. It is a literal
the tests sign with so they can then prove a *different* key fails to
verify; it authenticates nothing and exists in no deployment, so it is
allowlisted with that reason beside it.

Worth recording how that was verified, because the first answer was
wrong. The gitleaks on this machine is 8.30.1 and CI pins 8.21.2, and
the two disagree: 8.30 reports 11 findings in tracked files that 8.21
does not, none of them touched by this branch. Checking against the local
binary would have sent me after pre-existing files for no reason.
Against the pinned one the tree is clean — 0 findings in tracked files,
with the remainder being __pycache__ and apps/docs/build artefacts that
do not exist in a fresh checkout.

Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com>

* fix(readme): a reflow split a gated phrase across a line break

generate_corpus_stats.py pins the sentence "fusion runs 2603 executable
detection rules" so the figure cannot drift from the compiled ruleset.
Trimming the README to its 250-line cap rewrapped that line and left
"detection" and "rules" on opposite sides of a newline, so the pattern
stopped matching — the count was right and the gate still red, correctly.

Rewrapped to keep the phrase intact and folded a line elsewhere, away
from anything gated, to stay at 250.

Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com>

---------

Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com>
2026-10-02 21:32:26 -07:00

320 lines
12 KiB
Python

#!/usr/bin/env python3
"""Publish the delta between two eval runs, and refuse the ones that lie.
Parity 3.4, which defers to gap-closure 6.4: *"replay before and after
... and publish the delta."*
Why a delta needs its own tool
-------------------------------
Subtracting two numbers is easy. Subtracting them *honestly* is where
this goes wrong, and three of the four ways it goes wrong produce a
plausible figure rather than an error.
**"Not measured" is not zero, and a delta involving it is not a delta.**
If the before run measured malicious recall and the after run did not,
the arithmetic says `0.62 - 0 = -0.62` and the report says the agent got
much worse. It did not; nobody asked it. Every axis here reports one of
four states — improved, regressed, unchanged, or *not comparable* — and
the fourth exists because the first three would otherwise absorb it.
**A mean without its denominator is not comparable.** A precision of
1.00 over two predictions and a precision of 1.00 over two hundred are
the same number and different facts. When the support behind an axis
changes materially, the delta is reported with both counts rather than
as a bare difference.
**Two runs on different corpora are not a before and after.** A delta
between a run over 200 incidents and one over 10 measures the corpus,
not the change. The dataset identity is compared first and a mismatch is
refused outright.
**A wall-clock number is not a property of the change.** Latency differs
between two runs on one host, let alone two hosts, so it is excluded
from the verdict and reported separately, labelled as measuring the
machine.
What "regressed" means
----------------------
Any axis moving down by more than :data:`NOISE_FLOOR`. The floor is not
a tolerance for sloppiness — it exists because a bootstrap CI and a
sampled corpus both move slightly between runs, and a tool that called
every 0.001 drift a regression would be ignored within a week.
"""
from __future__ import annotations
import argparse
import json
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import Any
sys.path.insert(0, str(Path(__file__).resolve().parent))
from gate_toolkit import self_test_if_requested # noqa: E402
self_test_if_requested(__file__)
#: Below this, a move is reported as unchanged. See the module docstring.
NOISE_FLOOR = 0.005
#: Axes whose *higher is better*. Everything else is reported without a
#: direction rather than guessed at, because a tool that assumed the
#: wrong direction would call an improvement a regression.
HIGHER_IS_BETTER = (
"accuracy",
"malicious_recall",
"groundedness",
"mitre_accuracy",
"alert_reduction",
"investigation_completeness",
"response_quality",
)
#: Measures the host, not the agent. Reported, never graded.
HOST_AXES = ("mean_latency_ms", "p95_latency_ms")
#: Fields that identify the run rather than measure it. Excluded so the
#: dataset name does not become an axis with no delta.
_IDENTITY_KEYS = frozenset({"dataset", "corpus", "dataset_id", "model", "commit", "date", "mode"})
VERDICT_IMPROVED = "improved"
VERDICT_REGRESSED = "regressed"
VERDICT_UNCHANGED = "unchanged"
VERDICT_NOT_COMPARABLE = "not comparable"
class ComparisonRefused(RuntimeError):
"""The two runs cannot honestly be compared. Carries why."""
@dataclass(frozen=True)
class AxisDelta:
axis: str
before: float | None
after: float | None
delta: float | None
verdict: str
note: str = ""
before_n: int | None = None
after_n: int | None = None
def _number(value: Any) -> float | None:
"""A float, or None for anything that is not a measurement.
`None`, `"not measured"` and a missing key all mean the same thing
and all become `None`. A string that happens to parse is still a
number; a bool is not, because `True` would silently become 1.0.
"""
if value is None or isinstance(value, bool):
return None
if isinstance(value, (int, float)):
return float(value)
if isinstance(value, str):
try:
return float(value)
except ValueError:
return None
return None
def _axis_values(report: dict[str, Any]) -> dict[str, tuple[float | None, int | None]]:
"""Flatten a report into axis -> (value, support).
Handles both shapes this tree produces: a flat `{"accuracy": 0.9}`
and the nested `{"groundedness": {"mean": 0.8, "scored_incidents": 20}}`
the live-agent harness writes.
"""
out: dict[str, tuple[float | None, int | None]] = {}
for key, value in (report or {}).items():
if isinstance(value, dict):
number = _number(value.get("mean", value.get("value", value.get("score"))))
support = value.get("scored_incidents", value.get("count", value.get("support")))
out[key] = (number, support if isinstance(support, int) else None)
elif key not in _IDENTITY_KEYS:
# Recorded even when it is not a number, so a key that
# stopped being a measurement shows up as "not comparable"
# rather than vanishing. Dropping it is how a report loses an
# axis without anyone noticing which one went quiet.
out[key] = (_number(value), None)
return out
def _dataset_identity(report: dict[str, Any]) -> str | None:
for key in ("dataset", "corpus", "dataset_id"):
value = report.get(key)
if isinstance(value, str) and value:
return value
return None
def compare(before: dict[str, Any], after: dict[str, Any]) -> list[AxisDelta]:
"""Every axis in either run, with a verdict that can say "no".
Axes present in only one run are reported as not comparable rather
than dropped: an axis that stopped being measured is a change worth
seeing, and silently omitting it is how a report shrinks without
anyone noticing.
"""
before_id, after_id = _dataset_identity(before), _dataset_identity(after)
if before_id and after_id and before_id != after_id:
raise ComparisonRefused(
f"these runs used different datasets ({before_id!r} and {after_id!r}), so a delta "
"between them measures the corpus rather than the change"
)
left, right = _axis_values(before), _axis_values(after)
deltas: list[AxisDelta] = []
for axis in sorted(set(left) | set(right)):
before_value, before_n = left.get(axis, (None, None))
after_value, after_n = right.get(axis, (None, None))
if axis in HOST_AXES:
deltas.append(
AxisDelta(
axis=axis,
before=before_value,
after=after_value,
delta=None,
verdict=VERDICT_NOT_COMPARABLE,
note="measures the machine the run happened on, not the agent",
before_n=before_n,
after_n=after_n,
)
)
continue
if before_value is None or after_value is None:
# The case the arithmetic gets wrong. Saying "not measured"
# minus 0.62 is a regression would be a confident lie.
which = (
"the before run did not measure it"
if before_value is None and after_value is not None
else "the after run did not measure it"
if after_value is None and before_value is not None
else "neither run measured it"
)
deltas.append(
AxisDelta(
axis=axis,
before=before_value,
after=after_value,
delta=None,
verdict=VERDICT_NOT_COMPARABLE,
note=f"{which}; absent is not zero, so there is no delta to report",
before_n=before_n,
after_n=after_n,
)
)
continue
raw = after_value - before_value
if abs(raw) <= NOISE_FLOOR:
verdict = VERDICT_UNCHANGED
elif axis in HIGHER_IS_BETTER:
verdict = VERDICT_IMPROVED if raw > 0 else VERDICT_REGRESSED
else:
verdict = VERDICT_NOT_COMPARABLE
note = ""
if axis not in HIGHER_IS_BETTER and verdict == VERDICT_NOT_COMPARABLE:
note = "no known direction for this axis, so the move is reported without a verdict"
elif before_n is not None and after_n is not None and before_n and after_n:
ratio = after_n / before_n
if ratio < 0.5 or ratio > 2.0:
note = (
f"support changed from {before_n} to {after_n}; a mean over a materially "
"different number of cases is a different fact, not only a different number"
)
deltas.append(
AxisDelta(
axis=axis,
before=before_value,
after=after_value,
delta=round(raw, 6),
verdict=verdict,
note=note,
before_n=before_n,
after_n=after_n,
)
)
return deltas
def _fmt(value: float | None) -> str:
return "not measured" if value is None else f"{value:.4f}"
def format_delta_report(deltas: list[AxisDelta], *, before_label: str, after_label: str) -> str:
"""Markdown, deterministic, with "not measured" spelled out.
No timestamps and no host names: a report that has to reproduce for
a reviewer cannot carry either.
"""
lines = [
"# Before and after",
"",
f"- Before: `{before_label}`",
f"- After: `{after_label}`",
"",
"| Axis | Before | After | Delta | Verdict |",
"|---|---|---|---|---|",
]
for d in deltas:
delta = "—" if d.delta is None else f"{d.delta:+.4f}"
lines.append(f"| `{d.axis}` | {_fmt(d.before)} | {_fmt(d.after)} | {delta} | {d.verdict} |")
notes = [d for d in deltas if d.note]
if notes:
lines += ["", "## Why some axes have no delta", ""]
lines += [f"- **`{d.axis}`** — {d.note}" for d in notes]
regressed = [d.axis for d in deltas if d.verdict == VERDICT_REGRESSED]
lines += ["", f"**Regressions: {len(regressed)}**" + (f" — {', '.join(regressed)}" if regressed else "")]
return "\n".join(lines) + "\n"
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--before", required=True, type=Path)
parser.add_argument("--after", required=True, type=Path)
parser.add_argument("--out", type=Path, help="write the Markdown report here")
parser.add_argument(
"--fail-on-regression",
action="store_true",
help="exit non-zero when any graded axis moved down past the noise floor",
)
args = parser.parse_args()
before = json.loads(args.before.read_text(encoding="utf-8"))
after = json.loads(args.after.read_text(encoding="utf-8"))
try:
deltas = compare(before, after)
except ComparisonRefused as exc:
print(f"compare_eval_runs: REFUSED — {exc}", file=sys.stderr)
return 2
report = format_delta_report(deltas, before_label=args.before.name, after_label=args.after.name)
if args.out:
args.out.write_text(report, encoding="utf-8")
print(report)
regressed = [d for d in deltas if d.verdict == VERDICT_REGRESSED]
if regressed and args.fail_on_regression:
print(
f"compare_eval_runs: {len(regressed)} axis/axes regressed: " + ", ".join(d.axis for d in regressed),
file=sys.stderr,
)
return 1
return 0
if __name__ == "__main__":
sys.exit(main())