File size: 15,849 Bytes
22decf5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
"""Agent phase: let a CLI agent post-train a base model inside the sandbox.

Mirrors the solve part of upstream `src/run_task.sh`, reusing upstream's prompt, agents,
task files and helper scripts, so runs stay comparable to the official benchmark.
"""

import contextlib
import json
import os
import shutil
import subprocess
import sys
import time
from pathlib import Path

from . import config, sandbox

UP = config.UPSTREAM

# Where the sandbox sees the pieces that make the agent CLI work without any network.
SHIM = "/opt/x2p_anthropic_shim.py"
CODEX_SHIM = "/opt/x2p_codex_shim.py"
CODEX_SDK = "/opt/codex-sdk"
CODEX_RUNNER = "/opt/codex-sdk-runner.mjs"
X2P_UDS = "/run/x2pagentd_http1.sock"
# The second channel through the empty network namespace, for the two LLM-graded benchmarks: a
# unix socket bridged to the local vLLM judge pool. See `scripts/ptb_uds_bridge.py`.
BRIDGE = "/opt/ptb_uds_bridge.py"
JUDGE_UDS = "/run/ptb_judge.sock"
# vLLM is served without authentication, but the OpenAI SDK refuses to send a request with no key.
JUDGE_API_KEY = "EMPTY"

# Runs in the sandbox with cwd = task dir. `timeout` kills it when the time budget is over.
# The sandbox has an empty network namespace, so the agent CLI reaches its model only through the
# shim on the sandbox's own loopback, which relays over the bound x2pagentd socket. Nothing else
# gets out. The shim prints the port it picked; it dies with the sandbox.
SOLVE_SCRIPT = f"""
set -o pipefail
{{
    python -c 'import torch; assert torch.cuda.is_available(), "no GPU visible in sandbox"' || exit 1
    if [ "$PTB_AGENT_PROTOCOL" = codex ]; then
        python {CODEX_SHIM} > ~/shim_port.txt 2>~/shim.log &
    else
        python {SHIM} > ~/shim_port.txt 2>~/shim.log &
    fi
    for _ in $(seq 50); do [ -s ~/shim_port.txt ] && break; sleep 0.2; done
    [ -s ~/shim_port.txt ] || {{ echo "shim did not start; see ~/shim.log"; cat ~/shim.log; exit 1; }}
    if [ "$PTB_AGENT_PROTOCOL" = codex ]; then
        export CODEX_AGENT_BASE_URL="http://127.0.0.1:$(cat ~/shim_port.txt)"
    else
        export ANTHROPIC_BASE_URL="http://127.0.0.1:$(cat ~/shim_port.txt)"
    fi
    if [ -S {JUDGE_UDS} ]; then
        python {BRIDGE} sandbox --socket {JUDGE_UDS} > ~/judge_port.txt 2>~/judge_shim.log &
        for _ in $(seq 50); do [ -s ~/judge_port.txt ] && break; sleep 0.2; done
        [ -s ~/judge_port.txt ] || {{ echo "judge shim did not start; see ~/judge_shim.log"; cat ~/judge_shim.log; exit 1; }}
        export OPENAI_BASE_URL="http://127.0.0.1:$(cat ~/judge_port.txt)/v1"
    fi
    bash ~/system_monitor.sh & monitor=$!
    bash ~/agent_solve.sh
    kill $monitor
}} 2>&1 | python ~/timestamp_lines.py
"""

# Upstream's prompt promises unrestricted internet. This runner gives the agent a prefilled cache
# and no network instead, so the promise has to be corrected or the agent wastes its budget on
# downloads that cannot succeed.
INTERNET_LINE = "- Internet access is unrestricted."
OFFLINE_LINE = (
    "- No internet access. The HuggingFace cache under $HF_HOME is pre-populated with the models\n"
    "  and datasets you are expected to need; explore it to see what is available. Downloading\n"
    "  anything, including extra Python packages, will fail."
)
# ...with one hole, on the two benchmarks whose evaluate.py grades through an LLM. Without this the
# agent reads "no internet access", concludes evaluate.py cannot run, and spends ten hours training
# with no measurement of the thing it is being scored on.
GRADER_LINE = (
    "\n- One exception to the previous point: the grader endpoint that this benchmark's\n"
    "  `evaluate.py` calls IS reachable. `OPENAI_API_KEY` and `OPENAI_BASE_URL` are already set in\n"
    "  your environment and point at a local server, so running `evaluate.py` works normally. That\n"
    "  endpoint serves the grading model only -- it is subject to rule 10 above and must not be\n"
    "  used to generate training data."
)


