Datasets:
Download experiments/common/tests/test_agents.py from PV-SJTU/PV-Bench: direct link, hf CLI and curl.
- Browser
- Download file 16.7 kB
-
https://huggingface.co/datasets/PV-SJTU/PV-Bench/resolve/main/experiments/common/tests/test_agents.py
- Command line
-
hf download hf://datasets/PV-SJTU/PV-Bench/experiments/common/tests/test_agents.py
-
curl -L -o test_agents.py https://huggingface.co/datasets/PV-SJTU/PV-Bench/resolve/main/experiments/common/tests/test_agents.py
16.7 kB
| import json | |
| import os | |
| import sys | |
| import tempfile | |
| import unittest | |
| from pathlib import Path | |
| from unittest import mock | |
| sys.path.insert(0, str(Path(__file__).resolve().parents[1])) | |
| from pvbench_common import agents # noqa: E402 | |
| from pvbench_common.agents import CLAUDE, CODEX, AgentError, parse_events, read_events # noqa: E402 | |
| def lines(*events) -> str: | |
| return "".join(json.dumps(e) + "\n" for e in events) | |
| CODEX_TRACE = [ | |
| {"type": "thread.started", "thread_id": "t"}, | |
| {"type": "turn.started"}, | |
| {"type": "item.completed", "item": {"id": "i1", "type": "reasoning", "text": "think"}}, | |
| {"type": "item.started", "item": {"id": "i2", "type": "command_execution", "command": "ls -l\nanswer"}}, | |
| {"type": "item.completed", "item": {"id": "i2", "type": "command_execution", "command": "ls -l\nanswer", | |
| "aggregated_output": "proof.v\n", "exit_code": 0}}, | |
| {"type": "item.completed", "item": {"id": "i3", "type": "agent_message", "text": "first"}}, | |
| {"type": "item.completed", "item": {"id": "i4", "type": "error", | |
| "message": "Model metadata for x not found. Defaulting to fallback metadata"}}, | |
| {"type": "item.completed", "item": {"id": "i5", "type": "agent_message", "text": "done"}, | |
| "usage": {"input_tokens": 5, "output_tokens": 2}}, | |
| ] | |
| CODEX_DONE = {"type": "turn.completed", | |
| "usage": {"input_tokens": 100, "cached_input_tokens": 40, "output_tokens": 7, "reasoning_output_tokens": 3}} | |
| CLAUDE_TRACE = [ | |
| {"type": "system", "subtype": "init", "model": "claude-sonnet-5"}, | |
| {"type": "assistant", "message": {"content": [ | |
| {"type": "text", "text": "looking"}, | |
| {"type": "tool_use", "id": "u1", "name": "Bash", "input": {"command": "ls\nanswer"}}, | |
| {"type": "tool_use", "id": "u2", "name": "Read", "input": {"file_path": "/work/a.v"}}, | |
| {"type": "tool_use", "id": "u3", "name": "Grep", "input": {"pattern": "Lemma", "path": "/work"}}, | |
| {"type": "tool_use", "id": "u4", "name": "Odd", "input": {"x": 1}}, | |
| ]}}, | |
| {"type": "user", "message": {"content": [ | |
| {"type": "tool_result", "tool_use_id": "u1", "content": "proof.v\n"}, | |
| {"type": "tool_result", "tool_use_id": "u2", "content": [{"type": "text", "text": "Lemma a."}]}, | |
| {"type": "tool_result", "tool_use_id": "zz", "content": "orphan"}, | |
| ]}}, | |
| ] | |
| CLAUDE_DONE = {"type": "result", "subtype": "success", "is_error": False, "result": "final words", | |
| "duration_ms": 12345, "num_turns": 4, "total_cost_usd": 0.25, | |
| "usage": {"input_tokens": 10, "cache_read_input_tokens": 8, "cache_creation_input_tokens": 1, | |
| "output_tokens": 3}} | |
| class RegistryTests(unittest.TestCase): | |
| def test_names_and_get(self): | |
| self.assertEqual(agents.NAMES, ("codex", "claude")) | |
| self.assertIs(agents.get("codex"), CODEX) | |
| self.assertIs(agents.get("claude"), CLAUDE) | |
| with self.assertRaises(AgentError) as cm: | |
| agents.get("gemini") | |
| self.assertIn("gemini", str(cm.exception)) | |
| def test_parse_events_skips_noise_and_huge_lines(self): | |
| text = "not json\n" + json.dumps([1, 2]) + "\n" + json.dumps({"type": "x"}) + "\n" + "{" + "a" * (4 * 1024 * 1024) + "}\n" | |
| self.assertEqual(parse_events(text), [{"type": "x"}]) | |
| def test_read_events_missing_file(self): | |
| self.assertEqual(read_events(Path(tempfile.gettempdir()) / "pvbench-no-such-trace.jsonl"), []) | |
| with tempfile.TemporaryDirectory() as tmp: | |
| path = Path(tmp) / "events.jsonl" | |
| path.write_bytes(b'{"type": "a"}\n\xff\xfe\n{"type": "b"}\n') | |
| self.assertEqual([e["type"] for e in read_events(path)], ["a", "b"]) | |
| def test_detect(self): | |
| self.assertIs(agents.detect(CODEX_TRACE + [CODEX_DONE]), CODEX) | |
| self.assertIs(agents.detect(CODEX_TRACE), CODEX) | |
| self.assertIs(agents.detect(CLAUDE_TRACE + [CLAUDE_DONE]), CLAUDE) | |
| self.assertIs(agents.detect(CLAUDE_TRACE), CLAUDE) | |
| self.assertIsNone(agents.detect([])) | |
| self.assertIsNone(agents.detect([{"type": "mystery"}])) | |
| class CodexTests(unittest.TestCase): | |
| def test_api_error(self): | |
| self.assertIsNone(CODEX.api_error(CODEX_TRACE + [CODEX_DONE])) # the item-level "error" is not one | |
| self.assertIn("turn.failed", CODEX.api_error([{"type": "turn.failed", "error": {"message": "401"}}])) | |
| self.assertIn("usage limit", CODEX.api_error([{"type": "error", "message": "usage limit reached"}])) | |
| self.assertIsNotNone(CODEX.api_error([{"type": "turn.completed", "error": "x"}])) | |
| self.assertLessEqual(len(CODEX.api_error([{"type": "error", "message": "m" * 500}])), 180) | |
| def test_api_error_reconnect_is_not_one(self): | |
| reconnect = {"type": "error", "message": "Reconnecting... 2/5 (stream disconnected before completion)"} | |
| item = {"type": "item.completed", "item": {"id": "i9", "type": "command_execution", "command": "ls"}} | |
| # the stream dropped, the CLI reconnected and the session finished: not an API failure | |
| self.assertIsNone(CODEX.api_error(CODEX_TRACE + [reconnect, item, CODEX_DONE])) | |
| self.assertIsNone(CODEX.api_error(CODEX_TRACE + [reconnect, reconnect, item])) # killed at timeout later | |
| # the reconnect gave up: nothing follows the error, or turn.failed does | |
| self.assertIn("Reconnecting", CODEX.api_error(CODEX_TRACE + [reconnect])) | |
| self.assertIn("Reconnecting", CODEX.api_error(CODEX_TRACE + [item, reconnect, reconnect])) | |
| failed = {"type": "turn.failed", "error": {"message": "usage limit"}} | |
| self.assertIn("usage limit", CODEX.api_error(CODEX_TRACE + [reconnect, item, {"type": "error", "message": "usage limit"}, failed])) | |
| def test_completed(self): | |
| self.assertFalse(CODEX.completed(CODEX_TRACE)) | |
| self.assertTrue(CODEX.completed(CODEX_TRACE + [CODEX_DONE])) | |
| self.assertFalse(CODEX.completed([{"type": "item.completed", "item": {"type": "agent_message", "text": "turn.completed"}}])) | |
| def test_last_message_and_usage(self): | |
| self.assertEqual(CODEX.last_message(CODEX_TRACE), "done") | |
| self.assertIsNone(CODEX.last_message([])) | |
| self.assertEqual(CODEX.usage(CODEX_TRACE + [CODEX_DONE]), CODEX_DONE) | |
| self.assertEqual(CODEX.usage(CODEX_TRACE), {"partial": True, "usage": {"input_tokens": 5, "output_tokens": 2}}) | |
| self.assertEqual(CODEX.usage([]), {"partial": True, "usage": None}) | |
| item_usage = [{"type": "item.completed", "item": {"type": "agent_message", "text": "t", "usage": {"input_tokens": 9}}}] | |
| self.assertEqual(CODEX.usage(item_usage), {"partial": True, "usage": {"input_tokens": 9}}) | |
| def test_usage_summary(self): | |
| self.assertEqual(CODEX.usage_summary(CODEX_DONE), { | |
| "tokens": {"input": 100, "cached_input": 40, "output": 7, "reasoning": 3}}) | |
| self.assertEqual(CODEX.usage_summary({"partial": True, "usage": {"input_tokens": 5}}), { | |
| "usage_partial": True, "tokens": {"input": 5, "cached_input": None, "output": None, "reasoning": None}}) | |
| self.assertEqual(list(CODEX.usage_summary({"partial": True, "usage": None})), ["usage_partial", "tokens"]) | |
| def test_actions(self): | |
| self.assertEqual(CODEX.actions(CODEX_TRACE + [CODEX_DONE]), [("bash: ls -l answer", "proof.v\n")]) | |
| self.assertEqual(CODEX.actions([{"type": "item.completed", "item": {"type": "command_execution"}}]), [("bash: ", "")]) | |
| class ClaudeTests(unittest.TestCase): | |
| def test_api_error(self): | |
| self.assertIsNone(CLAUDE.api_error(CLAUDE_TRACE + [CLAUDE_DONE])) | |
| self.assertEqual(CLAUDE.api_error([{"type": "result", "is_error": True, "result": "403 forbidden"}]), "403 forbidden") | |
| self.assertIsNone(CLAUDE.api_error([{"type": "turn.failed"}])) | |
| def test_completed(self): | |
| self.assertFalse(CLAUDE.completed(CLAUDE_TRACE)) | |
| self.assertTrue(CLAUDE.completed(CLAUDE_TRACE + [CLAUDE_DONE])) | |
| def test_last_message_and_usage(self): | |
| self.assertEqual(CLAUDE.last_message(CLAUDE_TRACE + [CLAUDE_DONE]), "final words") | |
| self.assertIsNone(CLAUDE.last_message(CLAUDE_TRACE)) | |
| self.assertEqual(CLAUDE.last_message([{"type": "result", "result": None}]), "") | |
| self.assertEqual(CLAUDE.usage(CLAUDE_TRACE + [CLAUDE_DONE]), { | |
| "duration_ms": 12345, "num_turns": 4, "total_cost_usd": 0.25, "usage": CLAUDE_DONE["usage"]}) | |
| self.assertIsNone(CLAUDE.usage(CLAUDE_TRACE)) | |
| # the last result wins | |
| self.assertEqual(CLAUDE.last_message([CLAUDE_DONE, dict(CLAUDE_DONE, result="later")]), "later") | |
| def test_usage_summary(self): | |
| self.assertEqual(CLAUDE.usage_summary(CLAUDE.usage([CLAUDE_DONE])), { | |
| "tokens": {"input": 10, "cache_read": 8, "cache_creation": 1, "output": 3}, | |
| "cost_usd": 0.25, "turns": 4, "wall_seconds": 12.3}) | |
| self.assertEqual(CLAUDE.usage_summary({"usage": None, "num_turns": None}), { | |
| "tokens": {"input": None, "cache_read": None, "cache_creation": None, "output": None}, | |
| "cost_usd": None, "turns": None}) | |
| def test_actions_pair_results(self): | |
| self.assertEqual(CLAUDE.actions(CLAUDE_TRACE + [CLAUDE_DONE]), [ | |
| ("Bash: ls answer", "proof.v\n"), | |
| ("Read: /work/a.v", json.dumps([{"type": "text", "text": "Lemma a."}])), | |
| ("Grep: /work", ""), # path precedes pattern | |
| ("Odd: " + json.dumps({"x": 1}), ""), | |
| ]) | |
| class ModuleActionsTests(unittest.TestCase): | |
| def test_actions_from_file_detects_format(self): | |
| with tempfile.TemporaryDirectory() as tmp: | |
| path = Path(tmp) / "events.jsonl" | |
| path.write_text(lines(*CLAUDE_TRACE, CLAUDE_DONE)) | |
| self.assertEqual(agents.actions(path)[:2], ["Bash: ls answer", "Read: /work/a.v"]) | |
| path.write_text(lines(*CODEX_TRACE, CODEX_DONE)) | |
| self.assertEqual(agents.actions(path), ["bash: ls -l answer"]) | |
| self.assertEqual(agents.actions_with_results(path, CLAUDE), []) | |
| self.assertEqual(agents.actions(Path(tmp) / "missing.jsonl"), []) | |
| path.write_text("garbage\n") | |
| self.assertEqual(agents.actions(path), []) | |
| if __name__ == "__main__": | |
| unittest.main() | |
| class ContractTests(unittest.TestCase): | |
| """Static facts and command lines every registered adapter must provide.""" | |
| DOCKER_AGENTS = Path(__file__).resolve().parents[2] / "docker" / "agents" | |
| def test_static_facts(self): | |
| for agent in agents.AGENTS.values(): | |
| self.assertTrue(agent.name and agent.display and agent.prompt_file and agent.efforts) | |
| self.assertTrue((self.DOCKER_AGENTS / agent.install_script).is_file(), agent.install_script) | |
| self.assertEqual(agents.PROMPT_FILES, ("AGENTS.md", "CLAUDE.md")) | |
| self.assertEqual(CODEX.efforts, ("low", "medium", "high", "xhigh", "max", "ultra")) | |
| self.assertEqual(CLAUDE.efforts, ("low", "medium", "high", "max")) | |
| def test_check_effort(self): | |
| CODEX.check_effort(None) | |
| CODEX.check_effort("ultra") | |
| CLAUDE.check_effort("max") | |
| with self.assertRaises(agents.AgentError) as cm: | |
| CLAUDE.check_effort("ultra") | |
| self.assertIn("low, medium, high, max", str(cm.exception)) | |
| self.assertIn("'ultra'", str(cm.exception)) | |
| def test_codex_command(self): | |
| self.assertEqual(CODEX.command("/work", "gpt-6-astra", "Read AGENTS.md.", effort="high"), [ | |
| "codex", "exec", "-C", "/work", "-m", "gpt-6-astra", "--ephemeral", | |
| "--ignore-user-config", "--ignore-rules", "-c", 'approval_policy="never"', | |
| "-c", 'web_search="disabled"', "--dangerously-bypass-approvals-and-sandbox", | |
| "-c", 'model_reasoning_effort="high"', "--json", "Read AGENTS.md.", | |
| ]) | |
| self.assertNotIn("-c model_reasoning_effort", " ".join(CODEX.command("/work", "m", "p"))) | |
| routed = CODEX.command("/work", "m", "p", effort="high", config=('model_provider="x"', 'model_providers.x.wire_api="responses"')) | |
| self.assertEqual(routed[-6:], ["-c", 'model_provider="x"', "-c", 'model_providers.x.wire_api="responses"', "--json", "p"]) | |
| def test_claude_command(self): | |
| self.assertEqual(CLAUDE.command("/work", "opus", "Read CLAUDE.md.", effort="max"), [ | |
| "claude", "-p", "--model", "opus", "--effort", "max", "--dangerously-skip-permissions", | |
| "--setting-sources", "", "--output-format", "stream-json", "--verbose", "Read CLAUDE.md.", | |
| ]) | |
| self.assertNotIn("--effort", CLAUDE.command("/work", "opus", "p")) | |
| routed = CLAUDE.command("/work", "opus", "p", config=("env.A=1", 'model="x"', "note=plain")) | |
| self.assertEqual(routed[routed.index("--settings") + 1], '{"env.A": 1, "model": "x", "note": "plain"}') | |
| with self.assertRaises(agents.AgentError): | |
| CLAUDE.command("/work", "opus", "p", effort="ultra") | |
| def _setup(self, session: Path, effort=None) -> agents.JudgeSetup: | |
| return agents.JudgeSetup(workspace="/work/workspace", answer="/work/answer", session=session, server="t2", | |
| broker={"command": "python3", "args": ["-I", "/work/harness/broker.py"]}, | |
| tools=("read_file", "check"), tool_timeout=60, | |
| system_prompt="You are a judge.", effort=effort) | |
| def test_codex_judge_command(self): | |
| with tempfile.TemporaryDirectory() as tmp: | |
| home = Path(tmp) / "codex-home"; home.mkdir() | |
| (home / "models_cache.json").write_text(json.dumps({"models": [ | |
| {"slug": "gpt-5.6-sol", "tool_mode": "x", "apply_patch_tool_type": "y"}]})) | |
| session = Path(tmp) / "session"; session.mkdir() | |
| with mock.patch.dict(os.environ, {"CODEX_HOME": str(home)}): | |
| argv = CODEX.judge_command(self._setup(session, "medium"), "gpt-5.6-sol", "Judge.") | |
| with self.assertRaisesRegex(ValueError, "absent"): | |
| CODEX.judge_command(self._setup(Path(tmp) / "other"), "unknown", "Judge.") | |
| self.assertEqual(argv[:13], ["codex", "exec", "--json", "--color", "never", "--ephemeral", | |
| "--ignore-user-config", "--ignore-rules", "--skip-git-repo-check", | |
| "--dangerously-bypass-approvals-and-sandbox", "-C", "/work/workspace", "-m"]) | |
| self.assertEqual(argv[13], "gpt-5.6-sol") | |
| self.assertEqual(argv[-1], "Judge.") | |
| settings = dict(a.split("=", 1) for a in argv[14:-1] if a != "-c") | |
| self.assertEqual(settings["model_catalog_json"], '"/work/answer/model-catalog.json"') | |
| self.assertEqual(settings["mcp_servers.t2.command"], '"python3"') | |
| self.assertEqual(json.loads(settings["mcp_servers.t2.enabled_tools"]), ["read_file", "check"]) | |
| self.assertEqual(settings["mcp_servers.t2.tool_timeout_sec"], "75") | |
| self.assertEqual(settings["features.shell_tool"], "false") | |
| self.assertEqual(settings["model_reasoning_effort"], '"medium"') | |
| catalog = json.loads((session / "model-catalog.json").read_text()) | |
| self.assertIsNone(catalog["models"][0]["tool_mode"]) | |
| self.assertIsNone(catalog["models"][0]["apply_patch_tool_type"]) | |
| self.assertNotIn(tmp, " ".join(argv)) | |
| def test_claude_judge_command(self): | |
| with tempfile.TemporaryDirectory() as tmp: | |
| session = Path(tmp) / "session"; session.mkdir() | |
| argv = CLAUDE.judge_command(self._setup(session, "high"), "opus", "Judge.") | |
| self.assertEqual(argv[:7], ["claude", "--print", "--verbose", "--output-format", "stream-json", "--model", "opus"]) | |
| self.assertEqual(argv[argv.index("--tools") + 1], "") | |
| self.assertEqual(argv[argv.index("--settings") + 1], "/work/answer/claude-settings.json") | |
| self.assertEqual(argv[argv.index("--mcp-config") + 1], "/work/answer/mcp.json") | |
| self.assertEqual(argv[argv.index("--system-prompt") + 1], "You are a judge.") | |
| self.assertEqual(argv[-3:], ["--effort", "high", "Judge."]) | |
| mcp = json.loads((session / "mcp.json").read_text()) | |
| self.assertEqual(mcp["mcpServers"]["t2"]["args"], ["-I", "/work/harness/broker.py"]) | |
| settings = json.loads((session / "claude-settings.json").read_text()) | |
| self.assertEqual(settings["permissions"]["allow"], ["mcp__t2__read_file", "mcp__t2__check"]) | |
| with self.assertRaises(agents.AgentError): | |
| CLAUDE.judge_command(self._setup(session, "xhigh"), "opus", "Judge.") | |