Files
leleka/scripts/e2e/codex/delta/cell.py
T

255 lines
12 KiB
Python

#!/usr/bin/env python3
"""Run ONE cell (variant, task, repeat) of the Codex lossy-delta study against an already running stack (test tooling, stdlib only).
cell.py --cell-dir D --variant V1 --task fixbug-ledger --rep 1 --tasks-root TASKS --upstream http://127.0.0.1:8081
--upstream-model qwen-iq3 --codex-bin CODEX --wall-limit 2400 --max-rounds 150 [--engine-log PATH] [--stack-meta FILE]
Refuses to start when the task md / seed / acceptance files differ from MANIFEST.sha256. Writes into D:
workspace/ the final workspace (seed copied byte for byte before the run, then whatever Codex did)
codex-home/ CODEX_HOME of the run: config.toml and sessions/**/rollout-*.jsonl (Codex's own record of the session)
codex-events.jsonl `codex exec --json` events with the wall-clock time they were read (t_unix_ms)
codex.err Codex stderr
proxy/ logproxy output: rounds.jsonl and one gzip file per request and response (every byte Codex sent and received)
engine-slice.log the part of the engine log written during the cell (when --engine-log is given)
acceptance.log, acceptance.rc, workspace.sha256, prompt.txt, cell.json (metadata and outcome)
"""
import argparse
import json
import os
import shutil
import signal
import socket
import subprocess
import sys
import threading
import time
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import taskfile # noqa: E402
def utc():
return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
def copy_tree(src, dst):
"""Copy a tree byte for byte with default (writable) permissions: the task files on the server are read-only."""
os.makedirs(dst, exist_ok=True)
for root, dirs, files in os.walk(src):
rel = os.path.relpath(root, src)
for d in dirs:
os.makedirs(os.path.join(dst, rel, d) if rel != "." else os.path.join(dst, d), exist_ok=True)
for n in files:
shutil.copyfile(os.path.join(root, n), os.path.join(dst, rel, n) if rel != "." else os.path.join(dst, n))
def free_port():
with socket.socket() as s:
s.bind(("127.0.0.1", 0))
return s.getsockname()[1]
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--cell-dir", required=True)
ap.add_argument("--variant", required=True)
ap.add_argument("--task", required=True)
ap.add_argument("--rep", type=int, required=True)
ap.add_argument("--tasks-root", required=True)
ap.add_argument("--upstream", required=True)
ap.add_argument("--upstream-model", required=True)
ap.add_argument("--codex-bin", required=True)
ap.add_argument("--codex-sha256", default="")
ap.add_argument("--wall-limit", type=int, default=2400)
ap.add_argument("--max-rounds", type=int, default=150)
ap.add_argument("--effort", default="medium")
ap.add_argument("--temperature", type=float, default=0.0)
ap.add_argument("--engine-log", default="")
ap.add_argument("--stack-meta", default="")
ap.add_argument("--active-dir", default="", help="directory in which the workspace lives while Codex runs (moved into the cell afterwards)")
a = ap.parse_args()
cell = os.path.abspath(a.cell_dir)
if os.path.exists(os.path.join(cell, "cell.json")):
print("refusing: %s already holds a finished cell" % cell, file=sys.stderr)
return 3
# --- the task files must be byte-identical to the frozen manifest
problems = taskfile.check(a.tasks_root, [a.task])
if problems:
print("refusing to start: task %s differs from MANIFEST.sha256:\n %s" % (a.task, "\n ".join(problems[:10])), file=sys.stderr)
return 3
meta = taskfile.read_task(a.tasks_root, a.task)
prompt = meta["prompt"]
tdir = os.path.join(a.tasks_root, a.task)
os.makedirs(cell, exist_ok=True)
final_ws = os.path.join(cell, "workspace")
active = os.path.abspath(a.active_dir) if a.active_dir else cell
ws = os.path.join(active, "ws") if a.active_dir else final_ws
if os.path.exists(ws) or os.path.exists(final_ws):
print("refusing: workspace exists", file=sys.stderr)
return 3
os.makedirs(active, exist_ok=True)
seed = os.path.join(tdir, "seed")
if os.path.isdir(seed):
copy_tree(seed, ws)
else:
os.makedirs(ws)
for rel, sha, _n in meta["externals"]:
src = os.path.join(a.tasks_root, "_external", rel)
if not os.path.isfile(src) or taskfile.sha256_file(src) != sha:
print("refusing: external seed file %s missing or differs (%s)" % (rel, src), file=sys.stderr)
shutil.rmtree(ws, ignore_errors=True)
return 3
shutil.copyfile(src, os.path.join(ws, rel))
want = [l for l in open(os.path.join(a.tasks_root, "MANIFEST.sha256")).read().splitlines() if l.startswith("SEEDTREE %s " % a.task)]
have = taskfile.tree_digest(taskfile.workspace_lines(ws))
if not want or want[0].split()[2] != have:
print("refusing: the installed workspace digest %s differs from the manifest (%s)" % (have, want), file=sys.stderr)
shutil.rmtree(ws, ignore_errors=True)
return 3
seed_digest = have
with open(os.path.join(cell, "prompt.txt"), "w", encoding="utf-8", newline="") as f:
f.write(prompt)
# --- Codex home with the config (same template for all variants; the model name Codex sees is fixed)
port = free_port()
chome = os.path.join(cell, "codex-home")
os.makedirs(chome, mode=0o700)
tmpl = open(os.path.join(HERE, "..", "config.toml.tmpl"), encoding="utf-8").read()
cfg = tmpl.replace("@MODEL@", "qwen-local").replace("@BASE_URL@", "http://127.0.0.1:%d" % port).replace("@EFFORT@", a.effort)
open(os.path.join(chome, "config.toml"), "w", encoding="utf-8").write(cfg)
# --- logging proxy
pdir = os.path.join(cell, "proxy")
os.makedirs(pdir)
perr = open(os.path.join(cell, "proxy.err"), "w")
proxy = subprocess.Popen([sys.executable, os.path.join(HERE, "logproxy.py"), "--listen", "127.0.0.1:%d" % port, "--upstream", a.upstream,
"--out", pdir, "--temperature", str(a.temperature), "--model-map", "qwen-local=" + a.upstream_model,
"--max-rounds", str(a.max_rounds)], stdout=perr, stderr=perr)
for _ in range(100):
try:
socket.create_connection(("127.0.0.1", port), timeout=0.2).close()
break
except OSError:
time.sleep(0.1)
elog_start = os.path.getsize(a.engine_log) if a.engine_log and os.path.exists(a.engine_log) else 0
env = dict(os.environ)
env.update({"CODEX_HOME": chome})
if "E2E_API_KEY" not in env:
env["E2E_API_KEY"] = "none"
cmd = [a.codex_bin, "exec", "--json", "--skip-git-repo-check", "-C", ws, prompt]
t0 = time.time()
start_utc = utc()
events = open(os.path.join(cell, "codex-events.jsonl"), "w", encoding="utf-8", buffering=1)
errf = open(os.path.join(cell, "codex.err"), "w")
p = subprocess.Popen(cmd, cwd=ws, env=env, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=errf, start_new_session=True)
final_msg = {"text": ""}
def reader():
for raw in p.stdout:
line = raw.decode("utf-8", errors="replace").rstrip("\n")
tms = int(time.time() * 1000)
try:
d = json.loads(line)
if isinstance(d, dict):
d["t_unix_ms"] = tms
it = d.get("item") or {}
if d.get("type") == "item.completed" and it.get("type") == "agent_message":
final_msg["text"] = it.get("text") or ""
line = json.dumps(d, separators=(",", ":"))
else:
line = json.dumps({"t_unix_ms": tms, "value": d})
except ValueError:
line = json.dumps({"t_unix_ms": tms, "raw": line})
events.write(line + "\n")
th = threading.Thread(target=reader, daemon=True)
th.start()
termination = "exited"
cap_path = os.path.join(pdir, "cap.reached")
while True:
rc = p.poll()
if rc is not None:
break
if time.time() - t0 > a.wall_limit:
termination = "wall_limit"
elif os.path.exists(cap_path):
termination = "round_cap"
if termination != "exited":
try:
os.killpg(p.pid, signal.SIGTERM)
except OSError:
pass
for _ in range(20):
if p.poll() is not None:
break
time.sleep(0.5)
if p.poll() is None:
try:
os.killpg(p.pid, signal.SIGKILL)
except OSError:
pass
rc = p.wait()
break
time.sleep(0.5)
th.join(timeout=10)
wall = time.time() - t0
end_utc = utc()
events.close()
errf.close()
# a stray child of the agent (a server it started) must not outlive the cell
try:
os.killpg(p.pid, signal.SIGKILL)
except OSError:
pass
time.sleep(1)
proxy.terminate()
try:
proxy.wait(10)
except subprocess.TimeoutExpired:
proxy.kill()
perr.close()
if a.engine_log and os.path.exists(a.engine_log):
with open(a.engine_log, "rb") as f:
f.seek(elog_start)
data = f.read()
with open(os.path.join(cell, "engine-slice.log"), "wb") as f:
f.write(data)
if ws != final_ws:
shutil.move(ws, final_ws)
ws = final_ws
# --- objective acceptance (on the final workspace; the script copies it first)
acc_rc = -1
try:
r = subprocess.run([sys.executable, os.path.join(tdir, "accept.py"), ws], capture_output=True, text=True, timeout=900)
acc_rc = r.returncode
open(os.path.join(cell, "acceptance.log"), "w", encoding="utf-8").write(r.stdout + ("\n--- stderr ---\n" + r.stderr if r.stderr.strip() else ""))
except subprocess.TimeoutExpired:
open(os.path.join(cell, "acceptance.log"), "w").write("acceptance timed out\n")
open(os.path.join(cell, "acceptance.rc"), "w").write("%d\n" % acc_rc)
open(os.path.join(cell, "workspace.sha256"), "w").write("\n".join(taskfile.workspace_lines(ws)) + "\n")
stack = {}
if a.stack_meta and os.path.exists(a.stack_meta):
stack = json.load(open(a.stack_meta))
info = {"variant": a.variant, "task": a.task, "rep": a.rep, "start_utc": start_utc, "end_utc": end_utc, "wall_s": round(wall, 1),
"codex_rc": rc, "termination": termination, "accepted": acc_rc == 0, "acceptance_rc": acc_rc,
"wall_limit_s": a.wall_limit, "max_rounds_cap": a.max_rounds, "effort": a.effort, "temperature_injected": a.temperature,
"prompt_sha256": taskfile.sha256_text(prompt), "seed_digest": seed_digest, "codex_bin": a.codex_bin, "codex_sha256": a.codex_sha256,
"upstream": a.upstream, "upstream_model": a.upstream_model, "engine_log_start_offset": elog_start, "active_workspace": os.path.join(active, "ws") if a.active_dir else final_ws,
"tasks_manifest_sha256": taskfile.sha256_file(os.path.join(a.tasks_root, "MANIFEST.sha256")),
"final_message_tail": final_msg["text"][-800:], "stack": stack}
tmp = os.path.join(cell, "cell.json.part")
json.dump(info, open(tmp, "w"), indent=1)
os.replace(tmp, os.path.join(cell, "cell.json"))
print("cell %s %s r%d: codex_rc=%s %s wall=%.0fs accepted=%s" % (a.variant, a.task, a.rep, rc, termination, wall, acc_rc == 0), flush=True)
return 0
if __name__ == "__main__":
sys.exit(main())