Skip to content
Open
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
12 changes: 12 additions & 0 deletions bench/accuracy/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -194,3 +194,15 @@ next attempt. They are not a latest-result ledger, regression check, pass@1
estimate or full-suite score. Keep all original failures and repair attempts.
A final accuracy claim still needs the prescribed full-suite evaluation with
one fixed configuration and unchanged official denominator.

Interrupted Codex attempts retain complete MCP events, partial answers, CLI exit
status and the raw event hash in the per-case record. An incomplete JSON event
is logged and indexed by line; raw bytes are never rewritten. A malformed stream
cannot qualify as a prediction. Timeouts remain failures even if an earlier
query succeeded. Each new run also saves the exact UTF-8 stdin payload as
`codex-mcp/events/<instance_id>.prompt.txt` with `prompt_sha256` in the record.
This is the submitted benchmark request, not Codex's internal system context.
It contains question/schema/documentation and any explicitly requested prior
observations; no environment variables or authentication configuration are added.
Historical runs without these artifacts are not retroactively reconstructed as
captured inputs. This improves auditability, not measured benchmark accuracy.
90 changes: 53 additions & 37 deletions bench/accuracy/codex_mcp.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,31 @@ def executed_sql(answer, events, *, db=None, sql_timeout=30, max_rows=100000):
raise ValueError("Final SQL was not executed through Lang2SQL MCP")


def capture_trace(record, events_path, answer_path, process):
"""Keep complete events even when interruption leaves a partial final line."""
events, errors = [], []
if events_path.exists():
record["events_sha256"] = digest(events_path)
for number, line in enumerate(events_path.read_text(errors="replace").splitlines(), 1):
if not line.startswith("{"):
continue
try:
events.append(json.loads(line))
except json.JSONDecodeError as exc:
errors.append({"line": number, "error": str(exc)})
logger.warning("Invalid Codex event id=%s line=%d error=%s: %s",
record["instance_id"], number, type(exc).__name__, exc)
record.update(
cli_exit_code=process.returncode if process is not None else None,
cli_usage=[e.get("usage") for e in events if e.get("type") == "turn.completed"],
mcp_calls=[e["item"] for e in events if e.get("type") == "item.completed"
and e["item"].get("type") == "mcp_tool_call"],
answer=answer_path.read_text(errors="replace") if answer_path.exists() else "",
event_parse_errors=errors,
)
return events


def review_evidence(record):
"""Only model-visible prior evidence, never grader/status/answer-key fields."""
return json.dumps(
Expand Down Expand Up @@ -323,40 +348,34 @@ async def case_run(case):
)
process = None
try:
with (
events_path.open("wb") as out,
(directory / "events" / (ident + ".stderr")).open("wb") as err,
):
process = await asyncio.create_subprocess_exec(
*command,
cwd=work,
env=env,
stdin=asyncio.subprocess.PIPE,
stdout=out,
stderr=err,
)
await asyncio.wait_for(
process.communicate(prompt.encode()), args.case_timeout
)
events = [
json.loads(line)
for line in events_path.read_text().splitlines()
if line.startswith("{")
]
record["events_sha256"] = digest(events_path)
record["cli_exit_code"] = process.returncode
record["cli_usage"] = [
e.get("usage") for e in events if e.get("type") == "turn.completed"
]
record["mcp_calls"] = [
e["item"]
for e in events
if e.get("type") == "item.completed"
and e["item"].get("type") == "mcp_tool_call"
]
record["answer"] = (
answer_path.read_text() if answer_path.exists() else ""
)
prompt_path = directory / "events" / (ident + ".prompt.txt")
prompt_bytes = prompt.encode("utf-8")
prompt_path.write_bytes(prompt_bytes)
record["prompt_sha256"] = digest(prompt_path)
logger.info("Codex case starting id=%s prompt_sha256=%s", ident, record["prompt_sha256"])
try:
with (
events_path.open("wb") as out,
(directory / "events" / (ident + ".stderr")).open("wb") as err,
):
process = await asyncio.create_subprocess_exec(
*command,
cwd=work,
env=env,
stdin=asyncio.subprocess.PIPE,
stdout=out,
stderr=err,
)
await asyncio.wait_for(
process.communicate(prompt_bytes), args.case_timeout
)
finally:
if process is not None and process.returncode is None:
process.kill()
await process.wait()
events = capture_trace(record, events_path, answer_path, process)
if record["event_parse_errors"]:
raise ValueError("Malformed Codex event stream; retained complete events for diagnosis")
if process.returncode != 0:
raise RuntimeError("Codex invocation failed")
sql = executed_sql(
Expand All @@ -382,9 +401,6 @@ async def case_run(case):
)
record.update(status="failed", error_type=type(exc).__name__, error_message=str(exc))
finally:
if process is not None and process.returncode is None:
process.kill()
await process.wait()
record["seconds"] = time.monotonic() - started
write_json(directory / "records" / (ident + ".json"), record)
logger.info("Codex case finished id=%s status=%s", ident, record["status"])
Expand Down
104 changes: 104 additions & 0 deletions tests/test_codex_mcp_benchmark.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,3 +190,107 @@ async def test_pass_exclusion_cannot_filter_full_accuracy():

