393 lines
24 KiB
Python
393 lines
24 KiB
Python
#!/usr/bin/env python3
|
|
"""End-to-end test for the orch binary with a fake hx. Run: python3 tests/e2e.py [path/to/orch]"""
|
|
import json, os, pathlib, shutil, signal, subprocess, sys, tempfile, time
|
|
|
|
root = pathlib.Path(__file__).resolve().parent.parent
|
|
orch = sys.argv[1] if len(sys.argv) > 1 else str(root / "target/debug/orch")
|
|
tmp = pathlib.Path(tempfile.mkdtemp())
|
|
# hermetic provider mode: no `claude` binary, whatever the host has (a host with claude in PATH would be claude_cli)
|
|
env = {**os.environ, "HX_CLAUDE_BIN": "/nonexistent/claude", "ORCH_CONFIG_DIR": str(tmp / "cfg"), "ORCH_STATE_DIR": str(tmp / "state")}
|
|
repo = tmp / "repo"
|
|
repo.mkdir()
|
|
subprocess.run(["git", "init", "-q", "-b", "main"], cwd=repo, check=True)
|
|
subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "--allow-empty", "-m", "i"], cwd=repo, check=True)
|
|
(tmp / "cfg/profiles").mkdir(parents=True)
|
|
fake = tmp / "fake_hx.py"
|
|
shutil.copy(root / "tests/fake_hx.py", fake)
|
|
|
|
|
|
def profile(name, extra=""):
|
|
# test knobs pass through the (otherwise cleared) hx environment; the secrets used by the O5 tests do not
|
|
top, _, rest = extra.partition("\n[") if "\n[" in extra else (extra, "", "")
|
|
body = f'hx = "{sys.executable} {fake}"\nenv = ["MODE", "CONC", "PIDFILE", "HX_CLAUDE_BIN"]\n{top}'
|
|
if "env = [" in extra: # profile brings its own env list: merge
|
|
body = body.replace('env = ["MODE", "CONC", "PIDFILE", "HX_CLAUDE_BIN"]\n', "")
|
|
top = top.replace("env = [", 'env = ["MODE", "CONC", "PIDFILE", "HX_CLAUDE_BIN", ')
|
|
body = f'hx = "{sys.executable} {fake}"\n{top}'
|
|
(tmp / f"cfg/profiles/{name}.toml").write_text(body + (f"\n[{rest}" if rest else ""))
|
|
|
|
|
|
def task(name, body):
|
|
f = tmp / f"{name}.md"
|
|
f.write_text(f"# Title {name}\n{body}\n")
|
|
return f
|
|
|
|
|
|
def run(name, profile_name="p", **kw):
|
|
return subprocess.run([orch, "run", str(task(name, kw.pop("body"))), "--repo", str(repo), "--profile", profile_name],
|
|
env={**env, **kw.pop("env", {})}, capture_output=True, text=True, timeout=60)
|
|
|
|
|
|
def status(id):
|
|
return json.loads(subprocess.run([orch, "status", id], env=env, capture_output=True, text=True).stdout)
|
|
|
|
|
|
def check(p, st, reason=None):
|
|
id = p.stdout.split()[0]
|
|
s = status(id)
|
|
assert s["status"] == st and (reason is None or (s["reason"] or "").startswith(reason)), (p.stdout, p.stderr, s, (tmp / "state/runs" / (id + ".log")).read_text()[-1500:])
|
|
return s
|
|
|
|
|
|
profile("p", 'gate = "test -f out.txt || { echo MARKER-GATE-OUT; exit 3; }"\n')
|
|
s = check(run("ok", body="WRITE"), "done")
|
|
ok_id = s["id"]
|
|
assert s["gate_exit"] == 0 and s["input_tokens"] == 100 and s["session"] == "/s.jsonl", s
|
|
assert (s["cache_read_tokens"], s["cache_write_tokens"]) == (1000, 10), s
|
|
assert "out.txt" in subprocess.run(["git", "ls-tree", "--name-only", s["branch"]], cwd=repo, capture_output=True, text=True).stdout
|
|
s = check(run("nowrite", body="NEVERFIX", env={"MODE": "NEVER"}), "needs-human", "gate-failed")
|
|
assert s["attempts"] == 3 and s["gate_exit"] != 0, s # 1 + 2 retries
|
|
assert "MARKER-GATE-OUT" in (tmp / "state/runs" / (s["id"] + ".gate.log")).read_text()
|
|
profile("r", 'gate = "test -f out.txt || { echo MARKER-GATE-OUT; exit 3; }"\nmax_retries = 1\n')
|
|
s = check(run("fixes", "r", body="x"), "done")
|
|
assert s["attempts"] == 2 and s["gate_exit"] == 0 and s["reason"] is None, s
|
|
sent = subprocess.run(["git", "show", s["branch"] + ":retry-prompt.txt"], cwd=repo, capture_output=True, text=True).stdout
|
|
assert "MARKER-GATE-OUT" in sent and "exit 3" in sent, sent # failure log reached hx on the resumed session
|
|
profile("z", 'gate = "false"\nmax_retries = 0\n')
|
|
s = check(run("noretry", "z", body="x"), "needs-human")
|
|
assert s["attempts"] == 1, s
|
|
profile("b", 'gate = "false"\nmax_retries = 2\n[budget]\nmax_turns = 2\n')
|
|
s = check(run("budget-across", "b", body="x"), "failed", "budget:turns") # budget spans attempts
|
|
assert (s["attempts"], s["turns"]) == (3, 3), s # 1 turn per attempt; 3rd turn exceeds 2
|
|
check(run("hxerr", body="FAIL WRITE"), "failed", "hx-failed: boom")
|
|
check(run("nojson", body="NOJSON"), "failed", "hx-failed")
|
|
|
|
profile("t", "[budget]\nwall_secs = 1\n")
|
|
check(run("slow", "t", body="HANG"), "failed", "timeout")
|
|
profile("m", "[budget]\nmax_turns = 2\n")
|
|
check(run("turns", "m", body="TURNS=5"), "failed", "budget:turns")
|
|
# 1160 tokens per turn incl. cache (fresh-only counting would be 150/turn and never reach 2000 in 5 turns)
|
|
profile("k", "[budget]\nmax_tokens = 2000\n")
|
|
s = check(run("tokens", "k", body="TURNS=5"), "failed", "budget:tokens")
|
|
assert s["turns"] == 2 and s["spent_tokens"] == 2320, s
|
|
|
|
# yolo without sandbox is refused at load time
|
|
profile("y", "yolo = true\n")
|
|
assert run("yolo", "y", body="x").returncode != 0
|
|
|
|
# --- sources and sinks (O3) ---
|
|
tasks = tmp / "tasks"
|
|
tasks.mkdir()
|
|
(tasks / "b-ok.md").write_text("# B ok\nWRITE\n")
|
|
(tasks / "a-bad.md").write_text("# A bad\nFAIL\n")
|
|
profile("d", f'repo = "{repo}"\ngate = "test -f out.txt"\n[source]\nkind = "dir"\npath = "{tasks}"\n')
|
|
p = subprocess.run([orch, "pull", "--profile", "d"], env=env, capture_output=True, text=True)
|
|
assert p.returncode == 1, p # one task failed
|
|
assert (tasks / ".done/b-ok.md").exists() and (tasks / ".failed/a-bad.md").exists()
|
|
assert not list((tasks / ".running").glob("*.md"))
|
|
assert "-> branch orch/b-ok-" in p.stdout, p.stdout # default sink = local-branch
|
|
p = subprocess.run([orch, "pull", "--profile", "d"], env=env, capture_output=True, text=True)
|
|
assert p.returncode == 0 and p.stdout == "", p # nothing left
|
|
|
|
ad = tmp / "ad"
|
|
ad.mkdir()
|
|
cmd = f"{sys.executable} {root / 'tests/fake_adapter.py'}"
|
|
profile("c", f'repo = "{repo}"\ngate = "test -f out.txt"\n[source]\nkind = "cmd"\ncommand = "{cmd}"\n[sink]\nkind = "cmd"\ncommand = "{cmd}"\n')
|
|
aenv = {**env, "ADAPTER_DIR": str(ad), "REPO": str(repo)}
|
|
p = subprocess.run([orch, "pull", "--profile", "c"], env=aenv, capture_output=True, text=True)
|
|
assert p.returncode == 1, p
|
|
calls = [json.loads(l) for l in (ad / "calls.log").read_text().splitlines()]
|
|
ops = [(c["op"], c["in"].get("task", {}).get("id")) for c in calls]
|
|
assert ops == [("list", None), ("claim", "t-good"), ("publish", "t-good"), ("report", "t-good"),
|
|
("claim", "t-taken"), ("claim", "t-bad"), ("report", "t-bad")], ops # taken skipped, bad not published
|
|
pub = next(c for c in calls if c["op"] == "publish")["in"]
|
|
assert pub["task"]["number"] == 7, pub # adapter-private field echoed back
|
|
assert pub["run"]["status"] == "done" and pub["run"]["branch"].startswith("orch/t-good-"), pub
|
|
assert "-> http://example/pr/1" in p.stdout, p.stdout
|
|
rep = [c for c in calls if c["op"] == "report"]
|
|
assert [c["in"]["run"]["status"] for c in rep] == ["done", "failed"], rep
|
|
|
|
# broken adapter output: publish error never loses the run; broken list is a hard error
|
|
(ad / "calls.log").unlink()
|
|
p = subprocess.run([orch, "pull", "--profile", "c", "--limit", "1"], env={**aenv, "BREAK": "publish"}, capture_output=True, text=True)
|
|
assert "publish failed" in p.stderr and "publish-failed" in p.stdout, p
|
|
assert subprocess.run([orch, "pull", "--profile", "c"], env={**aenv, "BREAK": "list"}, capture_output=True, text=True).returncode != 0
|
|
profile("u", '[source]\nkind = "ftp"\n')
|
|
assert subprocess.run([orch, "pull", "--profile", "u"], env=env, capture_output=True, text=True).returncode != 0
|
|
|
|
# --- parallel pool, two orch instances, quota (O4) ---
|
|
def conc_max(f):
|
|
cur = best = 0
|
|
for ch in pathlib.Path(f).read_text():
|
|
cur += 1 if ch == "+" else -1
|
|
best = max(best, cur)
|
|
return best, pathlib.Path(f).read_text().count("+")
|
|
|
|
pq = tmp / "pq"
|
|
pq.mkdir()
|
|
for i in range(5):
|
|
(pq / f"t{i}.md").write_text(f"# T{i}\nWRITE SLEEP=0.5\n")
|
|
profile("w", f'repo = "{repo}"\ngate = "test -f out.txt"\nworkers = 2\n[source]\nkind = "dir"\npath = "{pq}"\n')
|
|
conc = tmp / "conc1"
|
|
t0 = time.time()
|
|
p = subprocess.run([orch, "pull", "--profile", "w"], env={**env, "CONC": str(conc)}, capture_output=True, text=True)
|
|
assert p.returncode == 0, p
|
|
assert conc_max(conc) == (2, 5), conc_max(conc) # 5 tasks, never more than 2 at once, and really 2
|
|
assert len(list((pq / ".done").glob("*.md"))) == 5
|
|
|
|
# account cap across profiles/processes: two profiles on one account, max_concurrent = 1 -> strictly serial
|
|
for n in ("x1", "x2"):
|
|
d = tmp / f"q{n}"
|
|
d.mkdir()
|
|
for i in range(2):
|
|
(d / f"{n}-{i}.md").write_text("# T\nWRITE SLEEP=0.4\n")
|
|
profile(n, f'repo = "{repo}"\naccount = "shared"\nworkers = 2\nmax_concurrent = 1\n[source]\nkind = "dir"\npath = "{d}"\n')
|
|
conc = tmp / "conc2"
|
|
ps = [subprocess.Popen([orch, "pull", "--profile", n], env={**env, "CONC": str(conc)}, stdout=subprocess.PIPE, text=True) for n in ("x1", "x2")]
|
|
assert all(x.wait() == 0 for x in ps)
|
|
assert conc_max(conc) == (1, 4), conc_max(conc)
|
|
|
|
# two orch instances on one queue (stateful claims, like a real host): every task runs exactly once
|
|
cd = tmp / "claims"
|
|
cd.mkdir()
|
|
cmd2 = f"{sys.executable} {root / 'tests/fake_adapter.py'}"
|
|
profile("two", f'repo = "{repo}"\nworkers = 2\n[source]\nkind = "cmd"\ncommand = "{cmd2}"\n')
|
|
ad2 = tmp / "ad2"
|
|
ad2.mkdir()
|
|
tenv = {**env, "ADAPTER_DIR": str(ad2), "REPO": str(repo), "LISTN": "6", "CLAIMDIR": str(cd)}
|
|
ps = [subprocess.Popen([orch, "pull", "--profile", "two"], env=tenv, stdout=subprocess.PIPE, text=True) for _ in range(2)]
|
|
outs = [x.communicate()[0] for x in ps]
|
|
ids = [l.split()[0] for o in outs for l in o.splitlines()]
|
|
names = sorted(i.rsplit("-", 1)[0] for i in ids)
|
|
assert names == [f"p{i}" for i in range(6)], names # each task exactly once, none lost
|
|
|
|
# quota: a full window pauses the account; the task is requeued, the rest stays queued; resumes after the window
|
|
qd = tmp / "qd"
|
|
qd.mkdir()
|
|
(qd / "a-quota.md").write_text("# A\nQUOTA RATELIMIT\n")
|
|
(qd / "b-next.md").write_text("# B\nWRITE\n")
|
|
(qd / "c-next.md").write_text("# C\nWRITE\n")
|
|
profile("qp", f'repo = "{repo}"\naccount = "acct-q"\ngate = "test -f out.txt"\n[source]\nkind = "dir"\npath = "{qd}"\n')
|
|
p = subprocess.run([orch, "pull", "--profile", "qp"], env=env, capture_output=True, text=True)
|
|
assert p.returncode == 0, p # requeue is not a failure
|
|
rid = p.stdout.split()[0]
|
|
s = status(rid)
|
|
assert s["status"] == "requeued" and s["reason"].startswith("quota:"), s
|
|
assert sorted(os.listdir(qd)) == [".running", "a-quota.md", "b-next.md", "c-next.md"], os.listdir(qd)
|
|
pause = tmp / "state/locks/pause-acct-q"
|
|
until = int(pause.read_text())
|
|
assert abs(until - (time.time() + 3600)) < 60, until # = the reset time hx reported
|
|
p = subprocess.run([orch, "pull", "--profile", "qp"], env=env, capture_output=True, text=True)
|
|
assert p.stdout == "" and "paused" in p.stderr, p # nothing runs while paused
|
|
pause.write_text(str(int(time.time()) - 1)) # window reset
|
|
(qd / "a-quota.md").write_text("# A\nWRITE\n")
|
|
p = subprocess.run([orch, "pull", "--profile", "qp"], env=env, capture_output=True, text=True)
|
|
assert p.returncode == 0 and p.stdout.count(" done") == 3, p
|
|
# a clean run that saw a full window still pauses the account for the next tasks
|
|
(qd / "d.md").write_text("# D\nQUOTA WRITE\n")
|
|
(qd / "e.md").write_text("# E\nWRITE\n")
|
|
p = subprocess.run([orch, "pull", "--profile", "qp"], env=env, capture_output=True, text=True)
|
|
assert p.stdout.count(" done") == 1 and (qd / "e.md").exists() and "paused" in p.stderr, p
|
|
|
|
# --- safety (O5) ---
|
|
def git_show(branch, path):
|
|
return subprocess.run(["git", "show", f"{branch}:{path}"], cwd=repo, capture_output=True, text=True).stdout
|
|
|
|
private = tmp / "private/.hx"
|
|
private.mkdir(parents=True)
|
|
(private / "auth.json").write_text('{"claude": "PRIVATE-TOKEN-123"}')
|
|
work_home = tmp / "work-home"
|
|
work_home.mkdir()
|
|
senv = {"HX_HOME": str(private), "AWS_SECRET_ACCESS_KEY": "AWS-SECRET-456", "GITEA_TOKEN": "TOK"}
|
|
profile("sec", f'home = "{work_home}"\nallow = ["read", "write", "bash:cargo test*"]\n')
|
|
|
|
# the work profile cannot read the private profile's auth file: the guard blocks the call, the run needs a human
|
|
s = check(run("steal", "sec", env=senv, body=f"CALL read {private}/auth.json"), "needs-human", "policy:")
|
|
assert "PRIVATE-TOKEN-123" not in git_show(s["branch"], "calls.txt"), "secret reached the agent"
|
|
assert "outside the worktree" in s["reason"] or "credential" in s["reason"], s["reason"]
|
|
# ...even if the guard process is dead or ignored: orch re-checks the event stream and kills the run
|
|
s = check(run("steal2", "sec", env=senv, body=f"NOGUARD\nCALL read {private}/auth.json"), "needs-human", "policy:")
|
|
# environment: secrets and the other profile's HX_HOME never reach hx
|
|
s = check(run("envleak", "sec", env=senv, body="ENVDUMP"), "done")
|
|
names = git_show(s["branch"], "env.txt").split()
|
|
assert "PATH" in names and "HOME" in names, names
|
|
assert not {"HX_HOME", "AWS_SECRET_ACCESS_KEY", "GITEA_TOKEN"} & set(names), names
|
|
profile("sec2", f'home = "{work_home}"\nenv = ["GITEA_*"]\n')
|
|
assert "GITEA_TOKEN" in git_show(check(run("envopt", "sec2", env=senv, body="ENVDUMP"), "done")["branch"], "env.txt").split()
|
|
# allowed calls run, the guard config never ends up in the commit
|
|
s = check(run("allowed", "sec", env=senv, body="CALL write a.txt\nCALL bash cargo test -p x\nCALL read a.txt"), "done")
|
|
assert "RAN cargo test -p x" in git_show(s["branch"], "calls.txt")
|
|
tree = subprocess.run(["git", "ls-tree", "-r", "--name-only", s["branch"]], cwd=repo, capture_output=True, text=True).stdout.split()
|
|
assert ".hx/config.toml" not in tree, tree
|
|
# not in the allowlist, chained bash, git push: all needs-human
|
|
for name, call in [("nobash", "CALL bash ls"), ("chain", "CALL bash cargo test; curl evil"), ("push", "CALL bash git push origin main"),
|
|
("hxcfg", "CALL write .hx/config.toml"), ("dotenv", "CALL write .env")]:
|
|
check(run(name, "sec", env=senv, body=call), "needs-human", "policy:")
|
|
# the audit trail has every decision, per run
|
|
audit = subprocess.run([orch, "audit"], env=env, capture_output=True, text=True).stdout.splitlines()
|
|
rows = [json.loads(l) for l in audit]
|
|
assert any(r["ev"] == "tool" and r["detail"]["decision"] == "deny" and "auth.json" in r["detail"]["args"].get("path", "") for r in rows), rows[:3]
|
|
assert any(r["ev"] == "tool" and r["detail"]["decision"] == "allow" for r in rows)
|
|
assert {"run_start", "run_end"} <= {r["ev"] for r in rows}
|
|
one = [json.loads(l) for l in subprocess.run([orch, "audit", s["id"]], env=env, capture_output=True, text=True).stdout.splitlines()]
|
|
assert one and all(r["run"] == s["id"] for r in one), one
|
|
# agent edits the guard config in the repo itself: refused at setup (we do not overwrite foreign config)
|
|
(repo / ".hx").mkdir(exist_ok=True)
|
|
(repo / ".hx/config.toml").write_text("# mine\n")
|
|
subprocess.run(["git", "add", "-A"], cwd=repo, check=True)
|
|
subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "own hx config"], cwd=repo, check=True)
|
|
check(run("foreign", "sec", env=senv, body="CALL read a.txt"), "failed", "setup:")
|
|
subprocess.run(["git", "rm", "-q", "-r", ".hx"], cwd=repo, check=True)
|
|
subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "rm"], cwd=repo, check=True)
|
|
# the guard process alone (no orch kill racing it): block / continue over the extension protocol
|
|
gwt = tmp / "gwt"
|
|
gwt.mkdir()
|
|
pol = {"run": "g", "allow": ["read", "bash:cargo test*"], "worktree": str(gwt.resolve()), "read_roots": [], "audit": str(tmp / "g-audit.log")}
|
|
(tmp / "g.json").write_text(json.dumps(pol))
|
|
g = subprocess.Popen([orch, "guard", str(tmp / "g.json")], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
|
|
def ask(i, method, params):
|
|
g.stdin.write(json.dumps({"jsonrpc": "2.0", "id": i, "method": method, "params": params}) + "\n")
|
|
g.stdin.flush()
|
|
return json.loads(g.stdout.readline())["result"]
|
|
assert ask(1, "initialize", {})["subscribe"] == ["tool_call"]
|
|
ev = lambda n, a: ask(2, "event", {"event": {"type": "tool_call", "name": n, "args": a}})
|
|
assert ev("read", {"path": "x.rs"})["action"] == "continue"
|
|
b = ev("read", {"path": str(private / "auth.json")})
|
|
assert b["action"] == "block" and b["reason"].startswith("orch-guard:"), b
|
|
assert ev("bash", {"command": "cargo test; id"})["action"] == "block"
|
|
assert ev("write", {"path": "x.rs"})["action"] == "block"
|
|
g.stdin.close()
|
|
assert g.wait(timeout=5) == 0
|
|
assert len((tmp / "g-audit.log").read_text().splitlines()) == 4
|
|
|
|
# provider mode is recorded; with `allow` + claude_cli the run is refused instead of running unguarded (#17)
|
|
s = check(run("direct-mode", "sec", env=senv, body="CALL write a.txt"), "done")
|
|
tel = tmp / "state/telemetry.jsonl"
|
|
recs2 = [json.loads(l) for l in tel.read_text().splitlines() if l.strip()]
|
|
assert [r["provider_mode"] for r in recs2 if r["task"] == "direct-mode"] == ["direct"], recs2[-3:]
|
|
fakecl = tmp / "claude"
|
|
fakecl.write_text("#!/bin/sh\n[ \"$1\" = --version ] && echo fake\nexit 0\n")
|
|
fakecl.chmod(0o755)
|
|
cenv = {"HX_CLAUDE_BIN": str(fakecl)} # a claude binary exists => hx would pick claude_cli
|
|
s = check(run("refuse", "sec", env=cenv, body="CALL write a.txt"), "needs-human", "policy: `allow` cannot be enforced")
|
|
assert s["attempts"] == 0 and s["hx_exit"] is None, s # hx was never started
|
|
assert "claude_cli = false" in (tmp / "state/runs" / (s["id"] + ".log")).read_text()
|
|
# explicit opt-out in the profile's hx config => direct, allowed again
|
|
(work_home / ".hx").mkdir(exist_ok=True)
|
|
(work_home / ".hx/config.toml").write_text("claude_cli = false\n")
|
|
check(run("optout", "sec", env=cenv, body="CALL write a.txt"), "done")
|
|
(work_home / ".hx/config.toml").unlink()
|
|
# without `allow` claude_cli runs as before (recorded as claude_cli)
|
|
profile("noallow", f'home = "{work_home}"\n')
|
|
check(run("cli-ok", "noallow", env=cenv, body="WRITE"), "done")
|
|
assert [json.loads(l)["provider_mode"] for l in tel.read_text().splitlines() if l.strip()][-1] == "claude_cli"
|
|
# mode comparison: files from different modes are refused
|
|
fa, fb = tmp / "ma.jsonl", tmp / "mb.jsonl"
|
|
base = next(r for r in recs2 if r["task"] == "ok")
|
|
fa.write_text(json.dumps({**base, "provider_mode": "direct"}) + "\n")
|
|
fb.write_text(json.dumps({**base, "provider_mode": "claude_cli"}) + "\n")
|
|
cmp_ = subprocess.run([orch, "eval", str(fa), str(fb)], env=env, capture_output=True, text=True)
|
|
assert cmp_.returncode == 1 and "NOT COMPARABLE" in cmp_.stdout, cmp_
|
|
assert subprocess.run([orch, "eval", str(fa), str(fa)], env=env, capture_output=True, text=True).returncode == 0
|
|
assert "mode" in subprocess.run([orch, "report", str(fb)], env=env, capture_output=True, text=True).stdout.splitlines()[0]
|
|
|
|
# warning for unrestricted profiles
|
|
assert "no `allow` list" in run("warn", "p", body="WRITE").stderr
|
|
|
|
# --- telemetry, report, eval, bench (O6) ---
|
|
tel = tmp / "state/telemetry.jsonl"
|
|
recs = [json.loads(l) for l in tel.read_text().splitlines() if l.strip()]
|
|
assert len(recs) >= 30, len(recs)
|
|
ok_rec = next(r for r in recs if r["task"] == "ok")
|
|
assert (ok_rec["status"], ok_rec["profile"], ok_rec["hx_version"], ok_rec["input_tokens"], ok_rec["attempts"]) == ("done", "p", "hx 9.9.9", 100, 1), ok_rec
|
|
assert (ok_rec["cache_read_tokens"], ok_rec["cache_write_tokens"]) == (1000, 10), ok_rec
|
|
assert next(r for r in recs if r["task"] == "nowrite")["status"] == "needs-human"
|
|
assert next(r for r in recs if r["task"] == "nowrite")["attempts"] == 3
|
|
assert any(r["status"] == "requeued" for r in recs)
|
|
rep = subprocess.run([orch, "report"], env=env, capture_output=True, text=True).stdout
|
|
assert "hx 9.9.9" in rep and "profile" in rep and rep.splitlines()[-1].startswith("retries"), rep
|
|
assert "cache" in rep.splitlines()[0], rep
|
|
allrow = next(l for l in rep.splitlines() if l.startswith("all"))
|
|
assert allrow.split()[1] == str(len([r for r in recs])), (allrow, len(recs))
|
|
# a half-written line (crash) is skipped and does not hide the next record
|
|
with open(tel, "a") as f:
|
|
f.write('{"ts": 1, "run": "cut')
|
|
run("after-cut", "p", body="WRITE")
|
|
rep2 = subprocess.run([orch, "report"], env=env, capture_output=True, text=True)
|
|
assert "skipped 1 unreadable" in rep2.stderr and rep2.returncode == 0, rep2
|
|
assert len(subprocess.run([orch, "report"], env=env, capture_output=True, text=True).stdout.splitlines()) == len(rep.splitlines()) # same table shape
|
|
|
|
# bench: the shipped eval cases, with a fake hx that solves every case but one
|
|
ev = root / "eval"
|
|
chk = subprocess.run([orch, "bench", str(ev), "--check"], env=env, capture_output=True, text=True)
|
|
assert chk.returncode == 0 and chk.stdout.count("untouched=fail solved=pass") == 4, chk
|
|
profile("bb", f'env = ["SOLVE_DIR", "SOLVE_SKIP", "FAKE_VERSION"]\ngate = "false"\nmax_retries = 0\n')
|
|
a_out, b_out = tmp / "a.jsonl", tmp / "b.jsonl"
|
|
benv = {**env, "SOLVE_DIR": str(ev)}
|
|
pa = subprocess.run([orch, "bench", str(ev), "--profile", "bb", "--out", str(a_out), "--repeat", "2"], env={**benv, "FAKE_VERSION": "1.0"}, capture_output=True, text=True)
|
|
assert pa.returncode == 0, pa # every case solved; the profile gate ("false") is replaced by the case's gate.sh
|
|
pb = subprocess.run([orch, "bench", str(ev), "--profile", "bb", "--out", str(b_out)], env={**benv, "SOLVE_SKIP": "rename-symbol", "FAKE_VERSION": "2.0"}, capture_output=True, text=True)
|
|
assert pb.returncode == 1, pb # one case unsolved -> bench exit 1
|
|
ra, rb = report_load = [[json.loads(l) for l in f.read_text().splitlines() if l.strip()] for f in (a_out, b_out)]
|
|
assert len(ra) == 8 and {r["hx_version"] for r in ra} == {"hx 1.0"} and {r["task"] for r in ra} == {"add-function", "fix-off-by-one", "fix-typo-readme", "rename-symbol"}
|
|
assert [r["status"] for r in rb if r["task"] == "rename-symbol"] == ["needs-human"] and len(rb) == 4
|
|
ev_out = subprocess.run([orch, "eval", str(a_out), str(b_out)], env=env, capture_output=True, text=True)
|
|
assert ev_out.returncode == 1 and "REGRESSION" in ev_out.stdout and "-25 pp" in ev_out.stdout, ev_out
|
|
line = next(l for l in ev_out.stdout.splitlines() if l.startswith("rename-symbol"))
|
|
assert line.split()[1:3] == ["2/2", "0/1"], line
|
|
ev_ok = subprocess.run([orch, "eval", str(b_out), str(a_out)], env=env, capture_output=True, text=True)
|
|
assert ev_ok.returncode == 0 and "REGRESSION" not in ev_ok.stdout and "+25 pp" in ev_ok.stdout, ev_ok # B better than A: no failure
|
|
# a broken case set is caught by --check
|
|
broken = tmp / "broken"
|
|
shutil.copytree(ev, broken)
|
|
(broken / "add-function/solution/text.py").write_text("def slugify(s):\n return s\n")
|
|
bad = subprocess.run([orch, "bench", str(broken), "--check"], env=env, capture_output=True, text=True)
|
|
assert bad.returncode == 1 and "broken case" in bad.stdout, bad
|
|
|
|
# --- no profile file: `default` falls back to built-in defaults, other names still fail ---
|
|
nocfg = {**env, "ORCH_CONFIG_DIR": str(tmp / "no-cfg"), "FAKE_VERSION": "0"}
|
|
(tmp / "bin").mkdir(exist_ok=True)
|
|
hxw = tmp / "bin/hx"
|
|
hxw.write_text(f"#!/bin/sh\nexec {sys.executable} {fake} \"$@\"\n")
|
|
hxw.chmod(0o755)
|
|
nb = subprocess.run([orch, "bench", str(ev), "--case", "fix-typo-readme", "--out", str(tmp / "nb.jsonl")], env={**nocfg, "PATH": f"{tmp / 'bin'}:{os.environ['PATH']}", "SOLVE_DIR": str(ev)}, capture_output=True, text=True)
|
|
assert nb.returncode == 1 and (tmp / "nb.jsonl").exists() and "default.toml" not in nb.stderr, nb # hx ran (unsolved: SOLVE_DIR is filtered from its env), no missing-profile error
|
|
miss = subprocess.run([orch, "bench", str(ev), "--profile", "typo"], env=nocfg, capture_output=True, text=True)
|
|
assert miss.returncode != 0 and "typo.toml" in miss.stderr, miss
|
|
|
|
# kill orch mid-run: status must say interrupted and hx must be dead after the next orch call
|
|
pidfile = tmp / "hx.pid"
|
|
p = subprocess.Popen([orch, "run", str(task("killed", "HANG")), "--repo", str(repo), "--profile", "p"],
|
|
env={**env, "PIDFILE": str(pidfile)}, stdout=subprocess.PIPE, text=True)
|
|
for _ in range(100):
|
|
if pidfile.exists() and pidfile.read_text():
|
|
break
|
|
time.sleep(0.1)
|
|
hx_pid = int(pidfile.read_text())
|
|
p.send_signal(signal.SIGKILL)
|
|
p.wait()
|
|
time.sleep(0.2)
|
|
out = subprocess.run([orch, "status"], env=env, capture_output=True, text=True).stdout
|
|
line = next(l for l in out.splitlines() if l.startswith("killed-"))
|
|
assert "failed" in line and "[interrupted]" in line, out
|
|
time.sleep(0.5)
|
|
try:
|
|
os.kill(hx_pid, 0)
|
|
raise AssertionError("orphan hx still alive")
|
|
except ProcessLookupError:
|
|
pass
|
|
|
|
logs = subprocess.run([orch, "logs", ok_id], env=env, capture_output=True, text=True).stdout
|
|
assert '"type": "done"' in logs or '"type":"done"' in logs, logs
|
|
print("e2e ok")
|