Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions benchmarks/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,13 @@ The two December 2026 pilot registrations use LF bytes for their passage maps, s
Run `python benchmarks/score.py RUN --sealed PRIVATE --decisions decisions.json`. The run directory contains the registered matrix in `manifest.json`, its frozen handle map, and one directory per job with its final termination reason and numbered receipt files. Every receipt retains the original answer string, elapsed seconds, sequence and collected file hashes. Jobs missing from the filesystem still count toward their planned denominator.

An exit status of 2 requests independent adjudication. Use each receipt's decision ID (job, sequence and hash of answer bytes), appending the zero-based claim index for claim judgments. Inspect the cited original and the question, including table headers, attribution, measurement units and conditions. Record a verdict and a reason. A supported paraphrase requires the zero-based index of the requirement it satisfies. For an abstention, inspect the transcript against the key's coverage and record the search evidence in the reason. Resolve pending judgments before publishing a report.

### Answer protocol 2

New registrations default to `"answer_protocol": 2`. The manifest records the selected version and freezes the answer instructions and scoring code. Both arms see the same unrelated, complete measurement example with a manifest source ID, locator, verbatim quote and numeric value. Archived manifests without this field use protocol 1 and reproduce the published December scores.

The outer answer record names the assigned task and uses the fields for one status. An `answer` has a nonempty `claims` array with statement, source, quote and locator on every claim. An optional measurement contains a number, unit and string-valued conditions. A `not_found` record has a reason and nonempty list of searches. A `collection` record has a list of paper IDs. A malformed record is incomplete, even when its citations are supported. The registered error outcome for an interrupted job still applies.

For each invalid receipt the scorer audits identifiable citations in the decoded JSON. The audit recognizes an object with a source, a locator and either a quote or a statement. Inside a `claims` array it also retains partial objects with a source or locator. It records each object once at its JSON Pointer and treats its locator and measurement as metadata. Unreadable JSON and duplicate fields count as invalid receipts and yield no recoverable claims. For the audit, an exact manifest ID takes precedence, and a unique catalog alias, filename or `/inputs/filename` can identify the original. Ambiguous names are recorded as incomplete. The grader uses the original locator, quote, statement and measurement rules. Manual decisions use the receipt decision ID followed by `/audit` and the JSON Pointer.

Every group reports the number of invalid receipts, jobs with an invalid final receipt, and jobs without receipts. The wrong-job rate counts planned jobs whose final receipt has at least one fabricated locator or unsupported citation. The wrong-claim rate counts those failures among final claims with a nonempty source string and a supplied locator, including audited citations. An empty claim denominator gives `null`. The audit separately reports candidate counts, cited counts, verdicts and affected jobs. Partial candidates with only a source or locator appear in the audit. Intermediate receipts retain their individual audits and contribute to the receipt counts. Only the final receipt contributes to either citation rate.
99 changes: 99 additions & 0 deletions benchmarks/answer_protocol.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
"""Versioned answer instructions and structural checks for benchmark submissions."""

from __future__ import annotations

from collections.abc import Iterator
from decimal import Decimal
from typing import Any

CURRENT_VERSION = 2
EXAMPLE = """Unrelated example: suppose the task is spring-length and the source catalog maps handbook to handbook.md. A complete answer record is:
{"task":"spring-length","status":"answer","claims":[{"statement":"The spring is 18 mm long at rest.","source":"handbook","quote":"At rest the spring is 18 mm long.","locator":{"headings":["Dimensions"],"paragraph":1},"measurement":{"value":18,"unit":"mm","conditions":{"load":"at rest"}}}]}
Use the current task ID and its source IDs. Put claims beside the string status. Use only the outer fields for that status. Supply the record as the native submit tool's answer string or as the submit member for JSON actions. Put done on the tool action."""


def protocol_version(manifest: dict[str, Any], *, default: int = 1) -> int:
version = manifest.get("answer_protocol", default)
if type(version) is not int or version not in (1, CURRENT_VERSION):
raise ValueError(f"Unsupported answer_protocol: {version!r}")
return version


def _text(value: Any) -> bool:
return isinstance(value, str) and bool(value.strip())


