The evaluator now receives AJIEVAL_LANGUAGE, AJIEVAL_TOOLCHAIN_PATH and AJIEVAL_TOOLCHAIN_DIRS (the toolchain exactly as the agent's sandbox had it), its full output is saved as evaluator.log in the run directory, and ajieval evaluate runs an evaluator on any workspace exactly as the harness does. harness.md documents what a sandboxing evaluator should do (bind the toolchain dirs, private CARGO_HOME + --offline, build without the agent's target/ and caches, report infrastructure failures distinctly).
167 lines
7.7 KiB
Python
167 lines
7.7 KiB
Python
"""Run recorder and the orchestration of one run (protocol §3, §28)."""
|
|
|
|
import datetime
|
|
import json
|
|
import os
|
|
import re
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
|
|
from . import __version__, agent, context, languages, providers, sandbox, task as task_mod, util
|
|
|
|
|
|
class Recorder:
|
|
def __init__(self, run_dir):
|
|
self.dir = run_dir
|
|
self.f = open(os.path.join(run_dir, "events.jsonl"), "w")
|
|
self.seq = 0
|
|
self.t0 = time.monotonic()
|
|
|
|
def event(self, kind, /, **fields):
|
|
self.seq += 1
|
|
self.f.write(json.dumps({"seq": self.seq, "t": round(time.monotonic() - self.t0, 3), "event": kind, **fields}) + "\n")
|
|
self.f.flush()
|
|
|
|
def snapshot(self, workspace, name):
|
|
dst = os.path.join(self.dir, name)
|
|
shutil.copytree(workspace, dst, ignore=shutil.ignore_patterns("target", ".zig-cache", "zig-cache", "zig-out"))
|
|
return dst
|
|
|
|
def close(self):
|
|
self.f.close()
|
|
|
|
|
|
def slug(s):
|
|
return re.sub(r"[^A-Za-z0-9._-]+", "-", s).strip("-")[:60]
|
|
|
|
|
|
def file_hashes(root):
|
|
out = {}
|
|
for r, dirs, files in os.walk(root):
|
|
dirs[:] = sorted(d for d in dirs if d not in ("target", ".zig-cache", "zig-cache", "zig-out"))
|
|
for name in sorted(files):
|
|
full = os.path.join(r, name)
|
|
out[os.path.relpath(full, root)] = util.sha256_path(full)
|
|
return out
|
|
|
|
|
|
def evaluator_env(lang):
|
|
"""Environment for the evaluator: the caller's environment plus the
|
|
language toolchain exactly as the agent's sandbox had it, so an
|
|
evaluator that sandboxes the code it runs can bind the same directories.
|
|
|
|
AJIEVAL_LANGUAGE language id (aji_air, rust, zig)
|
|
AJIEVAL_TOOLCHAIN_PATH PATH entries of the toolchain (`:`-separated)
|
|
AJIEVAL_TOOLCHAIN_DIRS directories to bind read-only (newline-separated)
|
|
"""
|
|
env = dict(os.environ)
|
|
try:
|
|
_, binds = languages.resolve_binaries(languages.load(lang))
|
|
except SystemExit:
|
|
binds = []
|
|
env["AJIEVAL_LANGUAGE"] = lang
|
|
env["AJIEVAL_TOOLCHAIN_PATH"] = ":".join(languages.sandbox_path(binds))
|
|
env["AJIEVAL_TOOLCHAIN_DIRS"] = "\n".join(binds)
|
|
return env
|
|
|
|
|
|
def evaluate(evaluator, workspace, lang, task_dir, timeout, log_path=None):
|
|
"""Runs the (external, hidden) evaluator; returns its JSON verdict. Its
|
|
full output goes to `log_path` (the run directory), not to the record."""
|
|
try:
|
|
p = subprocess.run(evaluator + [workspace, lang, task_dir], capture_output=True, text=True, timeout=timeout, env=evaluator_env(lang))
|
|
except subprocess.TimeoutExpired:
|
|
return {"accepted": False, "error": "evaluator timed out"}
|
|
if log_path:
|
|
with open(log_path, "w") as f:
|
|
f.write(f"$ {' '.join(evaluator)} WORKSPACE {lang} TASK_DIR\nexit {p.returncode}\n--- stdout ---\n{p.stdout}\n--- stderr ---\n{p.stderr}")
|
|
try:
|
|
verdict = json.loads(p.stdout)
|
|
except json.JSONDecodeError:
|
|
return {"accepted": False, "error": f"evaluator printed no JSON (exit {p.returncode})", "stderr": p.stderr[-2000:]}
|
|
verdict["accepted"] = bool(verdict.get("accepted"))
|
|
return verdict
|
|
|
|
|
|
def cost(pricing, model, m):
|
|
"""Cost in USD from a pricing table (USD per million tokens), or None."""
|
|
price = (pricing or {}).get(model)
|
|
if not price:
|
|
return None
|
|
cached = m["cached_input_tokens"]
|
|
return round(((m["input_tokens"] - cached) * price["input"] + cached * price.get("cached_input", price["input"]) + m["output_tokens"] * price["output"]) / 1e6, 6)
|
|
|
|
|
|
def run_one(task_dir, lang_name, provider_name, model, out_dir, model_class=None, seed=0, sandbox_kind="bwrap",
|
|
evaluator=None, evaluator_hash_path=None, pricing=None, base_url=None, max_tokens=8192, temperature=None, limits=None,
|
|
provider_options=None):
|
|
task = task_mod.Task(task_dir)
|
|
profile = languages.load(lang_name)
|
|
lang = task.language(lang_name)
|
|
lim = dict(task.limits, **(limits or {}))
|
|
|
|
stamp = datetime.datetime.now(datetime.timezone.utc).strftime("%Y%m%dT%H%M%SZ")
|
|
run_id = f"{slug(task.id)}.{lang_name}.{slug(os.path.basename(model))}.s{seed}.{stamp}"
|
|
run_dir = os.path.join(out_dir, run_id)
|
|
os.makedirs(run_dir)
|
|
workspace = os.path.join(run_dir, "workspace")
|
|
agent.copy_workspace(lang["workspace"], workspace)
|
|
|
|
_, binds = languages.resolve_binaries(profile)
|
|
docs = languages.docs_mounts(profile)
|
|
if not docs:
|
|
print(f"warning: no local documentation for {lang_name} (set {profile.get('docs', {}).get('env')}); protocol §4 requires pinned docs", file=sys.stderr)
|
|
sb = sandbox.Sandbox(sandbox_kind, workspace, binds, languages.sandbox_path(binds), docs, profile.get("env"))
|
|
kw = {"max_tokens": max_tokens, "temperature": temperature, "base_url": base_url, **(provider_options or {})}
|
|
prov = providers.make(provider_name, model, **kw)
|
|
|
|
rec = Recorder(run_dir)
|
|
a = agent.Agent(prov, profile, task, lang, sb, workspace, docs, rec, lim)
|
|
message = agent.task_message(task, workspace)
|
|
rec.event("start", system=a.system, task_message=message)
|
|
started = datetime.datetime.now(datetime.timezone.utc).isoformat()
|
|
metrics = a.run(message)
|
|
rec.close()
|
|
|
|
for key in ("files_opened",):
|
|
metrics[key + "_count"] = len(metrics[key])
|
|
metrics["documentation_tokens_estimate"] = util.estimate_tokens(metrics["documentation_bytes_read"])
|
|
metrics["context"] = context.metrics(context.tool_events_track_a(os.path.join(run_dir, "events.jsonl")), message, docs,
|
|
{"input": metrics["input_tokens"], "output": metrics["output_tokens"], "cached_input": metrics["cached_input_tokens"]})
|
|
metrics["repository_tokens_estimate"] = util.estimate_tokens(metrics["repository_bytes_read"])
|
|
|
|
verdict = first_verdict = None
|
|
if evaluator:
|
|
verdict = evaluate(evaluator, workspace, lang_name, task.dir, lim["command_timeout"] * 4, os.path.join(run_dir, "evaluator.log"))
|
|
if a.first_snapshot:
|
|
first_verdict = evaluate(evaluator, a.first_snapshot, lang_name, task.dir, lim["command_timeout"] * 4, os.path.join(run_dir, "evaluator.first.log"))
|
|
metrics["first_hidden_test_passed"] = None if first_verdict is None else first_verdict["accepted"]
|
|
|
|
record = {
|
|
"schema": "aji-eval-run/1",
|
|
"run_id": run_id,
|
|
"started": started,
|
|
"task": {"id": task.id, "version": task.version, "set": task.set, "family": task.spec.get("family"), "hash": task.hash(), "concurrency": bool(task.spec.get("concurrency"))},
|
|
"evaluator": None if not evaluator else {"command": evaluator, "hash": util.sha256_path(evaluator_hash_path or evaluator[0])},
|
|
"language": {"name": lang_name, "profile_hash": profile["profile_hash"], "toolchain": languages.versions(profile), "docs": [{"mount": "/docs/" + n, "path": p, "hash": util.sha256_path_cached(p)} for n, p in docs]},
|
|
"model": {"provider": provider_name, "id": model, "class": model_class, "params": prov.params(), "base_url": base_url},
|
|
"scaffold": {"version": __version__, "commit": util.git_commit(), "sandbox": sb.describe()},
|
|
"system_prompt_hash": util.sha256_text(a.system),
|
|
"task_prompt_hash": util.sha256_text(message),
|
|
"limits": lim,
|
|
"hardware": util.hardware(),
|
|
"seed": seed,
|
|
"metrics": metrics,
|
|
"cost_usd": cost(pricing, model, metrics),
|
|
"final_repository": {"path": "workspace", "files": file_hashes(workspace)},
|
|
"first_generation": None if not a.first_snapshot else "first_generation",
|
|
"verdict": verdict,
|
|
"first_generation_verdict": first_verdict,
|
|
"accepted": None if verdict is None else verdict["accepted"],
|
|
"classification": None,
|
|
}
|
|
util.write_json(os.path.join(run_dir, "run.json"), record)
|
|
return run_dir, record
|