Reversible clean-root candidate rebuilt from oak/benchmarks main@009dead264ca; original repository retained.

scripts/cloud_campaign.py in oak/benchmarks

scripts/cloud_campaign.py 126 lines · 5.7 KB · python
1
#!/usr/bin/env python3
2
"""Run one agent campaign in a disposable Cloudflare container and fetch the results.
3
4
The container (cloudflare/agent-runner) plans the campaign, proves containment
5
as the unprivileged agent user, runs the trials, and writes the reports. This
6
driver submits the job, polls it (which also keeps the container awake),
7
downloads the job bundle into results/cloud-campaigns/<job-id>/, and destroys
8
the container.
9
10
  python3 scripts/cloud_campaign.py --manifest config/agent-campaign-smoke.json
11
  python3 scripts/cloud_campaign.py --manifest m.json --enable-real
12
13
Runner URL and token come from ~/.config/oak-bench/agent-runner.{url,token}
14
(or OAK_AGENT_RUNNER_URL / OAK_AGENT_RUNNER_TOKEN). This driver never handles
15
provider credentials: the Worker adds ANTHROPIC_API_KEY from its own secret to
16
real jobs, and the container scrubs the key from the bundle before download.
17
stdlib only (ADR-0001).
18
"""
19
from __future__ import annotations
20
21
import argparse
22
import io
23
import json
24
import os
25
import ssl
26
import sys
27
import tarfile
28
import time
29
import urllib.error
30
import urllib.request
31
from datetime import datetime, timezone
32
from pathlib import Path
33
34
ROOT = Path(__file__).resolve().parents[1]
35
CONFIG_DIR = Path.home() / ".config" / "oak-bench"
36
37
38
def setting(env_name: str, file_name: str) -> str:
39
    value = os.environ.get(env_name)
40
    if value:
41
        return value.strip()
42
    path = CONFIG_DIR / file_name
43
    if not path.is_file():
44
        raise SystemExit(f"missing {env_name} and {path}")
45
    return path.read_text().strip()
46
47
48
def tls_context() -> ssl.SSLContext:
49
    context = ssl.create_default_context()
50
    # python.org macOS builds ship no CA store until "Install Certificates" runs.
51
    for bundle in ("/etc/ssl/cert.pem", "/etc/ssl/certs/ca-certificates.crt"):
52
        if os.path.exists(bundle):
53
            context.load_verify_locations(bundle)
54
    return context
55
56
57
def request(method: str, url: str, token: str, body: dict | None = None, timeout: float = 120) -> tuple[int, bytes]:
58
    data = json.dumps(body).encode() if body is not None else None
59
    req = urllib.request.Request(url, data=data, method=method, headers={
60
        "authorization": f"Bearer {token}", "content-type": "application/json", "user-agent": "oak-bench-cloud-campaign"})
61
    try:
62
        with urllib.request.urlopen(req, timeout=timeout, context=tls_context()) as resp:
63
            return resp.status, resp.read()
64
    except urllib.error.HTTPError as exc:
65
        return exc.code, exc.read()
66
67
68
def main(argv=None) -> int:
69
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
70
    parser.add_argument("--manifest", type=Path, required=True)
71
    parser.add_argument("--job-id", help="default: <campaign_id>-<UTC timestamp>")
72
    parser.add_argument("--enable-real", action="store_true", help="admit real (paid) agent CLIs")
73
    parser.add_argument("--limit", type=int)
74
    parser.add_argument("--out", type=Path, default=ROOT / "results" / "cloud-campaigns")
75
    parser.add_argument("--poll-seconds", type=float, default=30)
76
    parser.add_argument("--keep-container", action="store_true", help="do not destroy the container afterwards")
77
    args = parser.parse_args(argv)
78
79
    base = setting("OAK_AGENT_RUNNER_URL", "agent-runner.url").rstrip("/")
80
    token = setting("OAK_AGENT_RUNNER_TOKEN", "agent-runner.token")
81
    manifest = json.loads(args.manifest.read_text())
82
    job_id = args.job_id or f"{manifest['campaign_id']}-{datetime.now(timezone.utc):%Y%m%dT%H%M%SZ}"[:80]
83
    job_url = f"{base}/jobs/{job_id}"
84
    # The first request also cold-starts the container; allow for it.
85
    status, body = request("POST", job_url, token, {"manifest": manifest,
86
                                                    "enable_real": args.enable_real, "limit": args.limit}, timeout=300)
87
    if status != 202:
88
        raise SystemExit(f"submit failed: HTTP {status}: {body[:500].decode(errors='replace')}")
89
    print(f"[cloud] submitted {job_id}", file=sys.stderr)
90
91
    state: dict = {}
92
    last_step = None
93
    try:
94
        while True:
95
            time.sleep(args.poll_seconds)
96
            status, body = request("GET", job_url, token)
97
            if status != 200:
98
                print(f"[cloud] poll HTTP {status}: {body[:200].decode(errors='replace')}", file=sys.stderr)
99
                continue
100
            state = json.loads(body)
101
            if state.get("step") != last_step:
102
                last_step = state.get("step")
103
                print(f"[cloud] step={last_step} exit_codes={state.get('exit_codes')}", file=sys.stderr)
104
            tail = [line for line in state.get("log_tail", []) if line.startswith("[trial]")]
105
            if tail:
106
                print(f"[cloud] {tail[-1]}", file=sys.stderr)
107
            if state.get("state") != "running":
108
                break
109
        status, archive = request("GET", job_url + "/result", token, timeout=900)
110
        if status != 200:
111
            raise SystemExit(f"result download failed: HTTP {status}: {archive[:300].decode(errors='replace')}")
112
        args.out.mkdir(parents=True, exist_ok=True)
113
        with tarfile.open(fileobj=io.BytesIO(archive), mode="r:gz") as tar:
114
            tar.extractall(args.out, filter="data")
115
        (args.out / job_id / "job-status.json").write_text(json.dumps(state, indent=2) + "\n")
116
    finally:
117
        if not args.keep_container:
118
            request("DELETE", job_url, token)
119
    print(json.dumps({"job_id": job_id, "state": state.get("state"), "error": state.get("error"),
120
                      "exit_codes": state.get("exit_codes"), "egress_policy": state.get("egress_policy"),
121
                      "results": str(args.out / job_id)}, indent=2))
122
    return 0 if state.get("state") == "done" else 1
123
124
125
if __name__ == "__main__":
126
    raise SystemExit(main())