Download code/runner.py from wchai/prophet-v2: direct link, hf CLI and curl.
- Browser
- Download file 11 kB
-
https://huggingface.co/datasets/wchai/prophet-v2/resolve/main/code/runner.py
- Command line
-
hf download hf://datasets/wchai/prophet-v2/code/runner.py
-
curl -L -o runner.py https://huggingface.co/datasets/wchai/prophet-v2/resolve/main/code/runner.py
11 kB
| """Run FrontierCS 2 forecasting tasks (drkylj/prophet) with Claude Code on Gemini 4 Carbon, in a sandbox, on the shim host. | |
| Each trial: | |
| - one shared image (sandbox/prophet.sif: the task Dockerfile's python:3.12-slim + Claude Code 2.1.335 + managed settings | |
| that deny WebFetch/WebSearch); the task's context/ is bound read-only at /app/context, a fresh dir at /app and /tmp; | |
| - an empty network namespace (unshare -rn) whose only exit is sandbox/fwd.py, a bridge to the Carbon shim | |
| (the predictor spec's allowlist, with the shim in the place of api.anthropic.com); | |
| - claude -p <instruction.md>, stream-json to agent/claude-code.txt, sessions in agent/sessions/ (CLAUDE_CONFIG_DIR); | |
| - if /app/prediction.json is missing when claude exits, up to --resumes "continue" turns in the same session; | |
| - grading with the task's own tests/grade.py into verifier/{reward,prediction}.json. | |
| The job dir has Harbor's trial layout (config.json, result.json, agent/, verifier/), so the dataset's | |
| scripts/score_forecasts.py and scripts/audit_network.py read it unchanged. | |
| python3 -I runner.py --job jobs/pilot20 --tasks-dir tasks_x --ids ids.txt -n 8 (run on the shim host) | |
| """ | |
| import argparse, concurrent.futures as cf, json, os, secrets, shlex, signal, subprocess, sys, time | |
| V = os.path.dirname(os.path.abspath(__file__)) | |
| SIF = f'{V}/sandbox/prophet.sif' | |
| FWD = f'{V}/sandbox/fwd.py' | |
| SHIM_PORT = 8844 | |
| TOKEN = '<SCRATCH>' | |
| TAG = 'value' # shim client tag: the limiter files these calls under project "value" | |
| NUDGE = ('Your last turn ended before /app/prediction.json was written. Continue: write /app/prediction.json now in the ' | |
| 'required form, with one score for every target in /app/context/targets.json and a short rationale.') | |
| def sh(cmd, **kw): | |
| return subprocess.run(cmd, shell=True, **kw) | |
| def claude_cmd(prompt_file, resume=None): | |
| c = ['claude', '-p', f'"$(cat {prompt_file})"'] | |
| if resume: | |
| c += ['--resume', resume] | |
| c += ['--model', 'claude-opus-5-5', '--effort', 'high', '--permission-mode', 'bypassPermissions', | |
| '--output-format', 'stream-json', '--verbose'] | |
| return ' '.join(c) | |
| def run_claude(T, ctx, sock, prompt_file, resume, timeout): | |
| """One claude -p turn inside the sandbox. Returns (rc, timed_out).""" | |
| binds = [f'{T}/app:/app', f'{ctx}:/app/context:ro', f'{T}/tmp:/tmp', f'{T}/agent/sessions:/logs/agent/sessions', | |
| f'{prompt_file}:/logs/prompt.txt:ro'] | |
| inner = ( | |
| 'set -e; ip link set lo up; ' | |
| f'python3 -I {FWD} tcp2unix 127.0.0.1:{SHIM_PORT} {sock} > {T}/agent/fwd.log 2>&1 & ' | |
| f'for i in $(seq 50); do grep -q ready {T}/agent/fwd.log 2>/dev/null && break; sleep 0.1; done; ' | |
| f'apptainer exec --containall --cleanenv --no-init --writable-tmpfs --home {T}/home:/root --pwd /app ' | |
| + ' '.join(f'--bind {shlex.quote(b)}' for b in binds) + | |
| f' {SIF} bash -c {shlex.quote(claude_cmd("/logs/prompt.txt", resume))}' | |
| f' >> {T}/agent/claude-code.txt 2>> {T}/agent/claude-code.stderr < /dev/null; rc=$?; kill %1 2>/dev/null; exit $rc') | |
| env = {k: os.environ[k] for k in ('PATH', 'LANG', 'USER', 'LOGNAME') if k in os.environ} | |
| env.update({ | |
| 'HOME': f'{T}/home', | |
| 'APPTAINERENV_ANTHROPIC_BASE_URL': f'http://127.0.0.1:{SHIM_PORT}/w/{TAG}', | |
| 'APPTAINERENV_ANTHROPIC_API_KEY': open(TOKEN).read().strip(), | |
| 'APPTAINERENV_CLAUDE_CONFIG_DIR': '/logs/agent/sessions', | |
| 'APPTAINERENV_CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC': '1', | |
| 'APPTAINERENV_DISABLE_AUTOUPDATER': '1', | |
| 'APPTAINERENV_IS_SANDBOX': '1', | |
| 'APPTAINERENV_CLAUDE_STREAM_IDLE_TIMEOUT_MS': '1800000', | |
| 'APPTAINERENV_API_TIMEOUT_MS': '1800000', | |
| 'APPTAINERENV_TMPDIR': '/tmp', | |
| 'APPTAINERENV_PATH': '/usr/local/bin:/usr/local/sbin:/usr/sbin:/usr/bin:/sbin:/bin', | |
| }) | |
| p = subprocess.Popen(['unshare', '-rn', 'bash', '-c', inner], env=env, start_new_session=True) | |
| try: | |
| return p.wait(timeout=timeout), False | |
| except subprocess.TimeoutExpired: | |
| os.killpg(p.pid, signal.SIGTERM) | |
| time.sleep(5) | |
| try: | |
| os.killpg(p.pid, signal.SIGKILL) | |
| except ProcessLookupError: | |
| pass | |
| p.wait() | |
| return -9, True | |
| def stream_stats(path): | |
| sid, msg_ids, res = None, set(), None | |
| for line in open(path, errors='replace') if os.path.exists(path) else []: | |
| try: | |
| e = json.loads(line) | |
| except Exception: | |
| continue | |
| sid = e.get('session_id') or sid | |
| if e.get('type') == 'assistant': | |
| msg_ids.add((e.get('message') or {}).get('id')) | |
| if e.get('type') == 'result': | |
| res = e | |
| return sid, len(msg_ids - {None}), res | |
| def room(headroom): | |
| """True when the shim's limiter has at least `headroom` free calls in its window and no request waits.""" | |
| import urllib.request | |
| try: | |
| req = urllib.request.Request(f'http://127.0.0.1:{SHIM_PORT}/limiter', headers={'x-api-key': open(TOKEN).read().strip()}) | |
| d = json.load(urllib.request.urlopen(req, timeout=10)) | |
| if d.get('waiting') or d['used'] + headroom > d['budget']: | |
| return False | |
| except Exception: | |
| return False | |
| f10, f60 = upstream_failures() | |
| return f10 <= 10 and f60 <= 60 | |
| USAGE = '<SCRATCH>' | |
| def upstream_failures(): | |
| """Upstream 429/503/-1 counts (all clients) over the last 10 and 60 min, from the tail of the shim's call log. | |
| Brake asked by the controller 2026-12-03 09:1x: 429s mean there is no leftover capacity (owner rule).""" | |
| import datetime | |
| try: | |
| with open(USAGE, 'rb') as fh: | |
| fh.seek(0, 2) | |
| fh.seek(max(0, fh.tell() - 12_000_000)) | |
| lines = fh.read().decode('utf8', 'replace').splitlines()[1:] | |
| except OSError: | |
| return 10 ** 6, 10 ** 6 | |
| now = time.time() | |
| f10 = f60 = 0 | |
| for ln in lines: | |
| if '"status": 429' not in ln and '"status": 503' not in ln and '"status": -1' not in ln: | |
| continue | |
| try: | |
| d = json.loads(ln) | |
| age = now - datetime.datetime.strptime(d['ts'], '%Y-%m-%dT%H:%M:%SZ').replace( | |
| tzinfo=datetime.timezone.utc).timestamp() | |
| except Exception: | |
| continue | |
| if d.get('status') in (429, 503, -1) and age <= 3600: | |
| f60 += 1 | |
| f10 += age <= 600 | |
| return f10, f60 | |
| def run_trial(job, tasks_dir, tid, sock, timeout, resumes): | |
| task = os.path.abspath(os.path.join(tasks_dir, tid)) | |
| T = os.path.join(job, f'{tid}__{secrets.token_hex(4)}') | |
| for d in ('app', 'tmp', 'home', 'agent/sessions', 'verifier'): | |
| os.makedirs(f'{T}/{d}', exist_ok=True) | |
| json.dump({'task': {'path': task}, 'agent': {'name': 'claude-code', 'model': 'gemini-4-carbon (via Carbon shim)', | |
| 'effort': 'high', 'claude_code': '2.1.335'}, 'environment': {'type': 'apptainer+unshare-rn'}}, | |
| open(f'{T}/config.json', 'w'), indent=1) | |
| t0 = time.time() | |
| rc, to = run_claude(T, f'{task}/environment/context', sock, f'{task}/instruction.md', None, timeout) | |
| n_res = 0 | |
| nudge = f'{T}/agent/nudge.txt' | |
| open(nudge, 'w').write(NUDGE) | |
| while not to and not os.path.exists(f'{T}/app/prediction.json') and n_res < resumes: | |
| sid, _, _ = stream_stats(f'{T}/agent/claude-code.txt') | |
| left = timeout - (time.time() - t0) | |
| if not sid or left < 60: | |
| break | |
| n_res += 1 | |
| rc, to = run_claude(T, f'{task}/environment/context', sock, nudge, sid, left) | |
| elapsed = time.time() - t0 | |
| g = subprocess.run(['python3', '-I', f'{task}/tests/grade.py', f'{T}/app/prediction.json', | |
| f'{task}/tests/ground_truth.json', f'{T}/verifier/reward.json'], capture_output=True, text=True) | |
| rew = json.load(open(f'{T}/verifier/reward.json')) if os.path.exists(f'{T}/verifier/reward.json') else {} | |
| sid, n_calls, res = stream_stats(f'{T}/agent/claude-code.txt') | |
| exc = 'AgentTimeoutError' if to else (None if os.path.exists(f'{T}/app/prediction.json') else 'NoPrediction') | |
| out = {'task_name': tid, 'started_at': t0, 'elapsed_s': round(elapsed, 1), 'claude_rc': rc, 'resumes': n_res, | |
| 'n_assistant_messages': n_calls, 'num_turns': (res or {}).get('num_turns'), | |
| 'usage': (res or {}).get('usage'), 'verifier_result': {'rewards': rew}, | |
| 'exception_info': {'exception_type': exc} if exc else None, 'grade_stderr': g.stderr[-2000:]} | |
| json.dump(out, open(f'{T}/result.json', 'w'), indent=1) | |
| return tid, rew.get('reward'), elapsed, n_calls, exc | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument('--job', required=True) | |
| ap.add_argument('--tasks-dir', required=True) | |
| ap.add_argument('--ids', required=True, help='file with one task id per line') | |
| ap.add_argument('-n', type=int, default=8, help='concurrent trials') | |
| ap.add_argument('--timeout', type=int, default=3600, help='wall seconds per trial (limiter queueing included)') | |
| ap.add_argument('--resumes', type=int, default=2) | |
| ap.add_argument('--headroom', type=int, default=10, help='free calls per window the limiter must show to start a trial') | |
| a = ap.parse_args() | |
| job = os.path.abspath(a.job) | |
| os.makedirs(job, exist_ok=True) | |
| done = set() | |
| for d in os.listdir(job): | |
| if os.path.exists(os.path.join(job, d, 'result.json')): | |
| done.add(d.rsplit('__', 1)[0]) | |
| ids = [l.strip() for l in open(a.ids) if l.strip() and l.strip() not in done] | |
| sock = f'/tmp/value_shim_{os.getpid()}.sock' | |
| fwd = subprocess.Popen(['python3', '-I', FWD, 'unix2tcp', sock, f'127.0.0.1:{SHIM_PORT}'], stdout=subprocess.PIPE, text=True) | |
| assert fwd.stdout.readline().strip() == 'ready' | |
| print(f'{len(ids)} trials to run ({len(done)} already done), n={a.n}', flush=True) | |
| try: | |
| with cf.ThreadPoolExecutor(a.n) as ex: | |
| pending, todo = set(), list(ids) | |
| while todo or pending: | |
| # cq-style admission (owner 2026-12-02: 「走cq队列 最低优先级」; project value is prio -30 in | |
| # tools/cq/limits.json): start a trial only when the shim's window has room and nobody is waiting | |
| while todo and len(pending) < a.n and room(a.headroom): | |
| pending.add(ex.submit(run_trial, job, a.tasks_dir, todo.pop(0), sock, a.timeout, a.resumes)) | |
| time.sleep(2) | |
| done, pending = cf.wait(pending, timeout=60, return_when=cf.FIRST_COMPLETED) | |
| for f in done: | |
| try: | |
| tid, r, el, nc, exc = f.result() | |
| print(f'{time.strftime("%H:%M:%S")} {tid} reward={r} {el:.0f}s msgs={nc} exc={exc}', flush=True) | |
| except Exception as e: | |
| print('trial error', repr(e), flush=True) | |
| finally: | |
| fwd.terminate() | |
| if os.path.exists(sock): | |
| os.unlink(sock) | |
| if __name__ == '__main__': | |
| main() | |