Files
aji/tools/eval/tests/test_harness.py
T
dev b49003bdb9 E0-3: language-neutral agent scaffold and run recorder
tools/eval (stdlib Python): one agent loop, system prompt and tool set
(list/read/write/edit files, run, finish) for every language; language
profiles for aji_air, rust, zig carry only toolchain invocation, docs
location and command classification; bubblewrap sandbox without
network, read-only toolchain and /docs; providers: Anthropic Messages,
OpenAI-compatible (incl. local servers), scripted; run record per
protocol §28 (hashes, versions, limits, hardware, seed, all events,
patches, commands, final repository, first-generation snapshot,
evaluator verdicts, cost); metrics §14-§17; resumable matrix plans;
report (VSR, repair cycles, context, cost per correct solution);
classify (§27 categories, caught-by, smoke-test causes).

docs/evaluation/harness.md (task format for the private benchmark
repository, evaluator contract, record schema); dev-tasks/dev-echo
(harness development task, no benchmark family); smoke plan shape for
the owner's E-S choice (binary/stream parser, bounded pipeline);
self-tests in CI
2026-10-04 17:17:43 +03:00

129 lines
5.6 KiB
Python

"""Harness self-tests: sandbox isolation, path confinement, budgets, the
complete run record (protocol §28) and resumable matrices.
cd tools/eval && python3 -m unittest discover tests
Requires zig-out/bin/aji (`zig build`) and the Rust and Zig toolchains;
sandbox tests are skipped where bubblewrap cannot create namespaces.
"""
import json
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.dirname(HERE))
from ajieval import agent, languages, record, report, sandbox, util # noqa: E402
TASK = os.path.join(util.REPO, "docs", "evaluation", "dev-tasks", "dev-echo")
EVALUATOR = [os.path.join(TASK, "evaluator.py")]
def bwrap_works():
if shutil.which("bwrap") is None:
return False
return subprocess.run(["bwrap", "--unshare-all", "--ro-bind", "/", "/", "true"], capture_output=True).returncode == 0
SANDBOX = "bwrap" if bwrap_works() else "none"
class SandboxTest(unittest.TestCase):
@unittest.skipUnless(SANDBOX == "bwrap", "bubblewrap unavailable")
def test_isolation(self):
ws = tempfile.mkdtemp()
sb = sandbox.Sandbox("bwrap", ws, [], [], docs=TASK)
code, out, _ = sb.run("echo hi > f && cat f", 30, 1000)
self.assertEqual((code, out.strip()), (0, "hi"))
code, out, _ = sb.run("getent hosts example.com || echo NO_NET", 30, 1000)
self.assertIn("NO_NET", out)
code, _, _ = sb.run("touch /docs/x", 30, 1000)
self.assertNotEqual(code, 0)
code, out, _ = sb.run("ls " + os.path.expanduser("~") + " 2>&1 || echo NO_HOME", 30, 1000)
self.assertIn("NO_HOME", out)
self.assertTrue(os.path.exists(os.path.join(ws, "f")))
def test_output_limit_and_timeout(self):
sb = sandbox.Sandbox(SANDBOX, tempfile.mkdtemp(), [], [])
code, out, truncated = sb.run("yes | head -c 5000", 30, 100)
self.assertTrue(truncated)
self.assertLess(len(out), 200)
code, _, _ = sb.run("sleep 5", 1, 100)
self.assertIsNone(code)
class PathTest(unittest.TestCase):
def test_confinement(self):
ws = tempfile.mkdtemp()
a = agent.Agent(None, {"instructions": ""}, None, {}, None, ws, None, None, {"tool_calls": 1, "total_tokens": 1, "output_chars": 100})
for bad in ["/etc/passwd", "../x", "/work/../etc/passwd", "/docs/x"]:
with self.assertRaises(agent.ToolError):
a.host_path(bad)
with self.assertRaises(agent.ToolError):
a.host_path("/docs", write=True)
self.assertEqual(a.host_path("a/b")[0], os.path.join(os.path.realpath(ws), "a", "b"))
class RunTest(unittest.TestCase):
def setUp(self):
self.out = tempfile.mkdtemp()
def run_lang(self, lang, **kw):
return record.run_one(TASK, lang, "scripted", os.path.join(HERE, "scripts", lang + ".json"), self.out,
model_class="test", sandbox_kind=SANDBOX, evaluator=EVALUATOR, **kw)
def test_all_languages_complete_record(self):
for lang in languages.available():
with self.subTest(lang=lang):
run_dir, rec = self.run_lang(lang)
self.assertTrue(rec["accepted"], rec["verdict"])
self.assertEqual(rec["metrics"]["termination"], "finished")
for key in ["task", "evaluator", "language", "model", "scaffold", "system_prompt_hash", "task_prompt_hash",
"limits", "hardware", "seed", "metrics", "final_repository", "verdict", "cost_usd"]:
self.assertIn(key, rec)
self.assertTrue(rec["evaluator"]["hash"].startswith("sha256:"))
m = rec["metrics"]
self.assertEqual(m["patches"], 2)
self.assertEqual(m["failed_verifier_cycles"], 1)
self.assertFalse(m["first_check_accepted"] or m["first_build_accepted"])
self.assertTrue(m["first_public_test_passed"])
self.assertFalse(m["first_hidden_test_passed"]) # the snapshot holds the broken file
kinds = [json.loads(l)["event"] for l in open(os.path.join(run_dir, "events.jsonl"))]
for k in ["start", "model", "tool", "patch", "command"]:
self.assertIn(k, kinds)
rows = report.aggregate(report.load([self.out]))
self.assertEqual(len(rows), len(languages.available()))
self.assertTrue(all(r["verified_success_rate"] == 1.0 for r in rows))
def test_tool_budget(self):
_, rec = self.run_lang("aji_air", limits={"tool_calls": 3})
self.assertEqual(rec["metrics"]["termination"], "budget_tool_calls")
self.assertFalse(rec["accepted"])
def test_cost(self):
pricing = {os.path.join(HERE, "scripts", "zig.json"): {"input": 1.0, "output": 10.0}}
_, rec = self.run_lang("zig", pricing=pricing)
m = rec["metrics"]
self.assertAlmostEqual(rec["cost_usd"], (m["input_tokens"] + 10 * m["output_tokens"]) / 1e6, places=6)
class MatrixTest(unittest.TestCase):
def test_resume(self):
d = tempfile.mkdtemp()
plan = {"tasks": [TASK], "languages": ["rust"], "runs": 1, "sandbox": SANDBOX, "evaluator": EVALUATOR[0],
"models": [{"provider": "scripted", "model": os.path.join(HERE, "scripts", "rust.json"), "class": "test"}]}
path = os.path.join(d, "plan.json")
util.write_json(path, plan)
for _ in range(2):
subprocess.run([sys.executable, "-m", "ajieval", "matrix", path], cwd=os.path.dirname(HERE), check=True, capture_output=True)
self.assertEqual(len(report.load([os.path.join(d, "runs")])), 1)
if __name__ == "__main__":
unittest.main()