SafetyBench-AgentEnv / run_benchmark.py
kellu-scale's picture
Keep the public package minimal
7f6f574 verified
Raw History Blame Contribute Delete
8.53 kB
"""Validate or run one SafetyBench task using public AgentEnv and local Docker."""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
def select_task(root, task):
rows = [json.loads(line) for line in (root / "tasks/profiles.jsonl").read_text().splitlines()]
if len(rows) != 110 or len({r["task_id"] for r in rows}) != 110:
raise ValueError("Expected exactly 110 benchmark tasks")
matches = [r for r in rows if task in (r["task"], r["task_id"])]
if len(matches) != 1:
raise ValueError("Select exactly one task by bundle name or original task_id")
return matches[0]
def validate(root, row):
bundle = root / "bundles/safetybench-environments"
steps = json.loads((bundle / "tasks" / (row["task"] + ".json")).read_text())
prompt, = [s for s in steps if s["type"] == "prompt_agent"]
agent, = [s for s in steps if s["type"] == "deploy_agent"]
clock, = [s for s in steps if s["type"] == "sync_env_clock"]
if prompt["prompt"] != row["prompt"]:
raise ValueError("Prompt changed")
if hashlib.sha256(row["memory_md"].encode()).hexdigest() != row["memory_sha256"]:
raise ValueError("Memory changed")
if agent["system_prompt"] != f"<!-- BEGIN memory_md -->\n{row['memory_md'].strip()}\n<!-- END memory_md -->":
raise ValueError("System memory transport changed")
if (clock["virtual_time"], clock["virtual_seconds_per_real_second"]) != (
row["clock"]["now"], row["clock"]["virtual_seconds_per_real_second"]
):
raise ValueError("Clock changed")
for item in row["inputs"]:
path = bundle / "artifacts" / ("inputs_" + row["task"]) / Path(item["target"]).relative_to("/app")
if hashlib.sha256(path.read_bytes()).hexdigest() != item["sha256"]:
raise ValueError("Input file changed")
from agent_env.bundle import parse_bundle
from agent_env.bundle.plan import check_bundle
from agent_env.bundle.resolve import resolve_bundle
from agent_env.store.routing import namespace_routing
with namespace_routing():
check_bundle(resolve_bundle(parse_bundle(bundle)))
return bundle
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--task")
parser.add_argument("--list", action="store_true")
parser.add_argument("--execute", action="store_true")
parser.add_argument("--agent-image", help="User-supplied A2A image, registry/name@sha256:...")
parser.add_argument("--model")
parser.add_argument("--api-base")
parser.add_argument("--api-key-env", help="Only this explicitly named environment variable supplies the model key")
parser.add_argument("--judge-model", help="Explicit judge model; not inherited from the solver")
parser.add_argument("--judge-api-base")
parser.add_argument("--judge-api-key-env", help="Explicit judge credential variable; never auto-discovered")
parser.add_argument("--judge-project-id", help="Optional explicit project attribution required by some proxies")
parser.add_argument("--build-nofile", type=int)
args = parser.parse_args()
root = Path(__file__).resolve().parent
if args.list:
for line in (root / "tasks/profiles.jsonl").read_text().splitlines():
row = json.loads(line)
print(row["task"] + "\t" + row["task_id"])
return
if not args.task:
parser.error("Choose --task or --list")
row = select_task(root, args.task)
bundle = validate(root, row)
print(json.dumps({"task": row["task"], "task_id": row["task_id"], "prompt": row["prompt"],
"inputs": len(row["inputs"]), "validated": True, "execute": args.execute}), flush=True)
if not args.execute:
return
if sys.platform != "linux":
parser.error("The tested execution path requires Linux and Docker")
if not args.agent_image or not re.fullmatch(r"[^\s]+/[^\s]+@sha256:[0-9a-f]{64}", args.agent_image):
parser.error("Supply your compatible A2A image pinned by digest")
if not args.model or not args.api_base or not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", args.api_key_env or ""):
parser.error("Execution requires --model, --api-base and --api-key-env")
if not args.api_base.startswith(("https://", "http://")):
parser.error("Model endpoint must be an HTTP(S) URL")
if not os.environ.get(args.api_key_env):
parser.error("The explicitly selected model-key variable is empty; no fallback is attempted")
scored = any(s["type"] == "safetybench_outcome_verifier" for s in json.loads(
(bundle / "tasks" / (row["task"] + ".json")).read_text()))
if scored:
if not args.judge_model or not args.judge_api_base or not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", args.judge_api_key_env or ""):
parser.error("This bundle requires --judge-model, --judge-api-base and --judge-api-key-env")
if not os.environ.get(args.judge_api_key_env):
parser.error("The explicitly selected judge-key variable is empty; no fallback is attempted")
if args.judge_project_id and not re.fullmatch(r"[0-9a-f]{24}", args.judge_project_id):
parser.error("Judge project attribution must be a 24-character project ObjectId")
if args.build_nofile is not None and not 1024 <= args.build_nofile <= 262144:
parser.error("Build-only file limit must be between 1024 and 262144")
state = Path(tempfile.mkdtemp(prefix="safetybench-task-"))
staged = state / "bundle"
shutil.copytree(bundle, staged)
agent_dir = staged / "agents/solver"
agent_dir.mkdir(parents=True)
(agent_dir / "agent.toml").write_text('image = ' + json.dumps(args.agent_image) + '\n')
task_path = staged / "tasks" / (row["task"] + ".json")
steps = json.loads(task_path.read_text())
for step in steps:
if step["type"] == "deploy_agent":
step["a2a_agent_id"] = "solver"
task_path.write_text(json.dumps(steps, indent=2) + "\n")
config = (
'[stores]\ndocument = "local"\nobject = "local"\nimage = "local"\nsecret = "local"\n'
'[sandbox]\ndefault = "local"\nagent_default = "local"\n'
'[model]\nbase_url = ' + json.dumps(args.api_base) + '\napi_key = '
+ json.dumps("env:" + args.api_key_env) + '\n'
)
(state / "config.toml").write_text(config)
(state / "docker").mkdir()
(state / "docker/config.json").write_text("{}\n")
keep = {"PATH", "HOME", "USER", "LOGNAME", "LANG", "LC_ALL", "TMPDIR", "TERM", args.api_key_env}
if scored:
keep.add(args.judge_api_key_env)
env = {k: v for k, v in os.environ.items() if k in keep}
if scored:
env.update(SAFETYBENCH_JUDGE_MODEL=args.judge_model, SAFETYBENCH_JUDGE_API_BASE=args.judge_api_base,
SAFETYBENCH_JUDGE_KEY_ENV=args.judge_api_key_env)
if args.judge_project_id:
env["SAFETYBENCH_JUDGE_PROJECT_ID"] = args.judge_project_id
env.update(AGENT_ENV_CONFIG=str(state / "config.toml"), XDG_STATE_HOME=str(state / "state"),
DOCKER_CONFIG=str(state / "docker"), AGENT_ENV_LOCAL_SANDBOX_DIR=str(state / "sandboxes"),
AWS_EC2_METADATA_DISABLED="true", PYTHONUNBUFFERED="1")
if args.build_nofile:
docker = shutil.which("docker")
if not docker:
parser.error("Docker is not installed")
(state / "bin").mkdir()
wrapper = state / "bin/docker"
wrapper.write_text('#!/bin/sh\nif [ "$1" = "build" ]; then\n shift\n exec "$SAFETYBENCH_DOCKER_BIN" build --ulimit "nofile=$SAFETYBENCH_BUILD_NOFILE:$SAFETYBENCH_BUILD_NOFILE" "$@"\nfi\nexec "$SAFETYBENCH_DOCKER_BIN" "$@"\n')
wrapper.chmod(0o700)
env.update(SAFETYBENCH_DOCKER_BIN=docker, SAFETYBENCH_BUILD_NOFILE=str(args.build_nofile))
env["PATH"] = str(state / "bin") + os.pathsep + env.get("PATH", "")
print(json.dumps({"evidence_directory": str(state), "sandbox": "local", "key_source": args.api_key_env}), flush=True)
result = subprocess.run([str(Path(sys.executable).parent / "agent-env"), "run", str(staged),
"--task", row["task"], "--sandbox", "local", "--model", args.model], env=env, check=False)
print("Execution exit code:", result.returncode, "— execution status is not a safety verdict.", flush=True)
raise SystemExit(result.returncode)
if __name__ == "__main__":
main()