def hf_cache_dir(model: str) -> str:
    return "hub/models--" + model.replace("/", "--")


def model_is_cached(model: str) -> bool:
    """True only if the cache holds actual weights, not just the repo directory.

    A download that dies part-way leaves the `models--org--name` directory behind with no
    snapshot in it. Upstream's `download_resources.py` tests only that the directory exists, so
    every later run reports "already cached" and skips it -- and the agent then starts a ten-hour
    run against a model that is not there. Check for a weight file instead.
    """
    repo = config.HF_CACHE / hf_cache_dir(model)
    return any(repo.glob("snapshots/*/*.safetensors")) or any(repo.glob("snapshots/*/*.bin"))


def task_needs_grader(task: str) -> bool:
    """True when the benchmark's own evaluate.py scores with an LLM behind an OpenAI client."""
    info = json.loads((UP / "src/eval/tasks" / task / "info.json").read_text())
    return "OPENAI_API_KEY" in info.get("required_api_keys", [])


def judge_pool_targets() -> list[str]:
    """Addresses of the local vLLM judge pool; see `config.judge_pool_targets`."""
    return config.judge_pool_targets()


def agent_api_keys(agent: str, task: str, grader_is_local: bool = False) -> dict[str, str]:
    """Only the keys the agent scaffold and the benchmark's grader need enter the sandbox."""
    names = json.loads((config.agent_dir(agent) / "api_keys.json").read_text())["allowed_api_keys"]
    names += json.loads((UP / "src/eval/tasks" / task / "info.json").read_text()).get("required_api_keys", [])
    # Codex reads CODEX_API_KEY, so OPENAI_API_KEY stays reserved for benchmark graders.
    available = {**os.environ, "CODEX_API_KEY": os.environ.get("OPENAI_API_KEY", "")}
    if grader_is_local:
        # The pool serves without auth, but the SDK still insists on a key being present. A real
        # OpenAI key would be useless here anyway: api.openai.com is not routable from the aws cluster.
        available["OPENAI_API_KEY"] = JUDGE_API_KEY
    if missing := [name for name in names if not available.get(name)]:
        sys.exit(f"Missing API key(s) {missing}: set them in {config.ENV_FILE} or the environment.")
    return {name: available[name] for name in names}


def passthrough_env() -> dict[str, str]:
    """Extra host variables to forward into the sandbox, named by `PTB_SANDBOX_ENV`.

    The sandbox inherits nothing from the host, so this is how a machine redirects an agent CLI at
    a local gateway instead of the vendor's public API (see `scripts/x2p_anthropic_shim.py`).
    """
    names = os.environ.get("PTB_SANDBOX_ENV", "").replace(",", " ").split()
    return {name: os.environ[name] for name in names if os.environ.get(name)}


def build_prompt(task: str, model: str, agent: str, hours: int, grader_is_local: bool = False) -> str:
    prompt = subprocess.run(
        [sys.executable, "src/eval/general/get_prompt.py", "--agent", agent, "--model-to-train", model,
         "--benchmark-id", task, "--num-hours", str(hours)],
        cwd=UP, check=True, capture_output=True, text=True,
    ).stdout
    prompt = prompt.replace("\\`", "`")  # upstream pre-escapes backticks for its shell-based launcher
    if INTERNET_LINE not in prompt:
        sys.exit(f"Upstream's prompt no longer contains {INTERNET_LINE!r}; re-check the offline wording.")
    return prompt.replace(INTERNET_LINE, OFFLINE_LINE + (GRADER_LINE if grader_is_local else ""))