with pytest.raises(ValueError, match='requires --failures-from'):
await run(SimpleNamespace(exclude_passed_from=['completed'], failures_from=None))


@pytest.mark.asyncio
@pytest.mark.parametrize("timeout", [False, True])
async def test_runner_preserves_submitted_input_and_partial_trace(tmp_path, monkeypatch, timeout):
import asyncio
import hashlib
import json
from types import SimpleNamespace

from bench.accuracy import codex_mcp as runner

case = {"instance_id": "case1", "db": "fixture", "question": "Return one"}
manifest = tmp_path / "manifest.json"
manifest.write_text(json.dumps({"suite": "bird", "cases": [case], "db_sha256": {}}))
schema = tmp_path / "schema.json"
schema.write_text("{}")
monkeypatch.setattr(runner, "validate_inputs", lambda *a: None)
monkeypatch.setattr(runner, "load_schema_documents", lambda *a: {"fixture": "fixture schema"})
monkeypatch.setattr(runner.subprocess, "check_output", lambda *a, **k: "test-version")
monkeypatch.setattr(runner, "export_result", lambda *a: 1)
raw_event = json.dumps({"type": "item.completed", "item": event()["item"]}) + "\n"
submitted = []

class Process:
returncode = None
killed = False

async def communicate(self, data):
submitted.append(data)
if timeout:
await asyncio.sleep(60)
self.returncode = 0

def kill(self):
self.killed = True
self.returncode = -9

async def wait(self):
return self.returncode

process = Process()

async def spawn(*command, **kwargs):
kwargs["stdout"].write(raw_event.encode())
kwargs["stdout"].flush()
Path(command[command.index("--output-last-message") + 1]).write_text("```sql\nSELECT 1\n```")
return process

from pathlib import Path
monkeypatch.setattr(runner.asyncio, "create_subprocess_exec", spawn)
args = SimpleNamespace(
exclude_passed_from=[], failures_from=None, manifest=manifest, db_dir=tmp_path,
root=tmp_path, schema_docs=schema, split="all", output=tmp_path / "run",
model="test-model", reasoning_effort="high", concurrency=1,
case_timeout=0.01 if timeout else 1, sql_timeout=1, max_rows=100,
review_source=None,
)
await runner.run(args)
root = args.output / "codex-mcp"
record = json.loads((root / "records/case1.json").read_text())
assert record["status"] == ("failed" if timeout else "predicted")
assert len(record["mcp_calls"]) == 1
assert record["events_sha256"] == hashlib.sha256(raw_event.encode()).hexdigest()
assert record["answer"] == "```sql\nSELECT 1\n```"
assert record["cli_exit_code"] == (-9 if timeout else 0)
assert process.killed == timeout
assert (root / "events/case1.prompt.txt").read_bytes() == submitted[0]
assert record["prompt_sha256"] == hashlib.sha256(submitted[0]).hexdigest()
if timeout:
assert record["error_type"] == "TimeoutError"
assert "sql" not in record


def test_interrupted_event_tail_preserves_complete_calls(tmp_path, caplog):
import hashlib
import json
from types import SimpleNamespace

from bench.accuracy.codex_mcp import capture_trace

events = tmp_path / "events.jsonl"
payload = json.dumps({"type": "item.completed", "item": event()["item"]}) + '\n{"type":'
events.write_text(payload)
record = {"instance_id": "interrupted"}
complete = capture_trace(record, events, tmp_path / "missing-answer", SimpleNamespace(returncode=-9))
assert len(complete) == 1
assert len(record["mcp_calls"]) == 1
assert record["event_parse_errors"][0]["line"] == 2
assert record["events_sha256"] == hashlib.sha256(payload.encode()).hexdigest()
assert record["answer"] == ""
assert "interrupted" in caplog.text
assert "JSONDecodeError" in caplog.text
assert events.read_text() == payload


def test_spawn_failure_has_explicit_absent_trace(tmp_path):
from bench.accuracy.codex_mcp import capture_trace

record = {"instance_id": "not-started"}
assert capture_trace(record, tmp_path / "missing-events", tmp_path / "missing-answer", None) == []
assert record["cli_exit_code"] is None
assert record["mcp_calls"] == []
assert "events_sha256" not in record