#!/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, 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()) env = {**os.environ, "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" fake.write_text(''' import json, sys, time, os body = sys.argv[sys.argv.index("-p") + 1] e = lambda o: print(json.dumps(o), flush=True) e({"type": "session_start"}) if "NOJSON" in body: sys.exit(1) if "HANG" in body: open(os.environ.get("PIDFILE", "/dev/null"), "w").write(str(os.getpid())) time.sleep(300) conc = os.environ.get("CONC") if "SLEEP=" in body: if conc: open(conc, "a").write("+") time.sleep(float(body.split("SLEEP=")[1].split()[0])) if conc: open(conc, "a").write("-") if "QUOTA" in body: e({"type": "stream", "event": {"type": "quota", "windows": [{"label": "5h", "used_pct": 100.0, "resets_at": int(time.time()) + 3600}], "credits": None}}) for i in range(int(body.split("TURNS=")[1].split()[0]) if "TURNS=" in body else 1): e({"type": "turn_start"}) e({"type": "stream", "event": {"type": "done", "usage": {"input_tokens": 100, "output_tokens": 50}}}) if "WRITE" in body: open("out.txt", "w").write("x") if "--session" in sys.argv: open("retry-prompt.txt", "w").write(body) if "RETRYFIX" in os.environ.get("MODE", "RETRYFIX"): open("out.txt", "w").write("x") e({"type": "done", "error": "api 429: slow down" if "RATELIMIT" in body else "boom" if "FAIL" in body else None, "usage": {"input_tokens": 100, "output_tokens": 50}, "session": "/s.jsonl"}) ''') def profile(name, extra=""): (tmp / f"cfg/profiles/{name}.toml").write_text(f'hx = "{sys.executable} {fake}"\n{extra}') 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) return s profile("p", 'gate = "test -f out.txt || { echo MARKER-GATE-OUT; exit 3; }"\n') s = check(run("ok", body="WRITE"), "done") assert s["gate_exit"] == 0 and s["input_tokens"] == 100 and s["session"] == "/s.jsonl", 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") profile("k", "[budget]\nmax_tokens = 200\n") check(run("tokens", "k", body="TURNS=5"), "failed", "budget:tokens") # 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 # 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", s["id"]], env=env, capture_output=True, text=True).stdout assert '"type": "done"' in logs or '"type":"done"' in logs, logs print("e2e ok")