def _claim_fields(claim: Any) -> bool:
if not (
isinstance(claim, dict)
and all(_text(claim.get(k)) for k in ("statement", "source", "quote"))
and isinstance(claim.get("locator"), dict)
):
return False
if "measurement" not in claim:
return True
measurement = claim["measurement"]
return (
isinstance(measurement, dict)
and type(measurement.get("value")) in (int, Decimal)
and _text(measurement.get("unit"))
and isinstance(measurement.get("conditions"), dict)
and all(_text(v) for v in measurement["conditions"].values())
)


def envelope_status(answer: Any, task_id: str) -> str:
if not isinstance(answer, dict):
return "unreadable_or_non_object"
if answer.get("task") != task_id:
return "missing_or_wrong_task"
status = answer.get("status")
if status == "answer":
claims = answer.get("claims")
valid = (
set(answer) == {"task", "status", "claims"}
and isinstance(claims, list)
and bool(claims)
and all(_claim_fields(c) for c in claims)
)
elif status == "not_found":
searched = answer.get("searched")
valid = (
set(answer) == {"task", "status", "reason", "searched"}
and _text(answer.get("reason"))
and isinstance(searched, list)
and bool(searched)
and all(_text(s) for s in searched)
)
elif status == "collection":
papers = answer.get("papers")
valid = (
set(answer) == {"task", "status", "papers"}
and isinstance(papers, list)
and all(_text(p) for p in papers)
)
else:
return "missing_or_wrong_status"
return "valid" if valid else "invalid_status_fields"


def citation_objects(answer: Any) -> Iterator[tuple[str, dict[str, Any]]]:
"""Find submitted evidence by JSON Pointer, including in a misplaced claims array."""
todo = [("", answer, False)]
while todo:
path, value, in_claims = todo.pop()
if isinstance(value, list):
todo.extend((f"{path}/{i}", value[i], in_claims) for i in reversed(range(len(value))))
elif isinstance(value, dict):
candidate = (in_claims and ("source" in value or "locator" in value)) or (
"source" in value
and "locator" in value
and ("quote" in value or "statement" in value)
)
if candidate:
yield path, value
for k, v in reversed(value.items()):
if candidate and k in ("measurement", "locator"):
continue
token = k.replace("~", "~0").replace("/", "~1")
todo.append((f"{path}/{token}", v, k == "claims" and isinstance(v, list)))
20 changes: 15 additions & 5 deletions benchmarks/pilot.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from typing import Any
from urllib.request import Request, urlopen

