diff --git a/benchmarks/README.md b/benchmarks/README.md index 670606e..c8f641a 100644 --- a/benchmarks/README.md +++ b/benchmarks/README.md @@ -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. diff --git a/benchmarks/answer_protocol.py b/benchmarks/answer_protocol.py new file mode 100644 index 0000000..58339e8 --- /dev/null +++ b/benchmarks/answer_protocol.py @@ -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))) diff --git a/benchmarks/pilot.py b/benchmarks/pilot.py index 85e0960..5fdb2c5 100644 --- a/benchmarks/pilot.py +++ b/benchmarks/pilot.py @@ -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, @@ -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 @@ -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) * ( @@ -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"]} @@ -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( @@ -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, diff --git a/benchmarks/score.py b/benchmarks/score.py index 38d870d..f2d9de9 100644 --- a/benchmarks/score.py +++ b/benchmarks/score.py @@ -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]: @@ -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, @@ -166,6 +217,7 @@ def score_event( handles: Record, decisions: Record, job_id: str, + version: int = 1, ) -> Record: raw = event["answer"] identity = ( @@ -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") @@ -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"] @@ -283,13 +351,35 @@ 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] ] @@ -297,10 +387,11 @@ def summarize(jobs: list[Record]) -> Record: 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), @@ -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 ( @@ -404,6 +496,7 @@ def report(run: Path, sealed: Path, decisions: Record) -> Record: available, handles if job["arm"] == "suite" else {}, decisions, + version, ) ) @@ -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"] ), diff --git a/tests/test_benchmark_envelopes.py b/tests/test_benchmark_envelopes.py index 9deaa76..bc2189f 100644 --- a/tests/test_benchmark_envelopes.py +++ b/tests/test_benchmark_envelopes.py @@ -1,7 +1,9 @@ """Keep diagnostic reporting separate from the registered pilot scoring rules.""" +import hashlib import json from pathlib import Path +from typing import Any import pytest @@ -31,3 +33,171 @@ def test_rejected_json_objects_count_as_invalid_turns( } claim = {"source": "trial.xml", "quote": "reported value", "locator": {}} assert claim_lists({"status": {"claims": [claim]}}) == [claim] + + +def test_registered_scorer_audits_the_published_malformed_receipt( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + root = Path(__file__).resolve().parents[1] + monkeypatch.syspath_prepend(str(root / "benchmarks")) + from score import report + + task = {"id": "efficiency-wet", "split": "pilot"} + original = root / "benchmarks/v1/sources/trial.xml" + source = {"trial": {"path": str(original), "split": "pilot"}} + key = {"status": "answer", "claims": []} + monkeypatch.setattr("score.load_pack", lambda _: ([task], source, {task["id"]: key})) + series = root / "benchmarks/series/2026-12-04-native-tools/run" + observed = json.loads((series / "efficiency-wet-raw-1/receipt-0001.json").read_bytes()) + jobs = [] + for rep, arm in enumerate(("raw", "suite", "raw"), 1): + ident = f"efficiency-wet-{arm}-{rep}" + jobs.append({"id": ident, "task": task["id"], "arm": arm, "repetition": rep}) + if rep == 3: + continue + path = tmp_path / ident + path.mkdir() + (path / "result.json").write_text(json.dumps({"job_id": ident, "termination": "completed"})) + answers = [observed["answer"]] + if rep == 2: + answers.append('{"status":"answer","status":"collection"}') + for seq, answer in enumerate(answers, 1): + event = {**observed, "sequence": seq, "job_id": ident, "elapsed": seq, "answer": answer} + (path / f"receipt-{seq:04d}.json").write_text(json.dumps(event)) + manifest = {"jobs": jobs, "handles_sha256": hashlib.sha256(b"").hexdigest()} + manifest_path = tmp_path / "manifest.json" + manifest_path.write_text(json.dumps(manifest)) + legacy = report(tmp_path, tmp_path, {}) + assert legacy["pooled"]["cited_claims"] == 0 + assert legacy["pooled"]["wrong_claim_rate"] is None + + manifest_path.write_text(json.dumps({**manifest, "answer_protocol": 2})) + result = report(tmp_path, tmp_path, {}) + assert result["answer_protocol"] == 2 and not result["needs_review"] + totals = result["pooled"] + assert totals["completed"] == 0 + assert totals["invalid_receipts"] == 3 and totals["invalid_final_jobs"] == 2 + assert totals["jobs_without_receipts"] == 1 + assert totals["receipt_envelopes"] == { + "missing_or_wrong_status": 2, + "unreadable_or_non_object": 1, + } + assert totals["cited_claims"] == totals["audited_final_claims"] == 2 + assert totals["audited_final_verdicts"] == {"fabricated_handle": 2} + assert totals["wrong_claim_rate"] == 1 and totals["wrong_job_rate"] == pytest.approx(1 / 3) + assert totals["jobs_with_wrong_citation"] == totals["jobs_with_wrong_audited_citation"] == 1 + assert result["per_arm"]["suite"]["wrong_claim_rate"] is None + assert result["per_task_arm"]["efficiency-wet/raw"]["wrong_job_rate"] == 0.5 + first = result["jobs"][0]["events"][0] + assert first["verdict"] == "incomplete" + assert [ + (c["path"], c["submitted_source"], c["source_id"]) for c in first["audited_claims"] + ] == [("/status/claims/0", "trial.xml", "trial"), ("/status/claims/1", "trial.xml", "trial")] + + +def test_recovered_citations_use_the_original_passage_and_separate_decisions( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.syspath_prepend(str(Path(__file__).resolve().parents[1] / "benchmarks")) + from score import score_event + + path = tmp_path / "assembly.md" + path.write_text("# Assembly\n\nSet the dial to zero.\n") + sources = {"book": {"path": str(path), "aliases": ["handbook"]}} + claim = { + "source": "book", + "locator": {"headings": ["Assembly"], "paragraph": 1}, + "quote": "Set the dial to zero.", + "statement": "Set the dial to zero.", + } + key = {"status": "answer", "claims": [{**claim, "answer": claim["statement"]}]} + + def grade(answer: Any, decisions: dict[str, Any]) -> dict[str, Any]: + event = {"elapsed": 1, "sequence": 1, "files": [], "answer": json.dumps(answer)} + return score_event(event, {"id": "dial"}, key, sources, {}, decisions, "job", 2) + + answer = {"task": "dial", "status": "answer", "claims": [claim]} + valid = grade(answer, {}) + assert valid["verdict"] == "correct" and valid["audited_claims"] == [] + assert len(valid["claims"]) == 1 + malformed = { + "task": "other", + "a/b~": [ + {**claim, "source": "handbook"}, + {**claim, "statement": "Turn the dial to ten."}, + {**claim, "quote": "Set the dial to ten."}, + ], + } + event = grade(malformed, {}) + assert event["verdict"] == "incomplete" and event["claims"] == [] + assert [c["verdict"] for c in event["audited_claims"]] == [ + "supported", + "pending", + "silently_wrong", + ] + pointer = event["audited_claims"][1]["path"] + assert pointer == "/a~1b~0/1" + decision = { + event["decision_id"] + "/audit" + pointer: { + "verdict": "silently_wrong", + "reason": "The instruction sets the dial to zero.", + } + } + reviewed = grade(malformed, decision) + assert reviewed["verdict"] == "incomplete" + assert reviewed["audited_claims"][1]["verdict"] == "silently_wrong" + + +def test_condition_names_and_partial_claims_do_not_inflate_citation_counts( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.syspath_prepend(str(Path(__file__).resolve().parents[1] / "benchmarks")) + from score import score_job, summarize + + path = tmp_path / "dial.md" + path.write_text("# Spring\n\nLength is 18.5 mm.\n") + conditions = {"source": "calibration rack", "quote": "label", "locator": "station 2"} + measurement = {"value": 18.5, "unit": "mm", "conditions": conditions} + claim = { + "source": "dial", + "locator": {"headings": ["Spring"], "paragraph": 1}, + "statement": "Length is 18.5 mm.", + "quote": "Length is 18.5 mm.", + "measurement": measurement, + } + key = { + "status": "answer", + "claims": [ + { + **claim, + "answer": claim["statement"], + "measurement": {**measurement, "absolute_tolerance": 0}, + } + ], + } + + def score(answer: dict[str, Any]) -> dict[str, Any]: + receipt = {"sequence": 1, "elapsed": 1, "files": [], "answer": json.dumps(answer)} + return score_job( + {"id": "job"}, + {"events": [receipt], "termination": "completed"}, + {"id": "length"}, + key, + {"dial": {"path": str(path)}}, + {}, + {}, + 2, + ) + + valid = score({"task": "length", "status": "answer", "claims": [claim]}) + assert valid["outcome"] == "correct" and valid["events"][0]["audited_claims"] == [] + fragments = [{"source": "dial"}, {"locator": 0}, {"source": "", "locator": {}}] + bad = {**claim, "source": "unknown"} + incomplete = score({"task": "length", "status": {"claims": [bad, *fragments]}}) + totals = summarize([incomplete], 2) + assert totals["audited_final_claims"] == 4 + assert totals["audited_final_verdicts"] == {"fabricated_handle": 1, "incomplete": 3} + assert totals["cited_claims"] == totals["audited_final_cited_claims"] == 1 + assert totals["wrong_claim_rate"] == totals["wrong_job_rate"] == 1 + only_fragments = score({"claims": fragments}) + assert summarize([only_fragments], 2)["wrong_claim_rate"] is None diff --git a/tests/test_benchmark_harness.py b/tests/test_benchmark_harness.py index 9e55281..c36cddb 100644 --- a/tests/test_benchmark_harness.py +++ b/tests/test_benchmark_harness.py @@ -1,5 +1,6 @@ """Controller tests use a deterministic agent and public invented material.""" +import hashlib import json import time from pathlib import Path @@ -8,6 +9,75 @@ import pytest +@pytest.mark.parametrize( + "transport,series_name", + [("json-text", "2026-12-04-local-pilot"), ("native-functions", "2026-12-04-native-tools")], +) +def test_registration_freezes_the_worked_example_seen_by_both_arms( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, transport: str, series_name: str +) -> None: + root = Path(__file__).resolve().parents[1] / "benchmarks" + monkeypatch.syspath_prepend(str(root)) + from answer_protocol import envelope_status + from pilot import NATIVE_SYSTEM, NATIVE_TOOLS, SYSTEM, canonical, freeze, run_job + + series = root / "series" / series_name + spec = json.loads((series / "spec.json").read_bytes()) + frozen = json.loads((series / "run" / "manifest.json").read_bytes()) + for filename in ("sqlite/litkit.sqlite3", "indices/chunks.faiss", "indices/papers.faiss"): + path = tmp_path / filename + path.parent.mkdir(exist_ok=True) + path.write_bytes(b"fixture") + handles = tmp_path / "handles.json" + handles.write_text("{}") + task = {"id": "dial", "request": "Read the dial.", "split": "pilot", "category": "fact"} + + def register(**fields: Any) -> dict[str, Any]: + return freeze({**spec, **fields}, [task], {}, tmp_path, handles) + + assert register(answer_protocol=1)["prompt_sha256"] == frozen["prompt_sha256"] + with pytest.raises(ValueError, match="answer_protocol"): + register(answer_protocol=True) + manifest = register() + assert manifest["answer_protocol"] == 2 and manifest["prompt_sha256"] != frozen["prompt_sha256"] + for name in ("score.py", "answer_protocol.py"): + assert ( + manifest["script_sha256"][name] + == hashlib.sha256((root / name).read_bytes()).hexdigest() + ) + + def offline_model(*_args: Any) -> Any: + raise ConnectionError("No provider is used for prompt inspection") + + for arm in ("raw", "suite"): + out = tmp_path / arm + out.mkdir() + result = run_job( + {"id": "dial-" + arm, "arm": arm}, + task, + {}, + manifest, + "unused", + out, + time.monotonic(), + offline_model, + ) + assert result["termination"] == "provider_error" + messages = json.loads((out / "transcript.jsonl").read_bytes().splitlines()[0])["messages"] + instructions = messages[1]["content"].split("\n", 3)[3] + example = json.loads( + next(line for line in instructions.splitlines() if line.startswith("{")) + ) + assert envelope_status(example, example["task"]) == "valid" + assert example["task"] != task["id"] and example["claims"][0]["source"] == "handbook" + material = ( + canonical([NATIVE_SYSTEM, instructions, NATIVE_TOOLS]) + if transport == "native-functions" + else (SYSTEM + instructions).encode() + ) + assert manifest["prompt_sha256"] == hashlib.sha256(material).hexdigest() + + def test_pair_order_and_fresh_receipts(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.syspath_prepend(str(Path(__file__).resolve().parents[1] / "benchmarks")) from pilot import matrix, run_job, save