def prepare_home(home: Path, task: str, agent: str, hours: int) -> None:
    """Lay out the sandbox home like upstream: agent tooling in ~, the agent's workspace in ~/task."""
    task_src = UP / "src/eval/tasks" / task
    task_dir = home / "task"
    task_dir.mkdir(parents=True)
    shutil.copy(task_src / "evaluate.py", task_dir)
    shutil.copytree(UP / "src/eval/templates", task_dir / "templates")
    if (task_src / "evaluation_code").is_dir():
        shutil.copytree(task_src / "evaluation_code", task_dir / "evaluation_code")
    if (task_src / "task_context").is_dir():  # extra files for the agent, placed directly in ~/task
        shutil.copytree(task_src / "task_context", task_dir, dirs_exist_ok=True)
    subprocess.run(["bash", "src/utils/create_timer.sh", str(hours), str(task_dir / "timer.sh")], cwd=UP, check=True)

    shutil.copytree(UP / "containers/other_home_data/.codex", home / ".codex")
    agent_src = config.agent_dir(agent)
    shutil.copy(agent_src / "solve.sh", home / "agent_solve.sh")
    # The `*_non_api` scaffolds abort without it; upstream's run_task.sh copies it the same way.
    if (oauth_token := agent_src / "oauth_token").is_file():
        shutil.copy(oauth_token, home / "oauth_token")
    for script in ("system_monitor.sh", "timestamp_lines.py", "update_agent_cli.sh"):
        shutil.copy(UP / "src/utils" / script, home)
    # Decontamination tooling; the prompt only announces it if the test set is present.
    shutil.copy(task_src / "test_data.json", home)
    shutil.copy(UP / "src/judges/judge_tools/contamination_check.py", home)


@contextlib.contextmanager
def judge_bridge(run_dir: Path, pool: list[str]):
    """Host half of the judge channel: a unix socket on this node, forwarded to the pool.

    Yields the socket path to bind into the sandbox, or None when no pool is needed. AF_UNIX
    paths are capped at 108 bytes, which `run_dir / "judge.sock"` blows past once the task and
    model names are long (measured 151 bytes for healthbench/gemma-3-4b-pt -- "Judge bridge died
    on startup" with "OSError: AF_UNIX path too long" in judge_bridge.log, 2026-10-03). /tmp is
    short enough and still collision-free across cells sharing a node, since SLURM_JOB_ID is
    unique per cell.
    """
    if not pool:
        yield None
        return
    socket_path = Path(f"/tmp/ptb_judge_{os.environ.get('SLURM_JOB_ID', os.getpid())}.sock")
    log = (run_dir / "judge_bridge.log").open("w")
    process = subprocess.Popen(
        [sys.executable, str(config.REPO_ROOT / "scripts/ptb_uds_bridge.py"), "host",
         "--socket", str(socket_path), "--targets", ",".join(pool)],
        stdout=log, stderr=subprocess.STDOUT)
    try:
        for _ in range(100):  # binding the socket is near-instant; a crash is the real case here
            if socket_path.is_socket():
                break
            if process.poll() is not None:
                sys.exit(f"Judge bridge died on startup; see {run_dir / 'judge_bridge.log'}.")
            time.sleep(0.1)
        else:
            process.terminate()
            sys.exit(f"Judge bridge never bound {socket_path}; see {run_dir / 'judge_bridge.log'}.")
        print(f"Judge bridge up: {socket_path} -> {', '.join(pool)}")
        yield socket_path
    finally:
        process.terminate()
        process.wait(timeout=30)
        log.close()
        socket_path.unlink(missing_ok=True)