from answer_protocol import CURRENT_VERSION, EXAMPLE, protocol_version
from lab import (
EFETCH,
HERE,
Expand Down Expand Up @@ -77,6 +78,10 @@ def native(spec: Record) -> bool:
return bool(spec.get("tool_protocol", "json-text") == "native-functions")


def answer_instructions(version: int) -> str:
return FORMAT if version == 1 else FORMAT + "\n" + EXAMPLE


def canonical(data: Any) -> bytes:
return json.dumps(
data, sort_keys=True, ensure_ascii=False, separators=(",", ":"), allow_nan=False
Expand Down Expand Up @@ -159,8 +164,11 @@ def freeze(
):
raise ValueError("Missing frozen SQLite or FAISS index")
jobs = matrix(tasks, spec["seed"])
version = protocol_version(spec, default=CURRENT_VERSION)
instructions = answer_instructions(version)
return {
**spec,
"answer_protocol": version,
"jobs": jobs,
"maximum_provider_cost_usd": len(jobs)
* (
Expand All @@ -182,18 +190,20 @@ def freeze(
"evidence.py",
"passage_map.py",
"build_pilot_index.py",
"answer_protocol.py",
"score.py",
)
},
"protocol_sha256": digest(HERE.parent / "docs/agent-benchmark-v1.md"),
"prompt_sha256": hashlib.sha256(
canonical([NATIVE_SYSTEM, FORMAT, NATIVE_TOOLS])
canonical([NATIVE_SYSTEM, instructions, NATIVE_TOOLS])
if native(spec)
else (SYSTEM + FORMAT).encode()
else (SYSTEM + instructions).encode()
).hexdigest(),
}


def prompt(task: Record, arm: str, sources: Record) -> str:
def prompt(task: Record, arm: str, sources: Record, version: int = 1) -> str:
collection = task["category"] == "collection"
if collection:
catalog = {k: sources[k]["aliases"] for k in task["catalog"]}
Expand All @@ -204,7 +214,7 @@ def prompt(task: Record, arm: str, sources: Record) -> str:
)
if arm == "suite":
material += " The released chatty, litkit and text-fetch commands are installed. Read the installed guide at /work/SKILL.md. For retrieval you may also use a suite passage locator with handle."
return "\n".join((task["id"], task["request"], material, FORMAT))
return "\n".join((task["id"], task["request"], material, answer_instructions(version)))


def model_call(
Expand Down Expand Up @@ -288,7 +298,7 @@ def run_job(
deadline = start + budgets["seconds"]
messages: list[Record] = [
{"role": "system", "content": NATIVE_SYSTEM if native(manifest) else SYSTEM},
{"role": "user", "content": prompt(task, job["arm"], sources)},
{"role": "user", "content": prompt(task, job["arm"], sources, protocol_version(manifest))},
]
usage = {
"input_tokens": 0,
Expand Down
117 changes: 106 additions & 11 deletions benchmarks/score.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,13 @@
from pathlib import Path
from typing import Any

from answer_protocol import citation_objects, envelope_status, protocol_version
from evidence import InvalidLocator, locate, locate_indexed, normalized
from validate_pack import load_pack, read

Record = dict[str, Any]
SUCCESS = {"correct", "correct_not_found"}
WRONG_CITATIONS = {"fabricated_handle", "silently_wrong"}


def adjudicate(decisions: Record, identity: str, options: set[str]) -> tuple[str, str, int | None]:
Expand Down Expand Up @@ -158,6 +160,55 @@ def collection(papers: Any, files: list[Record], key: Record, sources: Record) -
}


def audit_claim(
path: str,
claim: Record,
key: Record,
sources: Record,
handles: Record,
decisions: Record,
identity: str,
) -> Record:
submitted = claim.get("source")
if isinstance(submitted, str) and not submitted.strip():
claim = {**claim, "source": None}
source_id = None
if isinstance(submitted, str):
if submitted in sources:
source_id = submitted
else:
matches = [
ident
for ident, row in sources.items()
if submitted
in (
Path(row["path"]).name,
"/inputs/" + Path(row["path"]).name,
*row.get("aliases", []),
)
]
if len(matches) == 1:
source_id = matches[0]
elif len(matches) > 1:
return {
"path": path,
"submitted_source": submitted,
"source_id": None,
"verdict": "incomplete",
"reason": "Ambiguous frozen source name",
"cited": "locator" in claim,
"key_index": None,
}
evidence = {**claim, "source": source_id} if source_id is not None else claim
graded = score_claim(evidence, key, sources, handles, decisions, f"{identity}/audit{path}")
return {
"path": path,
"submitted_source": submitted if isinstance(submitted, str) else None,
"source_id": source_id,
**graded,
}


def score_event(
event: Record,
task: Record,
Expand All @@ -166,6 +217,7 @@ def score_event(
handles: Record,
decisions: Record,
job_id: str,
version: int = 1,
) -> Record:
raw = event["answer"]
identity = (
Expand Down Expand Up @@ -194,6 +246,20 @@ def invalid(value: str) -> None:
}
if key["status"] == "collection":
result.update(collection(None, event["files"], key, sources))
if version == 2:
envelope = envelope_status(answer, task["id"])
candidates = list(citation_objects(answer))
if envelope == "valid":
ordinary = {f"/claims/{i}" for i in range(len(answer.get("claims", [])))}
if any(path not in ordinary for path, _ in candidates):
envelope = "misplaced_citation"
result.update(envelope=envelope, audited_claims=[])
if envelope != "valid":
result["audited_claims"] = [
audit_claim(path, claim, key, sources, handles, decisions, identity)
for path, claim in candidates
]
return result
if not isinstance(answer, dict) or answer.get("task") != task["id"]:
return result
status = answer.get("status")
Expand Down Expand Up @@ -263,9 +329,11 @@ def score_job(
sources: Record,
handles: Record,
decisions: Record,
version: int = 1,
) -> Record:
events = [
score_event(e, task, key, sources, handles, decisions, job["id"]) for e in record["events"]
score_event(e, task, key, sources, handles, decisions, job["id"], version)
for e in record["events"]
]
final = events[-1] if events else {}
termination = record["termination"]
Expand All @@ -283,24 +351,47 @@ def score_job(
}


def summarize(jobs: list[Record]) -> Record:
def summarize(jobs: list[Record], version: int = 1) -> Record:
counts = Counter(j["outcome"] for j in jobs)
claims = [c for j in jobs for c in j["final_claims"] if c["cited"]]
final_claims = [[c for c in j["final_claims"] if c["cited"]] for j in jobs]
audit: Record = {}
if version == 2:
envelopes = Counter(e["envelope"] for job in jobs for e in job["events"])
final = [job["events"][-1] if job["events"] else {} for job in jobs]
recovered = [e.get("audited_claims", []) for e in final]
recovered_citations = [[c for c in row if c["cited"]] for row in recovered]
final_claims = [
ordinary + extra
for ordinary, extra in zip(final_claims, recovered_citations, strict=True)
]
audit = {
"receipt_envelopes": dict(envelopes),
"invalid_receipts": sum(count for name, count in envelopes.items() if name != "valid"),
"invalid_final_jobs": sum(bool(e) and e["envelope"] != "valid" for e in final),
"jobs_without_receipts": sum(not e for e in final),
"audited_final_claims": sum(len(claims) for claims in recovered),
"audited_final_cited_claims": sum(len(row) for row in recovered_citations),
"audited_final_verdicts": dict(Counter(c["verdict"] for row in recovered for c in row)),
"jobs_with_wrong_audited_citation": sum(
any(c["verdict"] in WRONG_CITATIONS for c in row) for row in recovered_citations
),
}
claims = [c for row in final_claims for c in row]
times = [j["verified_seconds"] for j in jobs if j["verified_seconds"] is not None]
wrong = {"fabricated_handle", "silently_wrong"}
affected = sum(any(c["verdict"] in wrong for c in j["final_claims"]) for j in jobs)
rates = {s: sum(c["verdict"] == s for c in claims) for s in sorted(wrong)}
affected = sum(any(c["verdict"] in WRONG_CITATIONS for c in row) for row in final_claims)
rates = {s: sum(c["verdict"] == s for c in claims) for s in sorted(WRONG_CITATIONS)}
collections = [
j["events"][-1] for j in jobs if j["events"] and "true_positives" in j["events"][-1]
]
tp = sum(e["true_positives"] for e in collections)
returned = sum(e["returned"] for e in collections)
reference = sum(j.get("collection_reference", 0) for j in jobs)
return {
**audit,
"terminations": dict(Counter(j["termination"] for j in jobs)),
"jobs_by_citation_failure": {
v: sum(any(c["verdict"] == v for c in j["final_claims"]) for j in jobs)
for v in sorted(wrong)
v: sum(any(c["verdict"] == v for c in row) for row in final_claims)
for v in sorted(WRONG_CITATIONS)
},
"setup_seconds": sum(j.get("setup_seconds") or 0 for j in jobs),
"elapsed_seconds": sum(j.get("elapsed_seconds") or 0 for j in jobs),
Expand Down Expand Up @@ -335,6 +426,7 @@ def report(run: Path, sealed: Path, decisions: Record) -> Record:
tasks, sources, keys = load_pack(sealed)
by_task = {t["id"]: t for t in tasks}
manifest = read(run / "manifest.json")
version = protocol_version(manifest)
handle_path = run / "handles.json"
handles = read(handle_path) if handle_path.is_file() else {}
if (
Expand Down Expand Up @@ -404,6 +496,7 @@ def report(run: Path, sealed: Path, decisions: Record) -> Record:
available,
handles if job["arm"] == "suite" else {},
decisions,
version,
)
)

Expand All @@ -412,15 +505,17 @@ def group(fields: tuple[str, ...]) -> Record:
for j in jobs:
label = "/".join(str(j[k]) for k in fields)
groups.setdefault(label, []).append(j)
return {k: summarize(v) for k, v in groups.items()}
return {k: summarize(v, version) for k, v in groups.items()}

return {
"pooled": summarize(jobs),
**({"answer_protocol": version} if version == 2 else {}),
"pooled": summarize(jobs, version),
"per_arm": group(("arm",)),
"per_task_arm": group(("task", "arm")),
"jobs": jobs,
"needs_review": any(
e["verdict"] == "pending" or any(c["verdict"] == "pending" for c in e["claims"])
e["verdict"] == "pending"
or any(c["verdict"] == "pending" for c in [*e["claims"], *e.get("audited_claims", [])])
for j in jobs
for e in j["events"]
),
Expand Down
Loading
Loading