#!/usr/bin/env python3 """Relay v4 end-to-end test (local disk persist, no external network). Covers: 1. boot; /health reports schema 4; runner key rejected on agent endpoints (401) 2. batch with matrix (2 platforms x 2 runtimes x 2 stdin cases) -> 8 cells, ONE batch_id 3. REAL linux runner (tools/runner/worker.py subprocess, RUNNER_LOCAL_URL — no cloudflared in tests) claims the 4 linux cells by PUSH (zero polls), executes them for real, and uploads outputs/hello.txt artifacts 4. artifact round-trip: agent downloads bytes; sha256 matches the result metadata 5. crash recovery: cell pushed to a black-hole intake (claims, never reports), relay SIGKILLed, reboot -> cell requeued -> completed by a real worker 6. supersede: re-register same worker_id with a new url -> old intake gets /shutdown 7. consume batch -> status complete, remaining 0 8. pull mode: worker registers pull:// (no inbound tunnel), claims via /worker/next, executes, reports, batch complete 9. hybrid mode: tunnel push + gentle puller backstop in one worker — batch completes 10. multi-tunnel failover: relay registered urls=[dead, black-hole]; push lands on the second tunnel; /worker/result accepted from any registered url 11. duplicate /job delivery to the intake is executed exactly once (5s-sleep cell) 12. duplicate /worker/result on a completed cell -> 200 already_recorded; batch counts once 13. duplicate /worker/artifact (same job+path+sha256) -> same artifact_id, no second .bin """ import hashlib import json import os import shutil import signal import subprocess import sys import threading import time import urllib.error import urllib.request from pathlib import Path from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer REPO = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")) PORT = 8795 BASE = f"http://127.0.0.1:{PORT}/dataset_verification" PERSIST_DIR = "/tmp/relay_v4_test" LINUX_PORT = 8801 LINUX2_PORT = 8803 BH_WIN_PORT = 8812 BH_CRASH_PORT = 8810 BH_SUPER_PORT = 8811 BH_FAIL_PORT = 8813 HYBRID_PORT = 8814 DUPE_PORT = 8815 BH_DUPE2_PORT = 8816 ENV = dict(os.environ, PERSIST_DIR=PERSIST_DIR, RUNNER_API_KEY="runner-key", AGENT_API_KEY="agent-key", PUSH_URL_HOST_SUFFIX="*", RETENTION_SECONDS="10800") SPACE_DIR = os.path.join(os.path.dirname(__file__), "..") def req(method, path, body=None, key="agent-key", query="", raw=False, timeout=15): from urllib.parse import quote data = body if isinstance(body, (bytes, type(None))) else json.dumps(body).encode() if query: query = "&".join( f"{k}={quote(v, safe='')}" for k, v in (p.split("=", 1) for p in query.split("&") if p)) r = urllib.request.Request(BASE + path + (("?" + query) if query else ""), data=data, method=method) if key: r.add_header("Authorization", f"Bearer {key}") if not raw: r.add_header("Content-Type", "application/json") with urllib.request.urlopen(r, timeout=timeout) as resp: payload = resp.read() return (resp.status, payload, dict(resp.headers)) if raw else json.loads(payload.decode() or "{}") def boot(): proc = subprocess.Popen([sys.executable, "-m", "uvicorn", "main:app", "--host", "127.0.0.1", "--port", str(PORT)], cwd=SPACE_DIR, env=ENV, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) for _ in range(60): try: urllib.request.urlopen(f"http://127.0.0.1:{PORT}/dataset_verification/health", timeout=1) return proc except Exception: time.sleep(0.5) proc.kill() raise RuntimeError("boot failed") def start_worker(name, runner_id, runner_os, port, tags="python-3.11,python-3.12"): env = dict(os.environ, RELAY_URL=BASE, RUNNER_API_KEY="runner-key", RUNNER_ID=str(runner_id), RUNNER_OS=runner_os, RUNTIME_TAGS=tags, RUNNER_PORT=str(port), RUNNER_LOCAL_URL=f"http://127.0.0.1:{port}", RUNNER_MODE="push", MAX_CONCURRENT_JOBS="4", RUNNER_LIFETIME_SECONDS="240", BASE_VENV_DIR="/tmp/relay_v4_novenv") logf = open(f"/tmp/relay_v4_{name}.log", "w") return subprocess.Popen([sys.executable, os.path.join(REPO, "tools", "runner", "worker.py")], env=env, cwd=REPO, stdout=logf, stderr=subprocess.STDOUT) def start_worker_hybrid(name, runner_id, runner_os, port, tags="python-3.12"): env = dict(os.environ, RELAY_URL=BASE, RUNNER_API_KEY="runner-key", RUNNER_ID=str(runner_id), RUNNER_OS=runner_os, RUNTIME_TAGS=tags, RUNNER_PORT=str(port), RUNNER_LOCAL_URL=f"http://127.0.0.1:{port}", RUNNER_MODE="hybrid", RUNNER_POLL_SECONDS="2", MAX_CONCURRENT_JOBS="2", RUNNER_LIFETIME_SECONDS="240", RUNNER_IDLE_TIMEOUT_SECONDS="120", BASE_VENV_DIR="/tmp/relay_v4_novenv") logf = open(f"/tmp/relay_v4_{name}.log", "w") return subprocess.Popen([sys.executable, os.path.join(REPO, "tools", "runner", "worker.py")], env=env, cwd=REPO, stdout=logf, stderr=subprocess.STDOUT) def start_worker_pull(name, runner_id, runner_os, tags="python-3.12"): env = dict(os.environ, RELAY_URL=BASE, RUNNER_API_KEY="runner-key", RUNNER_ID=str(runner_id), RUNNER_OS=runner_os, RUNTIME_TAGS=tags, RUNNER_MODE="pull", RUNNER_POLL_SECONDS="1", MAX_CONCURRENT_JOBS="2", RUNNER_LIFETIME_SECONDS="240", RUNNER_IDLE_TIMEOUT_SECONDS="120", BASE_VENV_DIR="/tmp/relay_v4_novenv") logf = open(f"/tmp/relay_v4_{name}.log", "w") return subprocess.Popen([sys.executable, os.path.join(REPO, "tools", "runner", "worker.py")], env=env, cwd=REPO, stdout=logf, stderr=subprocess.STDOUT) class BlackHole: """Accepts /job (202) and /shutdown (200) with correct auth, records posts, never runs cells.""" def __init__(self, port): self.records = [] outer = self class Handler(BaseHTTPRequestHandler): protocol_version = "HTTP/1.1" def log_message(self, *a): pass def _json(self, code, obj): body = json.dumps(obj).encode() self.send_response(code) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(body))) self.end_headers(); self.wfile.write(body) def do_GET(self): self._json(401, {"detail": "auth required"}) def do_POST(self): length = int(self.headers.get("Content-Length", "0")) self.rfile.read(length) if self.headers.get("Authorization") != "Bearer runner-key": return self._json(401, {"detail": "Unauthorized"}) path = self.path.rstrip("/") outer.records.append(path) if path == "/job": return self._json(202, {"accepted": True}) if path == "/shutdown": return self._json(200, {"draining": True}) self._json(404, {"detail": "not found"}) self.server = ThreadingHTTPServer(("127.0.0.1", port), Handler) self.server.daemon_threads = True threading.Thread(target=self.server.serve_forever, daemon=True).start() def stop(self): try: self.server.shutdown() except Exception: pass def wait_for(predicate, timeout_s, what, interval=1.0): deadline = time.time() + timeout_s while time.time() < deadline: if predicate(): return True time.sleep(interval) raise RuntimeError(f"timeout waiting for: {what}") def header_ci(headers, name): for k, v in headers.items(): if k.lower() == name.lower(): return v return None def main(): shutil.rmtree(PERSIST_DIR, ignore_errors=True) ok = [] proc = boot() print("1. booted") health = json.load(urllib.request.urlopen(f"http://127.0.0.1:{PORT}/dataset_verification/health", timeout=5)) assert health["schema"] == 4, f"schema must be 4, got {health}" try: req("GET", "/desktop/status", key="runner-key") assert False, "runner key must not read agent endpoints" except urllib.error.HTTPError as e: assert e.code == 401 ok.append("boot + schema 4 + audience-scoped keys") batch = { "batch_id": "batch_v4_e2e0001", "jobs": [{ "job_id": "job_matrix1", "platform": "linux", "runtime": "python-3.12", "files": {"main.py": "import pathlib, sys\n" "pathlib.Path('outputs').mkdir(exist_ok=True)\n" "pathlib.Path('outputs/hello.txt').write_text('hello-linux')\n" "print('ok', sys.version_info[0], sys.version_info[1])\n", "common.txt": "base-content"}, "files_variants": {"windows": {"main.py": "import pathlib\npathlib.Path('outputs').mkdir(exist_ok=True)\n" "pathlib.Path('outputs/hello.txt').write_text('hello-windows')\n" "print('ok win')\n"}}, "steps": [{"name": "run", "entry_point": "python main.py", "timeout": 120}], "matrix": {"platforms": ["linux", "windows"], "runtimes": ["python-3.11", "python-3.12"], "stdin_cases": ["a\n", "b b b\n"]}, }], } b = req("POST", "/desktop/batch", batch) assert b["job_count"] == 8 and b["batch_id"] == "batch_v4_e2e0001" ok.append("matrix expansion 8 cells, one batch_id") worker1 = start_worker("linux1", 1, "linux", LINUX_PORT) worker2 = None try: wait_for(lambda: req("GET", "/desktop/batch/batch_v4_e2e0001")["completed_job_count"] >= 4, 120, "linux cells complete via push", interval=2.0) b_now = req("GET", "/desktop/batch/batch_v4_e2e0001") linux_cells = [r for r in b_now["results"] if r["platform"] == "linux"] assert all(r["status"] == "complete" for r in linux_cells) assert all(r["result"]["category"] == "success" for r in linux_cells) art_ref = next((r["result"]["artifacts"][0] for r in linux_cells if r["result"].get("artifacts")), None) assert art_ref, "linux cells must upload outputs/hello.txt" code, data, headers = req("GET", f"/desktop/artifact/{art_ref['artifact_id']}", raw=True) assert code == 200 and hashlib.sha256(data).hexdigest() == art_ref["sha256"] assert data.decode().startswith("hello-linux") assert header_ci(headers, "X-Artifact-SHA256") == art_ref["sha256"] ok.append("linux runner pushed cells (no polls), executed, artifact byte-exact") # ---- windows cells: black-hole claims by push; test reports results over HTTP ---- bh_win = BlackHole(BH_WIN_PORT) req("POST", "/worker/register", {"worker_id": 9, "url": f"http://127.0.0.1:{BH_WIN_PORT}", "environment": {"platform": "windows", "os_version": "windows-latest", "runtimes": ["python-3.11", "python-3.12"], "max_concurrent_jobs": 4}}, key="runner-key") wait_for(lambda: all(r["status"] == "claimed" for r in req("GET", "/desktop/batch/batch_v4_e2e0001")["results"] if r["platform"] == "windows"), 30, "windows cells claimed by push", interval=1.0) for r in req("GET", "/desktop/batch/batch_v4_e2e0001")["results"]: if r["platform"] == "windows" and r["status"] == "claimed": req("POST", "/worker/result", {"job_id": r["job_id"], "exit_code": 0, "timed_out": False, "category": "success", "steps": [{"name": "run", "stdout": "ok win", "stderr": "", "exit_code": 0, "timed_out": False}], "filesystem_state": None, "artifacts": []}, key="runner-key", query=f"worker_id=9&url=http://127.0.0.1:{BH_WIN_PORT}") fin = req("GET", "/desktop/batch/batch_v4_e2e0001", query="consume=true") assert fin["status"] == "complete" and fin["remaining"] == 0 bh_win.stop() ok.append("windows cells claim/result path + batch consume") # ---- crash recovery ---- # quiesce the linux runner first so ONLY the black-hole can claim the crash cell worker1.terminate() try: worker1.wait(timeout=30) except subprocess.TimeoutExpired: worker1.kill() crash = { "batch_id": "batch_v4_crash", "jobs": [{"job_id": "job_crash1", "platform": "linux", "runtime": "python-3.12", "files": {"main.py": "print('crash-test')\n"}, "entry_point": "python main.py", "timeout": 60}]} req("POST", "/desktop/batch", crash) bh_crash = BlackHole(BH_CRASH_PORT) req("POST", "/worker/register", {"worker_id": 10, "url": f"http://127.0.0.1:{BH_CRASH_PORT}", "environment": {"platform": "linux", "os_version": "ubuntu", "runtimes": ["python-3.12"], "max_concurrent_jobs": 1}}, key="runner-key") wait_for(lambda: req("GET", "/desktop/batch/batch_v4_crash")["results"][0]["status"] == "claimed", 30, "crash cell claimed by black-hole", interval=1.0) proc.send_signal(signal.SIGKILL) proc.wait() bh_crash.stop() print(" [crash] relay SIGKILLed with cell claimed; rebooting") proc = boot() wait_for(lambda: req("GET", "/desktop/batch/batch_v4_crash")["results"][0]["status"] == "queued", 30, "crash cell requeued after reboot", interval=1.0) worker2 = start_worker("linux2", 11, "linux", LINUX2_PORT, tags="python-3.12") try: wait_for(lambda: req("GET", "/desktop/batch/batch_v4_crash")["status"] == "complete", 120, "crash cell completed after recovery", interval=2.0) ok.append("crash -> requeue -> recovered & completed") finally: worker2.terminate() # ---- supersede sends /shutdown to the old generation ---- bh_sup = BlackHole(BH_SUPER_PORT) req("POST", "/worker/register", {"worker_id": 99, "url": f"http://127.0.0.1:{BH_SUPER_PORT}", "environment": {"platform": "linux", "os_version": "ubuntu", "runtimes": ["python-3.12"], "max_concurrent_jobs": 1}}, key="runner-key") req("POST", "/worker/register", {"worker_id": 99, "url": "http://127.0.0.1:9", "environment": {"platform": "linux", "os_version": "ubuntu", "runtimes": ["python-3.12"], "max_concurrent_jobs": 1}}, key="runner-key") wait_for(lambda: "/shutdown" in bh_sup.records, 10, "superseded generation receives /shutdown", interval=0.5) bh_sup.stop() ok.append("supersede -> /shutdown pushed to old generation") # ---- pull mode: no tunnel, claims via /worker/next ---- req("POST", "/desktop/batch", {"batch_id": "batch_v4_pull", "jobs": [{"job_id": "job_pull1", "platform": "linux", "runtime": "python-3.12", "files": {"main.py": "print('pull-ok')\n"}, "entry_point": "python main.py", "timeout": 60}]}) pull_worker = start_worker_pull("pull1", 21, "linux", tags="python-3.12") try: wait_for(lambda: req("GET", "/desktop/batch/batch_v4_pull")["status"] == "complete", 120, "pull-mode cell completed", interval=2.0) ok.append("pull mode: /worker/next claim -> execute -> result -> complete") finally: pull_worker.terminate() try: pull_worker.wait(timeout=15) except Exception: pull_worker.kill() # ---- hybrid mode: push primary + gentle pull backstop in one worker ---- req("POST", "/desktop/batch", {"batch_id": "batch_v4_hybrid", "jobs": [{"job_id": "job_hybrid1", "platform": "linux", "runtime": "python-3.12", "files": {"main.py": "print('hybrid-ok')\n"}, "entry_point": "python main.py", "timeout": 60}]}) hybrid_worker = start_worker_hybrid("hybrid1", 31, "linux", HYBRID_PORT, tags="python-3.12") try: wait_for(lambda: req("GET", "/desktop/batch/batch_v4_hybrid")["status"] == "complete", 120, "hybrid-mode cell completed", interval=2.0) ok.append("hybrid mode: tunnel push + pull backstop coexist; batch complete") finally: hybrid_worker.terminate() try: hybrid_worker.wait(timeout=15) except Exception: hybrid_worker.kill() # ---- multi-tunnel failover + result from a non-primary registered url ---- req("POST", "/desktop/batch", {"batch_id": "batch_v4_failover", "jobs": [{"job_id": "job_failover1", "platform": "linux", "runtime": "python-3.12", "files": {"main.py": "print('failover-ok')\n"}, "entry_point": "python main.py", "timeout": 60}]}) bh_fail = BlackHole(BH_FAIL_PORT) req("POST", "/worker/register", {"worker_id": 41, "url": "http://127.0.0.1:9", "urls": ["http://127.0.0.1:9", f"http://127.0.0.1:{BH_FAIL_PORT}"], "environment": {"platform": "linux", "os_version": "ubuntu", "runtimes": ["python-3.12"], "max_concurrent_jobs": 1}}, key="runner-key") wait_for(lambda: "/job" in bh_fail.records, 30, "push failed over from dead primary tunnel to second tunnel", interval=1.0) cell_id = req("GET", "/desktop/batch/batch_v4_failover")["results"][0]["job_id"] req("POST", "/worker/result", {"job_id": cell_id, "exit_code": 0, "timed_out": False, "category": "success", "steps": [{"name": "run", "stdout": "failover-ok", "stderr": "", "exit_code": 0, "timed_out": False}], "filesystem_state": None, "artifacts": []}, key="runner-key", query=f"worker_id=41&url=http://127.0.0.1:{BH_FAIL_PORT}") fin3 = req("GET", "/desktop/batch/batch_v4_failover", query="consume=true") assert fin3["status"] == "complete" bh_fail.stop() ok.append("multi-tunnel failover: push over 2nd tunnel; result accepted from 2nd url") # ---- duplicate /job delivery executes exactly once ---- counter_file = Path("/tmp/relay_v4_dupe_counter.txt") counter_file.unlink(missing_ok=True) dupe_worker = start_worker("dupe1", 51, "linux", DUPE_PORT, tags="python-3.12") dupe_body = { "job_id": "job_dupe1#linux/python-3.12", "platform": "linux", "runtime": "python-3.12", "files": {"main.py": "import time, pathlib\n" "time.sleep(5)\n" "p = pathlib.Path('/tmp/relay_v4_dupe_counter.txt')\n" "p.write_text((p.read_text() if p.exists() else '') + 'x\\n')\n"}, "steps": [{"name": "run", "entry_point": "python main.py", "timeout": 60}]} try: time.sleep(2.0) # let the dev worker register and open its intake statuses = [] duplicates = [] for _ in range(2): data = json.dumps(dupe_body).encode() r = urllib.request.Request(f"http://127.0.0.1:{DUPE_PORT}/job", data=data, method="POST") r.add_header("Authorization", "Bearer runner-key") r.add_header("Content-Type", "application/json") with urllib.request.urlopen(r, timeout=10) as resp: body = json.loads(resp.read()) statuses.append(resp.status) duplicates.append(bool(body.get("duplicate"))) assert statuses == [202, 202], statuses assert duplicates == [False, True], f"expected second delivery flagged duplicate, got {duplicates}" time.sleep(8.0) # cell sleeps 5s, then writes the counter assert counter_file.exists() assert counter_file.read_text() == "x\n", ( f"cell executed more than once: {counter_file.read_text()!r}") ok.append("duplicate /job delivery: executed exactly once") finally: dupe_worker.terminate() try: dupe_worker.wait(timeout=15) except Exception: dupe_worker.kill() counter_file.unlink(missing_ok=True) # ---- duplicate /worker/result on a completed cell -> already_recorded ---- # the leg-10 failover worker (id 41) is long dead but still registered with a # lower worker_id than our new claimant and would shadow every push until it # burns max_push_failures — retire it first, as a superseded generation would req("POST", "/worker/done", {"worker_id": 41, "url": "http://127.0.0.1:9"}, key="runner-key") req("POST", "/desktop/batch", {"batch_id": "batch_v4_dupe2", "jobs": [{"job_id": "job_dupe2", "platform": "linux", "runtime": "python-3.12", "files": {"main.py": "print('dupe2-ok')\n"}, "entry_point": "python main.py", "timeout": 60}]}) bh_dupe2 = BlackHole(BH_DUPE2_PORT) req("POST", "/worker/register", {"worker_id": 52, "url": "http://127.0.0.1:9", "urls": ["http://127.0.0.1:9", f"http://127.0.0.1:{BH_DUPE2_PORT}"], "environment": {"platform": "linux", "os_version": "ubuntu", "runtimes": ["python-3.12"], "max_concurrent_jobs": 1}}, key="runner-key") wait_for(lambda: "/job" in bh_dupe2.records, 30, "dupe2 cell pushed via failover", interval=1.0) cell_id2 = req("GET", "/desktop/batch/batch_v4_dupe2")["results"][0]["job_id"] result_body = {"job_id": cell_id2, "exit_code": 0, "timed_out": False, "category": "success", "steps": [{"name": "run", "stdout": "dupe2-ok", "stderr": "", "exit_code": 0, "timed_out": False}], "filesystem_state": None, "artifacts": []} first = req("POST", "/worker/result", result_body, key="runner-key", query=f"worker_id=52&url=http://127.0.0.1:{BH_DUPE2_PORT}") second = req("POST", "/worker/result", result_body, key="runner-key", query=f"worker_id=52&url=http://127.0.0.1:{BH_DUPE2_PORT}") assert first["status"] == "recorded", first assert second["status"] == "already_recorded", second b2 = req("GET", "/desktop/batch/batch_v4_dupe2") assert b2["completed_job_count"] == 1 and b2["job_count"] == 1 # ---- duplicate /worker/artifact -> same artifact_id ---- art_payload = b"dupe-artifact-bytes-\x00\x01\x02" from urllib.parse import urlencode def put_artifact(): q = urlencode({"job_id": cell_id2, "batch_id": "batch_v4_dupe2", "path": "outputs/dupe.bin", "kind": "file"}) r = urllib.request.Request(f"{BASE}/worker/artifact?{q}", data=art_payload, method="POST") r.add_header("Authorization", "Bearer runner-key") with urllib.request.urlopen(r, timeout=15) as resp: return json.loads(resp.read()) a1 = put_artifact() a2 = put_artifact() assert a1["artifact_id"] == a2["artifact_id"], (a1["artifact_id"], a2["artifact_id"]) ok.append("duplicate /worker/artifact -> same artifact_id, no second .bin") fin4 = req("GET", "/desktop/batch/batch_v4_dupe2", query="consume=true") assert fin4["status"] == "complete" bh_dupe2.stop() ok.append("duplicate /worker/result -> already_recorded; batch counted once") fin2 = req("GET", "/desktop/batch/batch_v4_crash", query="consume=true") assert fin2["status"] == "complete" finally: try: worker1.terminate() except Exception: pass if worker2 is not None: try: worker2.terminate() except Exception: pass try: proc.terminate() proc.wait(timeout=10) except Exception: pass print("PASS:", " | ".join(ok)) return 0 if __name__ == "__main__": sys.exit(main())