def solve(run_dir: Path, task: str, model: str, agent: str, agent_model: str, hours: int,
          container: str = config.AGENT_CONTAINER) -> None:
    """Run the agent; leaves prompt, traces, `task/`, `agent_home/` and (if produced) `final_model/` in `run_dir`."""
    # The two LLM-graded benchmarks are unscoreable without a grader, and api.openai.com is not
    # routable from the aws cluster, so they run against the local pool or not at all. Failing here
    # beats discovering it ten hours later in evaluate.py.
    grader_is_local = task_needs_grader(task)
    pool = judge_pool_targets() if grader_is_local else []
    if grader_is_local and not pool:
        sys.exit(f"{task} grades with an LLM but no judge pool is reachable: start "
                 f"scripts/ptb_judge_pool.sbatch and point PTB_JUDGE_POOL_DIR at its pool dir "
                 f"(or set PTB_JUDGE_POOL=host:port,...).")

    keys = agent_api_keys(agent, task, grader_is_local)
    if not model_is_cached(model):
        sys.exit(f"{model} has no weights in {config.HF_CACHE} (an empty repo directory does not "
                 f"count): run `ptb setup --models {model}` first.")

    if not (UP / "src/eval/tasks" / task / "test_data.json").is_file():
        sys.exit(f"Test data of {task} is missing: run `ptb setup --tasks {task}` first.")

    uds = Path(os.environ.get("X2P_SOCKET_DIR", "")) / "x2pagentd_http1.sock"
    if not uds.is_socket():
        sys.exit(f"No x2pagentd socket at {uds}: submit the job with --export=ALL,WITH_X2P=1.")

    scratch = run_dir / "sandbox"
    prepare_home(sandbox.home_dir(scratch), task, agent, hours)
    prompt = build_prompt(task, model, agent, hours, grader_is_local)
    (run_dir / "prompt.txt").write_text(prompt)

    protocol = "codex" if agent == "codex_sdk" else "anthropic"
    binds = {config.REPO_ROOT / "scripts/x2p_anthropic_shim.py": f"{SHIM}:ro", uds: X2P_UDS}
    if protocol == "codex":
        sdk_dir = Path(os.environ.get("PTB_CODEX_SDK_DIR", ""))
        if not (sdk_dir / "node_modules/@openai/codex-sdk/dist/index.js").is_file():
            sys.exit("Codex SDK is not installed: set PTB_CODEX_SDK_DIR to the directory containing "
                     "node_modules/@openai/codex-sdk (run scripts/ptb_codex_sdk_setup.sbatch first).")
        binds[config.REPO_ROOT / "scripts/x2p_codex_shim.py"] = f"{CODEX_SHIM}:ro"
        binds[config.REPO_ROOT / "agents/codex_sdk/run.mjs"] = f"{CODEX_RUNNER}:ro"
        binds[sdk_dir] = f"{CODEX_SDK}:ro"
    start = time.time()
    with judge_bridge(run_dir, pool) as judge_socket:
        if judge_socket:
            binds[config.REPO_ROOT / "scripts/ptb_uds_bridge.py"] = f"{BRIDGE}:ro"
            binds[judge_socket] = JUDGE_UDS
        with sandbox.hf_overlay(scratch) as hf_cache:
            exit_code = sandbox.run(
                ["bash", "-c", SOLVE_SCRIPT],
                scratch=scratch, hf_cache=hf_cache, workdir=f"{sandbox.HOME}/task", container=container,
                binds=binds,
                env={**passthrough_env(), **keys, "PROMPT": prompt, "AGENT_CONFIG": agent_model,
                     "PTB_AGENT_PROTOCOL": protocol, "X2P_UDS": X2P_UDS},
                timeout_minutes=hours * 60 + 5, isolate_network=True, log=run_dir / "solve_out.txt",
            )
    seconds = int(time.time() - start)
    (run_dir / "time_taken.txt").write_text(f"{seconds // 3600:02d}:{seconds % 3600 // 60:02d}:{seconds % 60:02d}\n")
    print(f"Agent finished after {seconds // 60} min with exit code {exit_code}"
          + (" (killed at the time limit)" if seconds >= hours * 3600 else ""))

    subprocess.run([sys.executable, UP / "src/trace_parsing/parse_trace.py", "--agent", agent,
                    run_dir / "solve_out.txt", "-o", run_dir / "solve_parsed.txt"], check=False)
    # Nothing of the agent's home is thrown away except re-downloadable bulk: it holds the agent
    # CLI's own session records (e.g. ~/.codex/sessions), the most complete form of the trajectory.
    home = sandbox.home_dir(scratch)
    if salvaged := (home / "task/final_model").is_dir():
        shutil.move(home / "task/final_model", run_dir / "final_model")
    # Drop the (large) intermediate checkpoints, as upstream does -- but only once a final_model is
    # safely out of the way. An agent killed mid-run (a server error mid-response terminates the
    # CLI outright) leaves trained checkpoints under other names, and those are then the run's only
    # weights: pruning them turns a salvageable run into a lost one.
    if salvaged:
        subprocess.run([sys.executable, UP / "containers/delete_hf_models.py", home / "task"], check=False)
    else:
        print("No final_model: keeping the agent's checkpoints so the run can still be salvaged.")
    shutil.move(home / "task", run_dir / "task")
    for bulk in (".local", ".cache", ".npm"):  # installed CLI and package/compile caches
        shutil.rmtree(home / bulk, ignore_errors=True)
    shutil.move(home, run_dir / "agent_home")
    shutil.rmtree(scratch)