Files
aji/tools/eval/ajieval/record.py
T
dev d7bb9273f3 E0-3/E0-4 groundwork: provider options, pinned docs, Track A/B in the protocol
- providers: per-model request extras (e.g. reasoning_effort), key_env,
  token_param (max_completion_tokens on api.openai.com); recorded
- docs pinned to the toolchain being run: Rust offline docs from the
  sysroot, Zig langref and std source of the same installation; several
  mounts under a read-only /docs; hashes recorded (cached for big trees)
- protocol: neutral model labels and calibration before classes (§2);
  smoke gates, fixed Aji commit, fixed per-model reasoning mode, slope of
  degradation (§39a); Track A controlled vs Track B native agents (§39b)
- plan: E-C calibration, E-G gates, E-N native-agent run
2026-10-04 17:28:15 +03:00

141 lines
6.2 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, 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 evaluate(evaluator, workspace, lang, task_dir, timeout):
"""Runs the (external, hidden) evaluator; returns its JSON verdict."""
try:
p = subprocess.run(evaluator + [workspace, lang, task_dir], capture_output=True, text=True, timeout=timeout)
except subprocess.TimeoutExpired:
return {"accepted": False, "error": "evaluator timed out"}
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["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)
if a.first_snapshot:
first_verdict = evaluate(evaluator, a.first_snapshot, lang_name, task.dir, lim["command_timeout"] * 4)
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