Files

138 lines
6.8 KiB
Python

#!/usr/bin/env python3
"""Run a list of cells inside ONE running stack (test tooling, stdlib only). Called by block.sh, once the stack is up.
block.py --variant V3 --tag TAG --cells "fixbug-ledger:1 fixbug-ledger:2 smoke-mini:1:_smoke" --runs-root R --tasks-root T
--upstream http://127.0.0.1:8081 --model qwen-iq3|auto --engine-log PATH --expect-skip on|off --stack-dir D
--codex-bin C --wall-limit 2400 --max-rounds 150
A cell token is `task:rep[:set]`; the cell directory is R/[set/]VARIANT/task-rREP. Cells that already hold a cell.json are skipped.
Before the first cell it sends one warm-up request straight to the engine (not part of any cell) and checks that the route tail skip
state the variant is supposed to have is what the engine log says; if not it stops without running a cell.
"""
import argparse
import json
import os
import re
import subprocess
import sys
import time
import urllib.request
HERE = os.path.dirname(os.path.abspath(__file__))
SKIP_ON = re.compile(r"ROUTE_TAIL_SKIP=\d+ is ON|EXPERIMENTAL route tail skip is ON")
SKIP_OFF_OURS = re.compile(r"route tail skip \d+ is OFF")
def post(url, body, key, timeout=900):
req = urllib.request.Request(url, data=json.dumps(body).encode(), headers={"Content-Type": "application/json", "Authorization": "Bearer " + key})
with urllib.request.urlopen(req, timeout=timeout) as r:
return r.status, r.read()
def read_log(path):
try:
return open(path, "r", errors="replace").read()
except OSError:
return ""
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--variant", required=True)
ap.add_argument("--tag", required=True)
ap.add_argument("--cells", required=True)
ap.add_argument("--runs-root", required=True)
ap.add_argument("--tasks-root", required=True)
ap.add_argument("--upstream", required=True)
ap.add_argument("--model", default="auto")
ap.add_argument("--engine-log", required=True)
ap.add_argument("--expect-skip", choices=["on", "off"], required=True)
ap.add_argument("--stack-dir", required=True)
ap.add_argument("--codex-bin", required=True)
ap.add_argument("--wall-limit", type=int, default=2400)
ap.add_argument("--max-rounds", type=int, default=150)
ap.add_argument("--active-dir", required=True)
a = ap.parse_args()
key = os.environ.get("E2E_API_KEY", "none")
model = a.model
if model == "auto":
with urllib.request.urlopen(urllib.request.Request(a.upstream + "/v1/models", headers={"Authorization": "Bearer " + key}), timeout=60) as r:
model = json.loads(r.read())["data"][0]["id"]
blog = open(os.path.join(a.stack_dir, "block.log"), "a", buffering=1)
def say(msg):
line = "%s %s" % (time.strftime("%H:%M:%SZ", time.gmtime()), msg)
print(line, flush=True)
blog.write(line + "\n")
# --- warm-up (graph capture, first-request costs), identical for every variant
t0 = time.time()
body = {"model": model, "input": [{"role": "user", "content": [{"type": "input_text", "text": "Reply with the single word OK."}]}],
"max_output_tokens": 48, "temperature": 0, "stream": False}
try:
st, raw = post(a.upstream + "/v1/responses", body, key)
warm = {"status": st, "seconds": round(time.time() - t0, 1), "reply_bytes": len(raw)}
except Exception as e: # noqa: BLE001
warm = {"status": "error", "error": str(e)[:300]}
say("warm-up: %s" % json.dumps(warm))
time.sleep(2)
log = read_log(a.engine_log)
on_lines = [l for l in log.splitlines() if SKIP_ON.search(l)]
off_lines = [l for l in log.splitlines() if SKIP_OFF_OURS.search(l)]
skip_state = {"expect": a.expect_skip, "on_lines": on_lines[:3], "off_lines": off_lines[:3],
"prefill_cpu_share_lines": [l.strip()[:300] for l in log.splitlines() if "CPU share" in l][:3]}
ok = bool(on_lines) if a.expect_skip == "on" else not on_lines
say("route tail skip check expect=%s: %s" % (a.expect_skip, "OK" if ok else "MISMATCH"))
for l in (on_lines + off_lines)[:3]:
say(" engine log: " + l.strip()[:300])
stack = {}
sp = os.path.join(a.stack_dir, "stack.json")
if os.path.exists(sp):
stack = json.load(open(sp))
stack.update({"variant": a.variant, "tag": a.tag, "upstream_model": model, "warmup": warm, "skip_state": skip_state,
"engine_log": a.engine_log, "block_start_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"uptime_s_at_block": float(open("/proc/uptime").read().split()[0]),
"boot_id": open("/proc/sys/kernel/random/boot_id").read().strip()})
json.dump(stack, open(sp, "w"), indent=1)
if not ok:
say("STOP: the engine log does not show the expected route tail skip state; no cell is run")
open(os.path.join(a.stack_dir, "BLOCK_FAILED"), "w").write("route tail skip state mismatch\n")
return 5
import hashlib
h = hashlib.sha256()
with open(a.codex_bin, "rb") as f:
for chunk in iter(lambda: f.read(1 << 22), b""):
h.update(chunk)
codex_sha = h.hexdigest()
for tok in a.cells.split():
parts = tok.split(":")
task, rep = parts[0], int(parts[1])
sset = parts[2] if len(parts) > 2 else ""
cell_dir = os.path.join(a.runs_root, sset, a.variant, "%s-r%d" % (task, rep))
if os.path.exists(os.path.join(cell_dir, "cell.json")):
say("skip %s (done)" % cell_dir)
continue
if os.path.exists(cell_dir):
garbage = cell_dir + ".incomplete-" + time.strftime("%Y%m%dT%H%M%S", time.gmtime())
os.rename(cell_dir, garbage)
say("renamed an incomplete cell to %s" % garbage)
os.makedirs(os.path.dirname(cell_dir), exist_ok=True)
for leftover in ("ws", "codex-home"):
left = os.path.join(a.active_dir, leftover)
if os.path.exists(left):
moved = os.path.join(a.runs_root, "_incomplete-%s-%s" % (leftover, time.strftime("%Y%m%dT%H%M%S", time.gmtime())))
os.rename(left, moved)
say("moved a leftover active %s to %s" % (leftover, moved))
say("cell %s" % cell_dir)
cmd = [sys.executable, "-I", os.path.join(HERE, "cell.py"), "--cell-dir", cell_dir, "--variant", a.variant, "--task", task, "--rep", str(rep),
"--tasks-root", a.tasks_root, "--upstream", a.upstream, "--upstream-model", model, "--codex-bin", a.codex_bin, "--codex-sha256", codex_sha,
"--wall-limit", str(a.wall_limit), "--max-rounds", str(a.max_rounds), "--engine-log", a.engine_log, "--stack-meta", sp, "--active-dir", a.active_dir]
r = subprocess.run(cmd, capture_output=True, text=True)
say("cell done rc=%d %s %s" % (r.returncode, r.stdout.strip()[-300:], r.stderr.strip()[-300:]))
time.sleep(5)
return 0
if __name__ == "__main__":
sys.exit(main())