From fd263ea29638cdf4d1d379589d04771bf398f5da Mon Sep 17 00:00:00 2001 From: Etienne Filhol Date: Wed, 2 Dec 2026 14:16:17 +0100 Subject: [PATCH] fix(standard): preserve container check fidelity --- .../swe-bench-multilingual/benchmark.json | 1 - .../swe-bench-multilingual/driver.py | 11 +- .../benchmarks/swe-bench-pro/benchmark.json | 2 +- .../benchmarks/swe-bench-pro/driver.py | 51 +++++--- .../benchmarks/swe-bench-pro/standard.json | 2 +- .../swe-bench-pro/upstream-settings.json | 4 +- .../terminal-bench-pro/benchmark.json | 8 +- .../benchmarks/terminal-bench-pro/driver.py | 15 +-- .../terminal-bench-pro/standard.json | 6 +- .../terminal-bench-pro/upstream-settings.json | 2 +- app/nullius/runs/parse.py | 2 +- app/nullius/standard/backends/container.py | 57 ++++++-- app/nullius/standard/backends/egress.py | 24 ++-- app/nullius/standard/contract/definitions.py | 18 ++- app/nullius/standard/runner/run.py | 53 ++++++-- app/tests/test_standard_check_safety.py | 122 +++++++++++++++++- app/tests/test_standard_own_image.py | 80 ++++++++++++ app/tests/test_swebench_patch.py | 41 +++--- .../supported/swe-bench-multilingual.md | 1 - docs/benchmarks/supported/swe-bench-pro.md | 2 +- .../supported/terminal-bench-pro.md | 8 +- docs/standard.md | 11 +- 22 files changed, 406 insertions(+), 115 deletions(-) diff --git a/app/nullius/catalogue/benchmarks/swe-bench-multilingual/benchmark.json b/app/nullius/catalogue/benchmarks/swe-bench-multilingual/benchmark.json index 3e0bdf4c9..c0796b611 100644 --- a/app/nullius/catalogue/benchmarks/swe-bench-multilingual/benchmark.json +++ b/app/nullius/catalogue/benchmarks/swe-bench-multilingual/benchmark.json @@ -24,7 +24,6 @@ "On Nullius, the agent can reach only its model, so it cannot run the tests of the 26 instances that download their test runner. The tests get internet access after the agent ends.", "mini-SWE-agent runs here with its general prompt and no step or cost limit of its own. The leaderboard runs it with its SWE-bench prompt, 250 steps, 3 USD per instance and internet access.", "On Nullius, the recorded patch is all that differs from the base commit, including what the image's build left there: an agent that changes nothing can still show a patch.", - "On Nullius, axios__axios-5085 cannot be resolved: one of its tests calls a public service through axios, and the tests' proxy refuses that request.", "SWE-agent, the paper's agent, is not offered: it needs a python command in the instance's image, which 42 of the 300 images have.", "Only instances of apache/druid, fmtlib/fmt, gin-gonic/gin, preactjs/preact, reactivex/rxjava and vuejs/core have been run through Nullius." ], diff --git a/app/nullius/catalogue/benchmarks/swe-bench-multilingual/driver.py b/app/nullius/catalogue/benchmarks/swe-bench-multilingual/driver.py index 9d3a9c12a..e0107fd7e 100644 --- a/app/nullius/catalogue/benchmarks/swe-bench-multilingual/driver.py +++ b/app/nullius/catalogue/benchmarks/swe-bench-multilingual/driver.py @@ -20,10 +20,6 @@ pnpm and yarn that corepack fetched, under root's home, where the tests find them; the agent's home is the run's, so it is told where they are. - ``JVM_PROXY``: the check's way out is a proxy named in - ``HTTPS_PROXY``, which the JVM does not read; the check tells it, - since an instance's tests may download what runs them (Maven's - test runner). score - the harness's own grading (``swebench.harness.grading.get_eval_report``) of the patch and eval script's output: resolved when a patch exists, every FAIL_TO_PASS test passes and every PASS_TO_PASS test still passes. Its report is kept @@ -51,11 +47,6 @@ RESULTS = "/tmp/nullius-swebench-verifier" # What the images keep under root's home, where the tests find it: an agent's home is the run's, not root's. AGENT_ENV = {"GOPATH": "/root/go", "GOCACHE": "/root/.cache/go-build", "COREPACK_HOME": "/root/.cache/node/corepack"} -# The check's proxy as the JVM takes one: its proxy properties, and Maven's resolver told to read them. -JVM_PROXY = ('if [ -n "${HTTPS_PROXY:-}" ]; then p="${HTTPS_PROXY#*://}"; p="${p%/}"; ' - 'export JAVA_TOOL_OPTIONS="${JAVA_TOOL_OPTIONS:+$JAVA_TOOL_OPTIONS }' - '-Dhttp.proxyHost=${p%:*} -Dhttp.proxyPort=${p##*:} -Dhttps.proxyHost=${p%:*} -Dhttps.proxyPort=${p##*:} ' - '-Daether.connector.http.useSystemProperties=true"; fi') with open(os.path.join(HERE, "images.json")) as f: IMAGES = json.load(f) @@ -94,7 +85,7 @@ def setup(unit, dir): r = row(unit) capture = (f"cd {WORKDIR} && git add -A && " f"git diff --cached --binary --no-ext-diff --no-textconv {shlex.quote(r['base_commit'])} -- " - f"> {RESULTS}/model.patch && {JVM_PROXY} && exec /bin/bash /eval.sh") + f"> {RESULTS}/model.patch && exec /bin/bash /eval.sh") return {"prompt": r["problem_statement"], "environment": "task", "image": {"pull": IMAGES[unit]}, "workdir": WORKDIR, "env": AGENT_ENV, "verify": {"write": {"/eval.sh": make_test_spec(r).eval_script}, "run": ["/bin/bash", "-c", capture], diff --git a/app/nullius/catalogue/benchmarks/swe-bench-pro/benchmark.json b/app/nullius/catalogue/benchmarks/swe-bench-pro/benchmark.json index 4b8beb098..e4b21c338 100644 --- a/app/nullius/catalogue/benchmarks/swe-bench-pro/benchmark.json +++ b/app/nullius/catalogue/benchmarks/swe-bench-pro/benchmark.json @@ -9,6 +9,7 @@ ], "origin": "official", "good_to_know": [ + "The reward is the authors’ re-grade: the captured patch replayed in a fresh image. The in-container score is kept beside it, with both test outputs.", "Agents work with no internet and their web tools off, as the authors' locked protocol requires. Its commands use high reasoning effort: set the same to compare.", "Each task gives the agent 50 minutes. A task cut there is still scored on what the agent changed, except with mini-swe-agent.", "V2 scores do not compare with v1 numbers: 89 tasks were dropped, 529 statements rewritten and the tests revised.", @@ -21,7 +22,6 @@ "The authors' capture of the agent's diff compares the repository with HEAD: it misses what an agent commits and includes files an image left untracked." ], "limitations": [ - "The tests run in the container the agent worked in. The authors' authoritative score re-grades the agent's diff on a fresh image; Nullius keeps the diff as verifier/model.patch and does not re-grade.", "mini-swe-agent runs mini's own config with no cost limit, where the protocol's file adds high effort, a named model class and its own error template; a task cut at 50 minutes is its timeout and not scored, where the protocol grades its diff.", "The tests reach the internet through an HTTP and HTTPS proxy to public addresses, where the protocol gives them open access.", "Tasks of element-web, navidrome, openlibrary, teleport, tutanota, vuls and webclients have not been run through Nullius." diff --git a/app/nullius/catalogue/benchmarks/swe-bench-pro/driver.py b/app/nullius/catalogue/benchmarks/swe-bench-pro/driver.py index e395ef8a4..db56cc597 100644 --- a/app/nullius/catalogue/benchmarks/swe-bench-pro/driver.py +++ b/app/nullius/catalogue/benchmarks/swe-bench-pro/driver.py @@ -14,14 +14,11 @@ authors' prebuilt image, pulled by the digest its tag had when pinned here, ``images.json``, with the memory and CPUs its task.toml asks for); its own agent timeout (``agent_seconds``, task.toml's agent.timeout_sec); and its check - (``verify``): once the agent has ended and what it left running is stopped, - ``tests/`` is copied to ``/tests`` and the check runs in the task's container: the - locked protocol's own capture of the agent's diff (``v2/tooling``: the repository - against HEAD, kept as ``model.patch``), a reward file left before the tests - removed, as Harbor's verifier does, then ``test.sh``, with the way out task.toml - gives the verifier, its results collected from ``/logs/verifier``. The tests reach - the container only then; nothing is written into the workspace. -score - the reward test.sh wrote, read from what the check collected + (``verify``): the upstream's capture runs in the agent's container; test.sh runs + there for the in-place score, then the upstream replay commands apply only the + captured patch in a fresh container of the same image and limits. test.sh runs + again there for the authoritative score. +score - the fresh reward test.sh wrote; the in-place reward is kept in detail.in_place oracle - the reference control: ``solution/`` copied to ``/solution`` and ``solve.sh`` run in the task's container, as the agent would have worked @@ -73,6 +70,21 @@ def capture() -> str: return _capture +def replay() -> str: + """The pinned replay agent's literal commands, without importing its Harbor dependencies.""" + with open(os.path.join(os.environ["NULLIUS_UPSTREAM"], "v2", "tooling", "patch_replay.py")) as f: + tree = ast.parse(f.read()) + cls = next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == "PatchReplayAgent") + method = next(n for n in cls.body if isinstance(n, ast.AsyncFunctionDef) and n.name == "run") + commands = [ast.literal_eval(k.value) for n in ast.walk(method) + if isinstance(n, ast.Call) and isinstance(n.func, ast.Attribute) + and isinstance(n.func.value, ast.Name) and n.func.value.id == "environment" and n.func.attr == "exec" + for k in n.keywords if k.arg == "command"] + if len(commands) != 2 or not all(isinstance(c, str) for c in commands): + raise ValueError("patch_replay.py: two literal environment commands were expected") + return "; ".join(commands) + + def task(unit): """The task's folder in the upstream and its task.toml.""" if unit not in IMAGES: @@ -132,15 +144,18 @@ def setup(unit, dir): if env.get("cpus"): image["cpus"] = env["cpus"] agent = (t.get("agent") or {}).get("timeout_sec") - # the capture first, then test.sh whatever the capture did; a reward left before the tests is removed, as - # Harbor's verifier removes both files before it runs a task's tests: only what test.sh writes is read - check = (f"{capture()}; cp {CAPTURED} {LOGS}/model.patch; rm -f -- {LOGS}/reward.txt {LOGS}/reward.json; " - "exec bash /tests/test.sh") + check = f"rm -f -- {LOGS}/reward.txt {LOGS}/reward.json; exec bash /tests/test.sh" + common = {"copy": {f"{TASKS}/{unit}/tests": "/tests"}, "collect": LOGS, + "seconds": verifier.get("timeout_sec") or 3000, + "network": verifier.get("network_mode") == "public"} + # Missing or empty patches apply nothing, exactly as PatchReplayAgent does. + apply = (f"cp {CAPTURED} {LOGS}/model.patch; " + f"if [ -s {CAPTURED} ]; then cp {CAPTURED} /tmp/replay.patch; {replay()}; fi; {check}") return {"prompt": prompt, "environment": "task", "image": image, - **({"agent_seconds": int(agent)} if agent else {}), # the task's own budget, not the run's - "verify": {"copy": {f"{TASKS}/{unit}/tests": "/tests"}, "run": ["bash", "-c", check], "collect": LOGS, - "seconds": verifier.get("timeout_sec") or 3000, - "network": verifier.get("network_mode") == "public"}} + **({"agent_seconds": int(agent)} if agent else {}), + "verify": {**common, "run": ["bash", "-c", apply], + "capture": {"run": ["bash", "-c", capture()], "collect": os.path.dirname(CAPTURED), "seconds": 300}, + "in_place": {**common, "run": ["bash", "-c", check]}}} def score(unit, dir, transcript, answer, verified=None): @@ -154,6 +169,10 @@ def score(unit, dir, transcript, answer, verified=None): except (OSError, ValueError): detail["why"] = "test.sh wrote no reward" reward = 0.0 + if verified.get("timed_out"): + reward = 0.0 + if verified.get("in_place"): + detail["in_place"] = score(unit, dir, transcript, answer, verified=verified["in_place"]) return {"reward": 1.0 if reward >= 1.0 else 0.0, "passed": reward >= 1.0, "detail": detail} diff --git a/app/nullius/catalogue/benchmarks/swe-bench-pro/standard.json b/app/nullius/catalogue/benchmarks/swe-bench-pro/standard.json index 2223cdfef..d34365452 100644 --- a/app/nullius/catalogue/benchmarks/swe-bench-pro/standard.json +++ b/app/nullius/catalogue/benchmarks/swe-bench-pro/standard.json @@ -2,7 +2,7 @@ "schema": "nullius.benchmark/v1", "key": "swe-bench-pro", "label": "SWE-bench Pro", - "summary": "Each task is a pull request's description and the authors' container for it, the repository at its base commit in /app; the agent implements the change there with no way out but its model, and the task's own tests, run there once it has ended, say whether every required test passes.", + "summary": "Each task is a pull request's description and the authors' container for it, the repository at its base commit in /app; the agent implements the change there with no way out but its model, and the task's own tests, run in a fresh image with its captured patch, say whether every required test passes.", "family": "agent", "needs": [ "agent.workspace/v1" diff --git a/app/nullius/catalogue/benchmarks/swe-bench-pro/upstream-settings.json b/app/nullius/catalogue/benchmarks/swe-bench-pro/upstream-settings.json index bff53a99b..eb2b0df2b 100644 --- a/app/nullius/catalogue/benchmarks/swe-bench-pro/upstream-settings.json +++ b/app/nullius/catalogue/benchmarks/swe-bench-pro/upstream-settings.json @@ -24,11 +24,11 @@ {"entry": "harbor run -p v2/tasks", "setting": "the 50 minutes: Harbor's agent timeout for Claude Code, an in-sandbox timeout of agent.timeout_sec less 60 s for mini-swe-agent and Codex; the partial diff is still graded", "values": "", "default": "3000, 2940", "nullius": "fixed:3000 s - the task's agent.timeout_sec is the agent's limit; a task cut there is still scored (limits.scored_cuts) for an agent run over ACP; one started as a command (mini-swe-agent) ends as its timeout, unscored; said in the limitations"}, {"entry": "harbor run -p v2/tasks", "setting": "the locked agents' capture of the diff: its own 300 s, a failure ignored", "values": "", "default": "300", - "nullius": "fixed:within the check's limit - the capture is the check's first step, its time counted in the check's 3000 s; a failure does not stop the tests"}, + "nullius": "fixed:300 s - the upstream capture command runs before either check; a timed-out capture is a verifier error"}, {"entry": "harbor run -p v2/tasks", "setting": "Harbor's verifier removes /logs/verifier/reward.txt and reward.json before a task's tests (Harbor 0.25 and later)", "values": "", "default": "", "nullius": "fixed:the same - the check removes both before test.sh, so only a reward the tests wrote is read"}, {"entry": "harbor run -p v2/tasks", "setting": "-a patch_replay:PatchReplayAgent -m replay --ak source_job, --ak patch_name (the diff applied to a fresh image and graded again: the authoritative score)", "values": "", "default": "", - "nullius": "not offered - the standard runs a task's check in the container the agent worked in; the captured diff is kept as verifier/model.patch; said in the limitations"}, + "nullius": "fixed:the authoritative reward - the upstream replay commands apply the captured patch in a fresh image before test.sh; both checks are kept"}, {"entry": "harbor run -p v2/tasks", "setting": "-a host_mini_swe:HostMiniSweAgent (--ak step_limit, cost_limit, command_timeout, cwd, deterministic_outputs_file)", "values": "", "default": "", "nullius": "not offered - mini-swe-agent's loop kept outside a sandbox with no network at all; the standard's agents work in the container and reach their model through the relay"}, {"entry": "harbor run -p v2/tasks", "setting": "-e (modal, docker), -n (trials at once)", "values": "", "default": "modal, 50", diff --git a/app/nullius/catalogue/benchmarks/terminal-bench-pro/benchmark.json b/app/nullius/catalogue/benchmarks/terminal-bench-pro/benchmark.json index 4bc017240..6f901bda2 100644 --- a/app/nullius/catalogue/benchmarks/terminal-bench-pro/benchmark.json +++ b/app/nullius/catalogue/benchmarks/terminal-bench-pro/benchmark.json @@ -23,11 +23,9 @@ "Most tests download package lists and uv within their time limit, 360 seconds for 164 tasks: on a slow connection they can time out." ], "limitations": [ - "optimize-product-search-query and retrieve-vault-root-token are left out: their image starts a service from its ENTRYPOINT, which Nullius replaces and Harbor keeps.", - "Nullius gives public internet access to 23 tasks, those whose reference solution downloads something, during the agent or reference solution. The other 175 keep only their model route; Harbor gives it to every task.", - "On Nullius, the tests get internet access after the agent ends. What the agent left running is stopped first, except in the 12 tasks whose tests need it.", - "fix-jni-unsatisfiedlinkerror-path cannot pass on Nullius: its tests download a Maven plugin, and Maven ignores the proxy variables that are the tests' only way out.", - "The 195 tasks that build on the authors' registry have not been run through Nullius." + "Nullius gives public internet access to 23 tasks, those whose reference solution downloads something, during the agent or reference solution. The other 177 keep only their model route; Harbor gives it to every task.", + "On Nullius, the tests get internet access after the agent ends. What the agent left running is stopped first, except in the 14 tasks whose tests need it.", + "The 197 tasks that build on the authors' registry have not been run through Nullius." ], "datasets": [ { diff --git a/app/nullius/catalogue/benchmarks/terminal-bench-pro/driver.py b/app/nullius/catalogue/benchmarks/terminal-bench-pro/driver.py index e20b3b20c..199f39145 100644 --- a/app/nullius/catalogue/benchmarks/terminal-bench-pro/driver.py +++ b/app/nullius/catalogue/benchmarks/terminal-bench-pro/driver.py @@ -8,8 +8,7 @@ units - the dataset's tasks: one that builds fast from a public base image and downloads nothing (``small``), or every task folder of the - upstream but the two whose image this runner cannot start as - published (``full``) + upstream (``full``) describe - the task's id as its title, its instruction as its text, and its task.toml's metadata difficulty and category as categories setup - the task's instruction as the prompt; its own image (``image``: its @@ -41,10 +40,8 @@ # the checks of the other two (bash-ddos-traffic-analyzer, train-fraud-detection-model) download their test runner. SMALL = ["python-prime-http-server"] -# Tasks whose image starts the task's service from its ENTRYPOINT (a database, a secrets server). The -# unit's container is kept alive by a command of the run's in place of the image's entrypoint, so the -# service would never start: they are left out. -LEFT_OUT = {"optimize-product-search-query", "retrieve-vault-root-token"} +# These images start the task's service before exec'ing their command. +ENTRYPOINT = {"optimize-product-search-query", "retrieve-vault-root-token"} # Tasks whose reference solution fetches something (a package manager, a download, a model or a dataset # from a hub), from reading each solve.sh at the pinned commit. The benchmark grants them the internet, @@ -86,7 +83,7 @@ def tasks(): """Every task folder of the upstream this benchmark runs, by name.""" root = os.environ["NULLIUS_UPSTREAM"] return sorted(d for d in os.listdir(root) - if d not in LEFT_OUT and os.path.isfile(os.path.join(root, d, "task.toml"))) + if os.path.isfile(os.path.join(root, d, "task.toml"))) def listed(dataset): @@ -126,7 +123,7 @@ def setup(unit, dir): with open(os.path.join(here, "instruction.md")) as f: prompt = f.read().strip() env = t.get("environment") or {} - image = {"build": f"{unit}/environment"} + image = {"build": f"{unit}/environment", **({"keep_entrypoint": True} if unit in ENTRYPOINT else {})} if env.get("memory_mb"): image["memory_mb"] = env["memory_mb"] if env.get("cpus"): @@ -137,7 +134,7 @@ def setup(unit, dir): **({"agent_seconds": agent} if agent else {}), # the task's own agent timeout, not the run's "verify": {"copy": {f"{unit}/tests": "/tests"}, "run": CHECK, "collect": LOGS, "seconds": (t.get("verifier") or {}).get("timeout_sec") or 600, "network": True, - **({"keep_processes": True} if unit in KEEP_PROCESSES else {})}} + **({"keep_processes": True} if unit in KEEP_PROCESSES | ENTRYPOINT else {})}} def score(unit, dir, transcript, answer, verified=None): diff --git a/app/nullius/catalogue/benchmarks/terminal-bench-pro/standard.json b/app/nullius/catalogue/benchmarks/terminal-bench-pro/standard.json index 1d6a110a4..11d04f1ab 100644 --- a/app/nullius/catalogue/benchmarks/terminal-bench-pro/standard.json +++ b/app/nullius/catalogue/benchmarks/terminal-bench-pro/standard.json @@ -31,9 +31,9 @@ }, { "id": "full", - "label": "All 198 tasks", - "summary": "195 of them need the authors' registry and end in setup errors without it.", - "units": 198, + "label": "All 200 tasks", + "summary": "197 of them need the authors' registry and end in setup errors without it.", + "units": 200, "environment": "task" } ], diff --git a/app/nullius/catalogue/benchmarks/terminal-bench-pro/upstream-settings.json b/app/nullius/catalogue/benchmarks/terminal-bench-pro/upstream-settings.json index e759d2c7b..9aad4044f 100644 --- a/app/nullius/catalogue/benchmarks/terminal-bench-pro/upstream-settings.json +++ b/app/nullius/catalogue/benchmarks/terminal-bench-pro/upstream-settings.json @@ -48,7 +48,7 @@ {"entry": "environment/Dockerfile", "setting": "FROM", "values": "two images of the authors' registry (197 tasks), python:3.11-slim, python:3.13-slim", "default": "per task", "nullius": "fixed:as published - no image is substituted; said in the limitations"}, {"entry": "environment/Dockerfile", "setting": "ENTRYPOINT, CMD", "values": "per task", "default": "per task", - "nullius": "fixed:replaced - the run keeps the container alive with a command of its own, where Harbor replaces the CMD alone; the two tasks whose ENTRYPOINT starts their service are left out"}, + "nullius": "fixed:kept for service tasks - the two tasks whose ENTRYPOINT starts their service opt in to keeping it, with the keep-alive as CMD"}, {"entry": "README", "setting": "Submission of results by email", "values": "", "default": "", "nullius": "not offered - a local run is not a leaderboard entry"} ] diff --git a/app/nullius/runs/parse.py b/app/nullius/runs/parse.py index 80bd3ca5c..8b1fdf3d5 100644 --- a/app/nullius/runs/parse.py +++ b/app/nullius/runs/parse.py @@ -34,7 +34,7 @@ # The shape this module produces. A workspace caches parsed Jobs keyed on it, # so bump it when a Trial or Job field is added, renamed or means something # new — otherwise a cache written by the old parse is read back as current. -SCHEMA = "32" +SCHEMA = "33" # What a rate-limit record in `agent/gateway.log` looks like. The agent's SDK # retries a 429 below the harness, so a limit the run survived leaves nothing in result.json — diff --git a/app/nullius/standard/backends/container.py b/app/nullius/standard/backends/container.py index 6334c345f..b514f5e12 100644 --- a/app/nullius/standard/backends/container.py +++ b/app/nullius/standard/backends/container.py @@ -1005,20 +1005,28 @@ def door_argv(image: str, *, name: str, job: str, port: int, socket_path: str, image, "python3", FORWARD_IN, "--listen", f"0.0.0.0:{port}"] -# A new drop-in per online phase adds only the six proxy variables to sudo's +# A new drop-in per online phase adds only the proxy variables to sudo's # environment allowlist. Its existing policy is not rewritten. PROXY_SUDOERS = r'''set -eu test ! -L /etc/sudoers.d mkdir -p /etc/sudoers.d policy=$(mktemp /etc/sudoers.d/nullius-egress-XXXXXXXXXX) trap 'rm -f "$policy"' 0 -printf '%s\n' 'Defaults env_keep += "HTTP_PROXY HTTPS_PROXY http_proxy https_proxy NO_PROXY no_proxy"' > "$policy" +printf '%s\n' 'Defaults env_keep += "HTTP_PROXY HTTPS_PROXY http_proxy https_proxy NO_PROXY no_proxy JAVA_TOOL_OPTIONS"' > "$policy" chmod 0440 "$policy" printf '%s\n' "$policy" trap - 0 ''' +# Read the image's existing options in the container, not from the host. +JVM_PROXY = ('if [ -n "${HTTPS_PROXY:-}" ]; then p="${HTTPS_PROXY#*://}"; p="${p%/}"; ' + 'export JAVA_TOOL_OPTIONS="${JAVA_TOOL_OPTIONS:+$JAVA_TOOL_OPTIONS }' + '-Dhttp.proxyHost=${p%:*} -Dhttp.proxyPort=${p##*:} -Dhttps.proxyHost=${p%:*} -Dhttps.proxyPort=${p##*:} ' + '-Dhttp.nonProxyHosts=localhost|127.*|[::1]|0.0.0.0 ' + '-Daether.connector.http.useSystemProperties=true"; fi; exec "$@"') + + def proxy_env(direct: Iterable[str] = ()) -> Dict[str, str]: """The variables that send HTTP(S) through the ``egress`` proxy; this machine's loopback and ``direct`` (the unit's relay, doors and servers) are @@ -1325,7 +1333,7 @@ def stop(self): RUNTIMES = "/opt/nullius" # where an own image is given what the agent runs on PYTHON_VERSION = "3.12.14" # the standalone Python an agent started as python3 runs on there; moves with UV_VERSION _PULL = re.compile(r"^[a-z0-9][a-z0-9._/:-]*@sha256:[0-9a-f]{64}$") -IMAGE_SPEC = ("build", "pull", "memory_mb", "cpus") +IMAGE_SPEC = ("build", "pull", "memory_mb", "cpus", "keep_entrypoint") KEEP_ALIVE = ["sh", "-c", "while :; do sleep 3600; done"] INIT = "/usr/sbin/docker-init" # what --init mounts: docker's, not the unit's @@ -1350,12 +1358,12 @@ def stop(self): # killed, round after round until a scan finds none; a zombie is init's to # reap and is passed over. Says each it stopped; exit 1 with what is left when # twenty rounds were not enough. -SETTLE = r"""keep=$1; n=0 +SETTLE = r"""keep=$1; initial=${2-}; n=0 while :; do left= for d in /proc/[0-9]*; do p=${d#/proc/} - case " 1 $keep $$ " in *" $p "*) continue ;; esac""" + _SCAN + r""" case $1 in Z|X|x) continue ;; esac + case " 1 $keep $initial $$ " in *" $p "*) continue ;; esac""" + _SCAN + r""" case $1 in Z|X|x) continue ;; esac [ "$2" = "$keep" ] && continue left="$left $p" done @@ -1403,6 +1411,8 @@ def spec_problems(spec) -> List[str]: bad.append("image: one of build (a folder with a Dockerfile) or pull (a reference by digest)") if "pull" in spec and not _PULL.match(str(spec["pull"])): bad.append(f"image.pull: {spec['pull']!r} is not pinned by digest (@sha256:<64 hex>)") + if "keep_entrypoint" in spec and not isinstance(spec["keep_entrypoint"], bool): + bad.append("image.keep_entrypoint: true or false") for k in ("memory_mb", "cpus"): if k in spec and (not isinstance(spec[k], (int, float)) or isinstance(spec[k], bool) or spec[k] <= 0): bad.append(f"image.{k}: a positive number") @@ -1620,7 +1630,8 @@ def in_runtime(cmd: List[str], runtimes: Dict[str, Tuple[str, str]]) -> List[str class Box: """A unit's own container: the task's image, kept running for the whole unit so the agent, a control's reference solution and the benchmark's - check all act on one container's state, one after the other. + check normally act on one container's state, one after the other. A check + with a capture step uses :meth:`fresh` for its authoritative result. It runs as the image's own user, as the task was written for - usually root, which its tasks need - @@ -1635,8 +1646,8 @@ class Box: otherwise still run while the check's files are copied in and while the check has a way out: free to rewrite the tests, or to reach what the check's network reaches. So every process but docker's init and the - keep-alive is stopped, as root in the box, and the box is confirmed empty - of them, before anything is copied in. A task about a service the agent + keep-alive and preserved entrypoint services is stopped, as root in the + box, and the box is confirmed empty of them, before anything is copied in. A task about a service the agent must leave running opts out with its ``verify`` step's ``keep_processes``. **The check's way out is a proxy, not a bridge** (:meth:`online`). The @@ -1668,10 +1679,14 @@ class Box: def __init__(self, job: str, tag: str, image: str, *, workdir: str, path: str = IMAGE_PATH, network: Optional[str] = None, mounted: Iterable[Tuple[str, bool]] = (), runtimes: Optional[Dict[str, Tuple[str, str]]] = None, task: Optional[dict] = None, app: Optional[str] = None, env: Optional[dict] = None, - volumes: Optional[Dict[str, str]] = None): + volumes: Optional[Dict[str, str]] = None, keep_entrypoint: bool = False): n = names(job, tag) self.job, self.image, self.workdir, self.path = job, image, workdir, path + self.tag = tag self.env = dict(env or {}) + self.keep_entrypoint = keep_entrypoint + self.initial_pids = "" + self.ready_file = "/tmp/nullius-keeper-" + token_hex(16) self.name = n["agent"] self.net = network or n["network"] self.own_net = network is None @@ -1703,13 +1718,25 @@ def start(self) -> "Box": for host, inside in self.volumes.items(): a += ["-v", f"{host}:{inside}" if inside.endswith(":ro") else f"{host}:{inside}:rw"] self.up = True - _docker(a + ["--entrypoint", KEEP_ALIVE[0], self.image] + KEEP_ALIVE[1:], timeout=300) + command = ([self.image, "sh", "-c", 'echo "$$" > "$1"; ' + KEEP_ALIVE[-1], "keep", self.ready_file] + if self.keep_entrypoint else ["--entrypoint", KEEP_ALIVE[0], self.image] + KEEP_ALIVE[1:]) + _docker(a + command, timeout=300) self.keep = self.keeper() + if self.keep_entrypoint: + r = self.run(["sh", "-c", 'for d in /proc/[0-9]*; do p=${d#/proc/}; [ "$p" = "$$" ] || echo "$p"; done'], 30, user="0") + if r["exit"] != 0: + raise Unavailable("the entrypoint's processes could not be recorded") + self.initial_pids = " ".join(p for p in r["output"].split() if p.isdigit()) except Exception: self.stop() raise return self + def fresh(self) -> "Box": + """The same image and limits on a new network, without the agent's mounts or writes.""" + return Box(self.job, self.tag + "-verify", self.image, workdir=self.workdir, path=self.path, + task=self.task, keep_entrypoint=self.keep_entrypoint).start() + def exec_argv(self, cmd: List[str], env: Dict[str, str], path: str, *, interactive: bool = True, workdir: Optional[str] = None) -> List[str]: """``docker exec`` of a command in the box, its environment as @@ -1721,6 +1748,8 @@ def exec_argv(self, cmd: List[str], env: Dict[str, str], path: str, *, interacti def run(self, cmd: List[str], seconds: float, *, user: Optional[str] = None, env: Optional[dict] = None) -> dict: """A command run in the box, to its end or ``seconds``: {exit, output, timed_out}. ``exit`` is None when it timed out.""" + if (env or {}).get("HTTPS_PROXY"): + cmd = ["sh", "-c", JVM_PROXY, "proxy", *cmd] a = ["exec", "-w", self.workdir] + (["-u", user] if user else []) for k in sorted(env or {}): a += ["-e", k] @@ -1762,10 +1791,12 @@ def copy_out(self, src: str, dest: str) -> bool: def keeper(self, timeout: float = 10) -> str: """The keep-alive's PID inside: the one child of docker's init, read - right after the start, before anything else runs in the box.""" + right after the start. A preserved entrypoint must reach the command + that writes the readiness file within the same bounded wait.""" end = time.time() + timeout while True: - r = self.run(["sh", "-c", KEEPER], 30, user="0") + command = ["cat", self.ready_file] if self.keep_entrypoint else ["sh", "-c", KEEPER] + r = self.run(command, min(5, max(0.1, end - time.time())), user="0") pids = r["output"].split() if r["exit"] == 0 and len(pids) == 1 and pids[0].isdigit(): return pids[0] @@ -1784,7 +1815,7 @@ def settle(self) -> List[str]: still running after it - the check is not run beside them.""" if not self.keep: raise Unavailable("the container's keep-alive is not known: its processes cannot be told apart") - r = self.run(self.settle_argv(self.keep), 120, user="0") + r = self.run(self.settle_argv(self.keep) + [self.initial_pids], 120, user="0") said = r["output"].splitlines() if r["exit"] != 0: raise Unavailable("what the agent left running could not be stopped: " + (said[-1] if said else diff --git a/app/nullius/standard/backends/egress.py b/app/nullius/standard/backends/egress.py index ed2b4b4c7..08d5b771a 100644 --- a/app/nullius/standard/backends/egress.py +++ b/app/nullius/standard/backends/egress.py @@ -12,8 +12,8 @@ docker bridge and the machine behind it. It connects to the address it checked, not to the name again, so a name that resolves differently the second time gains nothing. ``CONNECT`` is passed through unread (TLS stays the -client's); a plain ``http://`` request is sent on with ``Connection: close``, -so one connection is one destination. +client's); an absolute HTTP(S) request is sent on with ``Connection: close`` +and verified TLS for HTTPS, so one connection is one destination. Why a proxy and not firewall rules: rules on docker's ``DOCKER-USER`` chain need root on the machine, and a host without it would have to run the check @@ -33,6 +33,7 @@ import ipaddress import json import socket +import ssl import sys import threading from typing import List, Optional, Tuple @@ -111,29 +112,30 @@ def _read_head(conn: socket.socket) -> Tuple[bytes, bytes]: return head, rest -def target(head: bytes) -> Tuple[str, str, int, bytes]: - """(method, host, port, the head as the origin is sent it) from a request +def target(head: bytes) -> Tuple[str, str, int, bytes, bool]: + """(method, host, port, the head as the origin is sent it, TLS) from a request head; ValueError when it is not a proxy request.""" lines = head.decode("iso-8859-1").split("\r\n") method, uri, version = lines[0].split(" ", 2) if method.upper() == "CONNECT": host, _, port = uri.rpartition(":") - return "CONNECT", host.strip("[]"), int(port), b"" + return "CONNECT", host.strip("[]"), int(port), b"", False u = urlsplit(uri) - if u.scheme != "http" or not u.hostname: - raise ValueError("an absolute http:// URL, or CONNECT host:port") + if u.scheme not in ("http", "https") or not u.hostname: + raise ValueError("an absolute HTTP(S) URL, or CONNECT host:port") path = (u.path or "/") + ("?" + u.query if u.query else "") kept = [l for l in lines[1:] if l and l.split(":", 1)[0].strip().lower() not in HOP] out = "\r\n".join([f"{method} {path} {version}"] + kept + ["Connection: close", "", ""]) - return method, u.hostname, u.port or 80, out.encode("iso-8859-1") + return method, u.hostname, u.port or (443 if u.scheme == "https" else 80), out.encode("iso-8859-1"), u.scheme == "https" def _serve(conn: socket.socket) -> None: + up = None try: conn.settimeout(60) head, rest = _read_head(conn) try: - method, host, port, origin_head = target(head) + method, host, port, origin_head, tls = target(head) if not 0 < port < 65536: raise ValueError("a port") except (ValueError, IndexError): @@ -149,6 +151,8 @@ def _serve(conn: socket.socket) -> None: up = socket.socket(family, socket.SOCK_STREAM) up.settimeout(30) up.connect(sockaddr) + if tls: + up = ssl.create_default_context().wrap_socket(up, server_hostname=host) up.settimeout(None) except OSError as e: _say("unreachable", host=host, port=port, error=str(e)[:200]) @@ -168,6 +172,8 @@ def _serve(conn: socket.socket) -> None: pass finally: try: + if up is not None: + up.close() conn.close() except OSError: pass diff --git a/app/nullius/standard/contract/definitions.py b/app/nullius/standard/contract/definitions.py index d40ca7acf..557987500 100644 --- a/app/nullius/standard/contract/definitions.py +++ b/app/nullius/standard/contract/definitions.py @@ -1632,15 +1632,16 @@ def _own_agents(d: dict) -> List[str]: return bad -STEP = ("copy", "write", "run", "collect", "seconds", "network", "keep_processes") +STEP = ("copy", "write", "run", "collect", "seconds", "network", "keep_processes", "capture", "in_place") -def step_problems(step, *, collect: bool) -> List[str]: +def step_problems(step, *, collect: bool, fresh: bool = True) -> List[str]: """Validate a preparation, solve or verification step in a unit container.""" if not isinstance(step, dict): return ["a step: {copy?, write?, run, collect?, seconds?, network?, keep_processes?}"] bad = [f"{k}: not a field ({', '.join(STEP)})" for k in step - if k not in STEP or (k in ("collect", "keep_processes") and not collect)] + if k not in STEP or (k in ("collect", "keep_processes", "capture", "in_place") and not collect) + or (k in ("capture", "in_place") and not fresh)] run = step.get("run") if not isinstance(run, list) or not run or not all(isinstance(w, str) and w for w in run): bad.append("run: the command, a list of words") @@ -1659,6 +1660,17 @@ def step_problems(step, *, collect: bool) -> List[str]: bad.append("network: true or false") if "keep_processes" in step and not isinstance(step["keep_processes"], bool): bad.append("keep_processes: true or false") + if "capture" in step: + capture = step["capture"] + bad += ["capture." + p for p in step_problems(capture, collect=True, fresh=False)] + if isinstance(capture, dict) and not capture.get("collect"): + bad.append("capture.collect: the folder transferred to the fresh container at the same path") + if step.get("keep_processes"): + bad.append("keep_processes: not with a fresh check") + if "in_place" in step: + if "capture" not in step: + bad.append("in_place: needs capture and a fresh check") + bad += ["in_place." + p for p in step_problems(step["in_place"], collect=True, fresh=False)] return bad diff --git a/app/nullius/standard/runner/run.py b/app/nullius/standard/runner/run.py index 5d43603a5..c44afb814 100644 --- a/app/nullius/standard/runner/run.py +++ b/app/nullius/standard/runner/run.py @@ -36,9 +36,11 @@ the image (``image``: a folder of the upstream to build, or a reference by digest) and, optionally, the working directory (``workdir``; the image's own by default) and a check (``verify``) - files of the upstream copied in, a -command run, a folder of results copied out - which runs in that container -after the agent ends and before ``score``, which is sent what it found -(``verified``: {exit, timed_out, output, dir, collected}) and reads the rest from ``dir``. The +command run, a folder of results copied out - which runs after the agent ends. +A ``capture`` step transfers its collected files into a fresh container for the +check; an optional ``in_place`` step keeps the original check beside it. +``score`` receives what it found (``verified``: {exit, timed_out, output, dir, +collected}) and reads the rest from ``dir``. The oracle's reference solution is such a step too (its reply's ``solve``). So the driver never needs docker, and the task's tests reach the container only once the agent is done and nothing it started still runs there @@ -2786,7 +2788,8 @@ def own_box(self, tag: str, setup: dict, rl, home: str): box = container.Box(self.name, tag, image, workdir=setup.get("workdir") or cfg["workdir"], path=cfg["path"], network=rl.names["network"] if isinstance(rl, container.Unit) else None, mounted=mounted, runtimes=runtimes, app=APP, env=setup.get("env"), volumes=volumes, - task={k: spec[k] for k in ("cpus", "memory_mb") if k in spec}).start() + task={k: spec[k] for k in ("cpus", "memory_mb") if k in spec}, + keep_entrypoint=spec.get("keep_entrypoint", False)).start() for name in runtimes: why = box.runtime_problem(name) if why: @@ -2926,13 +2929,42 @@ def prepare(self, step: dict, box, trial: str, *, agent: bool = False) -> None: + ("did not end in time" if done["timed_out"] else f"ended with exit {done['exit']}") + ": " + done["output"].strip()[-300:], retryable=not done["timed_out"]) - def verify(self, step: dict, box, trial: str) -> dict: + def verify(self, step: dict, box, trial: str, *, folder: str = "verifier", allow_timeout: bool = False, separate_files: bool = False) -> dict: """The benchmark's check, run in the unit's container once the agent has ended (``in_box``), what it collects copied out into the trial's ``verifier/`` and its output kept there (``test-stdout.txt``, and what its proxy let through and refused, ``egress.log``): what ``score`` is - sent as ``verified``, the folder to read the rest from.""" - out = os.path.join(trial, "verifier") + sent as ``verified``, the folder to read the rest from. With ``capture``, + only captured files cross into a fresh box; ``in_place`` keeps the + original check beside the fresh result.""" + bad = container.step_problems(step, collect=True) + if bad: + raise _Ended("VerifierError", "the benchmark's check: " + "; ".join(bad)) + if "capture" in step: + out = os.path.join(trial, folder) + capture = self.verify(step["capture"], box, out, folder="capture", separate_files=True) + if capture["exit"] != 0 or not capture["collected"]: + raise _Ended("VerifierError", "the benchmark's capture failed or its folder is missing") + original = None + fresh = None + try: + box.offline() + if "in_place" in step: + original = self.verify(step["in_place"], box, out, folder="in-place", allow_timeout=True) + box.offline() + fresh = box.fresh() + fresh.copy_in(capture["dir"], step["capture"]["collect"]) + done = self.verify({k: v for k, v in step.items() if k not in ("capture", "in_place")}, fresh, trial) + done["capture"] = capture + if original is not None: + done["in_place"] = original + return done + except (container.Unavailable, ValueError, OSError) as e: + raise _Ended("VerifierError", "the fresh check: " + str(e)) + finally: + if fresh is not None: + fresh.stop() + out = os.path.join(trial, folder) os.makedirs(out, exist_ok=True) try: done = self.in_box(box, step, collect=True, what="the benchmark's check", out=out) @@ -2943,12 +2975,13 @@ def verify(self, step: dict, box, trial: str) -> dict: f.write(said) with open(os.path.join(out, "test-stdout.txt"), "w") as f: f.write(done["output"]) - collected = box.copy_out(step["collect"], out) if step.get("collect") else False - if done["timed_out"]: + files = os.path.join(out, "files") if separate_files else out + collected = box.copy_out(step["collect"], files) if step.get("collect") else False + if done["timed_out"] and not allow_timeout: raise _Ended("VerifierError", "the benchmark's check did not end in time: " + done["output"].strip()[-300:], retryable=False) return {"exit": done["exit"], "timed_out": done["timed_out"], "output": done["output"][-4000:], - "dir": out, "collected": collected} + "dir": files, "collected": collected} # -- an agent, over ACP ---------------------------------------------------- def simulator(self, rl, tag: str) -> dict: diff --git a/app/tests/test_standard_check_safety.py b/app/tests/test_standard_check_safety.py index e97f54a86..60c69a69e 100644 --- a/app/tests/test_standard_check_safety.py +++ b/app/tests/test_standard_check_safety.py @@ -36,6 +36,13 @@ def test_a_check_may_keep_what_the_agent_left_running(self): solve = {"copy": {"s": "/solution"}, "run": ["sh", "/solution/solve.sh"], "keep_processes": True} self.assertTrue(any("keep_processes: not a field" in p for p in container.step_problems(solve, collect=False))) + def test_fresh_check_needs_a_bounded_capture_step_and_no_nested_regrade(self): + capture = {"run": ["capture"], "collect": "/patch", "seconds": 30} + self.assertEqual(container.step_problems(dict(self.BASE, capture=capture, in_place=self.BASE), collect=True), []) + for extra in ({"capture": {"run": ["capture"]}}, {"in_place": self.BASE}, + {"capture": {**capture, "capture": capture}}, {"capture": capture, "keep_processes": True}): + self.assertTrue(container.step_problems(dict(self.BASE, **extra), collect=True)) + def _fake_proc(root: str, procs: dict): """A /proc of our own: pid -> (comm, state, ppid).""" @@ -200,6 +207,39 @@ def test_a_reference_solution_is_not_settled(self): self.r.in_box(box, {"copy": {"tests": "/solution"}, "run": ["sh", "/solution/solve.sh"]}, collect=False, what="oracle") self.assertNotIn("settle", box.did) + def test_capture_is_transferred_and_only_the_fresh_result_is_primary(self): + box, fresh = FakeBox(exit=1), FakeBox(exit=0) + capture = {"run": ["capture"], "collect": "/captured"} + box.run = mock.Mock(side_effect=lambda cmd, *a, **kw: {"exit": 0 if cmd[0] == "capture" else 1, + "output": "original", "timed_out": False}) + with mock.patch.object(box, "fresh", return_value=fresh, create=True), \ + mock.patch.object(fresh, "stop", create=True) as stop: + got = self.r.verify({**self.step, "capture": capture, "in_place": self.step}, box, self.tmp) + self.assertEqual(got["exit"], 0) + self.assertEqual(got["in_place"]["exit"], 1) + self.assertEqual(got["capture"]["exit"], 0) + self.assertEqual(fresh.did[0], "copy /captured") + self.assertEqual(got["in_place"]["dir"], os.path.join(self.tmp, "verifier", "in-place")) + self.assertEqual(got["dir"], os.path.join(self.tmp, "verifier")) + stop.assert_called_once() + + def test_failed_or_missing_capture_never_starts_a_fresh_check(self): + for exit, collected in ((1, True), (0, False)): + box = FakeBox(exit=exit) + with mock.patch.object(box, "copy_out", return_value=collected), \ + mock.patch.object(box, "fresh", create=True) as fresh: + with self.assertRaisesRegex(run._Ended, "capture failed"): + self.r.verify({**self.step, "capture": {"run": ["capture"], "collect": "/patch"}}, box, self.tmp) + fresh.assert_not_called() + + def test_fresh_check_failure_always_removes_its_container(self): + box, fresh = FakeBox(), FakeBox(fail_settle=True) + with mock.patch.object(box, "fresh", return_value=fresh, create=True), \ + mock.patch.object(fresh, "stop", create=True) as stop: + with self.assertRaises(run._Ended): + self.r.verify({**self.step, "capture": {"run": ["capture"], "collect": "/patch"}}, box, self.tmp) + stop.assert_called_once() + class Prepare(unittest.TestCase): """A unit's preparation: run as root before anyone works in the box, its @@ -345,8 +385,9 @@ def test_only_global_addresses_are_reached(self): def test_a_request_names_its_destination(self): self.assertEqual(egress.target(b"CONNECT pypi.org:443 HTTP/1.1\r\nHost: pypi.org:443")[:3], ("CONNECT", "pypi.org", 443)) - m, host, port, head = egress.target(b"GET http://archive.example/ubuntu/x?y=1 HTTP/1.1\r\nHost: archive.example\r\n" + m, host, port, head, tls = egress.target(b"GET http://archive.example/ubuntu/x?y=1 HTTP/1.1\r\nHost: archive.example\r\n" b"Proxy-Connection: keep-alive\r\nUser-Agent: apt") + self.assertFalse(tls) self.assertEqual((m, host, port), ("GET", "archive.example", 80)) self.assertTrue(head.startswith(b"GET /ubuntu/x?y=1 HTTP/1.1\r\n")) self.assertIn(b"Connection: close\r\n", head) @@ -355,6 +396,28 @@ def test_a_request_names_its_destination(self): with self.assertRaises(ValueError): egress.target(b"GET /relative HTTP/1.1\r\nHost: x") + def test_absolute_https_names_tls_and_default_or_explicit_port(self): + for uri, port in (("https://example.org/a?q=1", 443), ("https://example.org:8443/a?q=1", 8443)): + method, host, got_port, head, tls = egress.target(f"GET {uri} HTTP/1.1\r\nHost: example.org".encode()) + self.assertEqual((method, host, got_port, tls), ("GET", "example.org", port, True)) + self.assertTrue(head.startswith(b"GET /a?q=1 HTTP/1.1\r\n")) + + def test_jvm_proxy_preserves_image_options_and_runs_the_requested_command(self): + env = {**os.environ, **container.proxy_env(), "JAVA_TOOL_OPTIONS": "-Xmx1g"} + r = subprocess.run(["sh", "-c", container.JVM_PROXY, "proxy", "sh", "-c", 'printf %s "$JAVA_TOOL_OPTIONS"'], + env=env, capture_output=True, text=True, check=True) + self.assertTrue(r.stdout.startswith("-Xmx1g ")) + for prop in ("http.proxyHost=egress", "https.proxyPort=3128", "aether.connector.http.useSystemProperties=true"): + self.assertIn("-D" + prop, r.stdout) + + def test_box_uses_jvm_proxy_only_for_online_commands(self): + box = container.Box("job", "unit", "img", workdir="/") + with mock.patch.object(container.subprocess, "run", return_value=subprocess.CompletedProcess([], 0, b"")) as call: + box.run(["mvn", "test"], 10, env=container.proxy_env()) + self.assertEqual(call.call_args.args[0][-6:], ["sh", "-c", container.JVM_PROXY, "proxy", "mvn", "test"]) + box.run(["mvn", "test"], 10) + self.assertNotIn(container.JVM_PROXY, call.call_args.args[0]) + class Refusals(unittest.TestCase): """The proxy itself, served on this machine: a private destination, by @@ -392,12 +455,48 @@ def ask(self, raw: bytes) -> bytes: def test_metadata_private_this_machine_and_what_is_not_a_proxy_request_are_refused(self): for raw in (b"GET http://169.254.169.254/latest/meta-data/ HTTP/1.1\r\nHost: 169.254.169.254\r\n\r\n", b"CONNECT 100.100.100.200:443 HTTP/1.1\r\n\r\n", - b"GET http://10.0.0.1/ HTTP/1.1\r\n\r\n", + b"GET https://10.0.0.1/ HTTP/1.1\r\n\r\n", b"CONNECT localhost:%d HTTP/1.1\r\n\r\n" % self.srv.getsockname()[1]): self.assertTrue(self.ask(raw).startswith(b"HTTP/1.1 403"), raw) self.assertEqual([e for e, _ in self.said], ["refused"] * 4) self.assertTrue(self.ask(b"GET / HTTP/1.1\r\nHost: x\r\n\r\n").startswith(b"HTTP/1.1 400")) + def test_absolute_https_reaches_a_verified_tls_origin_at_the_checked_address(self): + import ssl + with tempfile.TemporaryDirectory() as tmp: + cert, key = os.path.join(tmp, "cert.pem"), os.path.join(tmp, "key.pem") + subprocess.run(["openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes", "-days", "1", + "-subj", "/CN=origin.invalid", "-addext", "subjectAltName=DNS:origin.invalid", + "-keyout", key, "-out", cert], check=True, capture_output=True) + class Handler(BaseHTTPRequestHandler): + def do_GET(self): + self.send_response(200) + self.end_headers() + self.wfile.write(self.path.encode()) + def log_message(self, *args): + pass + origin = HTTPServer(("127.0.0.1", 0), Handler) + context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + context.load_cert_chain(cert, key) + origin.socket = context.wrap_socket(origin.socket, server_side=True) + thread = threading.Thread(target=origin.serve_forever, daemon=True) + thread.start() + trusted = ssl.create_default_context(cafile=cert) + try: + with mock.patch.object(egress, "resolve", return_value=((socket.AF_INET, origin.server_address), ["1.1.1.1"])) as resolve, \ + mock.patch.object(egress.ssl, "create_default_context", return_value=trusted): + response = self.ask(b"GET https://origin.invalid/test?q=1 HTTP/1.1\r\nHost: origin.invalid\r\n\r\n") + self.assertIn(b"200 OK", response) + self.assertTrue(response.endswith(b"/test?q=1")) + resolve.assert_called_once_with("origin.invalid", 443) + with mock.patch.object(egress, "resolve", return_value=((socket.AF_INET, origin.server_address), ["1.1.1.1"])): + response = self.ask(b"GET https://origin.invalid/ HTTP/1.1\r\nHost: origin.invalid\r\n\r\n") + self.assertIn(b"502 Bad Gateway", response) # its self-signed certificate is not normally trusted + finally: + origin.shutdown() + origin.server_close() + thread.join(5) + def test_a_local_service_at_the_unspecified_address_bypasses_the_public_proxy(self): class Handler(BaseHTTPRequestHandler): def do_GET(self): @@ -491,6 +590,25 @@ def test_the_tmux_script_leaves_an_image_that_has_it_alone(self): self.assertFalse(os.path.exists(os.path.join(self.tmp, "called"))) +class TerminalBenchPro(unittest.TestCase): + def test_service_tasks_are_listed_and_preserve_their_entrypoint(self): + with tempfile.TemporaryDirectory() as root: + for name in ("optimize-product-search-query", "retrieve-vault-root-token", "ordinary"): + os.mkdir(os.path.join(root, name)) + with open(os.path.join(root, name, "task.toml"), "w") as f: + f.write("[agent]\ntimeout_sec = 3600\n") + with open(os.path.join(root, name, "instruction.md"), "w") as f: + f.write("task") + with mock.patch.dict(os.environ, NULLIUS_UPSTREAM=root), mock.patch("sys.stdin", []): + driver = runpy.run_path(os.path.join(definitions.CATALOGUE, "benchmarks", "terminal-bench-pro", "driver.py")) + self.assertEqual(len(driver["units"]("full")["units"]), 3) + for name in ("optimize-product-search-query", "retrieve-vault-root-token"): + setup = driver["setup"](name, root) + self.assertTrue(setup["image"]["keep_entrypoint"]) + self.assertTrue(setup["verify"]["keep_processes"]) + self.assertNotIn("keep_entrypoint", driver["setup"]("ordinary", root)["image"]) + + def _docker_ready() -> str: return docker_tier.why_not() diff --git a/app/tests/test_standard_own_image.py b/app/tests/test_standard_own_image.py index 8d2e78b9e..307a79646 100644 --- a/app/tests/test_standard_own_image.py +++ b/app/tests/test_standard_own_image.py @@ -67,6 +67,11 @@ def test_an_image_is_built_from_a_folder_or_pulled_by_digest(self): self.assertTrue(any("one of build" in p for p in container.spec_problems({"build": "a", "pull": "b"}))) self.assertTrue(any("memory_mb" in p for p in container.spec_problems({"build": "a", "memory_mb": "lots"}))) + def test_entrypoint_preservation_is_opt_in_and_boolean(self): + for value in (True, False): + self.assertEqual(container.spec_problems({"build": "task/environment", "keep_entrypoint": value}), []) + self.assertTrue(container.spec_problems({"build": "task/environment", "keep_entrypoint": "yes"})) + def test_a_step_names_its_files_command_and_results(self): step = {"copy": {"t": "/tests"}, "run": ["sh", "/tests/x.sh"], "collect": "/logs", "seconds": 5, "network": True} self.assertEqual(container.step_problems(step, collect=True), []) @@ -146,6 +151,31 @@ def test_the_tag_is_the_hash_of_the_folder_built(self): class Runtime(unittest.TestCase): RT = {"node": ("/host/node", "/opt/nullius/node"), "python": ("/host/py", "/opt/nullius/python")} + def test_entrypoint_gets_the_keep_alive_as_command_and_startup_is_bounded(self): + box = container.Box("job", "unit", "img", workdir="/", network="net", keep_entrypoint=True) + with mock.patch.object(container, "_docker") as docker, \ + mock.patch.object(box, "keeper", return_value="7"), \ + mock.patch.object(box, "run", return_value={"exit": 0, "output": "1 7 9"}): + box.start() + argv = docker.call_args.args[0] + self.assertNotIn("--entrypoint", argv) + self.assertEqual(argv[argv.index("img") + 1:][:2], ["sh", "-c"]) + self.assertEqual(box.initial_pids, "1 7 9") + with mock.patch.object(box, "run", return_value={"exit": 0, "output": ""}), \ + mock.patch.object(container.time, "sleep"): + with self.assertRaisesRegex(container.Unavailable, "keep-alive was not found"): + box.keeper(timeout=0) + + def test_a_fresh_box_has_the_image_limits_and_no_agent_or_writable_mounts(self): + box = container.Box("job", "unit", "img", workdir="/app", task={"cpus": 2}, keep_entrypoint=True, + mounted=[("/agent-home", False)], volumes={"/staged": "/data"}, network="agent-net") + with mock.patch.object(container.Box, "start", autospec=True, side_effect=lambda b: b): + fresh = box.fresh() + self.assertEqual((fresh.image, fresh.workdir, fresh.task), ("img", "/app", {"cpus": 2})) + self.assertTrue(fresh.keep_entrypoint) + self.assertNotEqual(fresh.net, box.net) + self.assertEqual((fresh.mounted, fresh.volumes, fresh.runtimes), ([], {}, {})) + def test_the_agent_runs_on_its_runtime_and_the_task_keeps_its_own(self): self.assertEqual(container.in_runtime(["python3", "/x/agent.py"], self.RT), ["/opt/nullius/python/bin/python3", "/x/agent.py"]) self.assertEqual(container.in_runtime(["sh", "/x/run.sh"], self.RT), ["sh", "/x/run.sh"]) @@ -361,3 +391,53 @@ def test_a_run_keeps_its_images_unless_asked_and_always_with_a_repeat(self): with mock.patch.object(container, "fetched", lambda image: True), \ mock.patch.object(container, "drop_image", lambda image: self.fail("dropped")): r.release_image("img:1") + + +@unittest.skipIf(docker_tier.why_not(), docker_tier.why_not() or "") +class FidelityInDocker(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = self.tmp.name + self.r = run.Run.__new__(run.Run) + self.r.up, self.r.bench, self.r.turn_seconds = self.root, {"_here": self.root}, 30 + + def test_only_captured_files_reach_fresh_grading_for_agents_and_controls(self): + for control in ("agent", "nop", "oracle"): + with self.subTest(control=control): + box = container.Box("nullius-test-fidelity", control, container.base_tag(), workdir="/").start() + try: + box.run(["sh", "-c", "echo dirty > /tmp/agent-only; mkdir -p /capture; echo patch > /capture/model.patch"], 10) + check = {"run": ["sh", "-c", "test ! -e /tmp/agent-only && test -f /capture/model.patch"], "seconds": 10} + result = self.r.verify({**check, "capture": {"run": ["true"], "collect": "/capture"}, + "in_place": check}, box, os.path.join(self.root, control)) + self.assertEqual(result["exit"], 0) + self.assertEqual(result["in_place"]["exit"], 1) + self.assertTrue(os.path.isfile(os.path.join(result["capture"]["dir"], "model.patch"))) + finally: + box.stop() + + def test_entrypoint_service_survives_preparation_and_check_and_bad_entrypoint_fails(self): + image = "nullius/test-entrypoint:" + os.path.basename(self.root).lower() + with open(os.path.join(self.root, "Dockerfile"), "w") as f: + f.write(f'FROM {container.base_tag()}\nCOPY entry.sh /entry.sh\nENTRYPOINT ["sh", "/entry.sh"]\n') + with open(os.path.join(self.root, "entry.sh"), "w") as f: + f.write('sleep 3600 &\necho $! > /service.pid\nexec "$@"\n') + container._docker(["build", "-t", image, self.root], timeout=120) + self.addCleanup(container._docker, ["rmi", image], check=False) + box = container.Box("nullius-test-fidelity", "entry", image, workdir="/", keep_entrypoint=True).start() + try: + self.r.prepare({"run": ["true"]}, box, self.root) + result = self.r.verify({"run": ["sh", "-c", 'kill -0 "$(cat /service.pid)"']}, box, self.root) + self.assertEqual(result["exit"], 0) + finally: + box.stop() + with open(os.path.join(self.root, "entry.sh"), "w") as f: + f.write('exec sleep 3600\n') + container._docker(["build", "-t", image, self.root], timeout=120) + box = container.Box("nullius-test-fidelity", "bad-entry", image, workdir="/", keep_entrypoint=True) + keeper = box.keeper + with mock.patch.object(box, "keeper", side_effect=lambda: keeper(timeout=0.5)): + with self.assertRaisesRegex(container.Unavailable, "keep-alive was not found"): + box.start() + self.assertFalse(box.up) diff --git a/app/tests/test_swebench_patch.py b/app/tests/test_swebench_patch.py index cdd6c4533..eec662404 100644 --- a/app/tests/test_swebench_patch.py +++ b/app/tests/test_swebench_patch.py @@ -136,6 +136,10 @@ def setUp(self): (task / "task.toml").write_text('[agent]\ntimeout_sec = 3000.0\n[verifier]\ntimeout_sec = 3000.0\nnetwork_mode = "public"\n') (task / "instruction.md").write_text("Fix\n") (self.root / "up" / "v2" / "tooling").mkdir() + (self.root / "up" / "v2" / "tooling" / "patch_replay.py").write_text( + "class PatchReplayAgent:\n async def run(self, instruction, environment, context):\n" + f" await environment.exec(command={f'git -C {self.repo} apply /tmp/replay.patch'!r})\n" + " await environment.exec(command='true')\n") self.capture_is(f"mkdir -p {self.captured.parent}; cd {self.repo} && git add -A; " f"git diff --cached > {self.captured}; git reset -q; true") env = mock.patch.dict(os.environ, {"NULLIUS_UPSTREAM": str(self.root / "up")}) @@ -159,7 +163,10 @@ def check(self, tests): self.tests.write_text(tests) step = self.driver.setup("unit", str(self.root))["verify"] self.assertEqual(step["collect"], str(self.logs)) - command = step["run"][-1].replace("/tests/test.sh", str(self.tests)) + subprocess.run(step["capture"]["run"], check=True, capture_output=True) + self.git("reset", "--hard", "HEAD") + self.git("clean", "-fd") + command = step["run"][-1].replace("/tests/test.sh", str(self.tests)).replace("/tmp/replay.patch", str(self.root / "replay.patch")) return subprocess.run([*step["run"][:-1], command], capture_output=True).returncode def score(self): @@ -182,11 +189,22 @@ def test_a_reward_left_before_the_tests_is_removed(self): got = self.score() self.assertEqual((got["reward"], got["passed"], got["detail"]["why"]), (0.0, False, "test.sh wrote no reward")) - def test_the_tests_run_when_the_capture_fails(self): + def test_a_failed_capture_cannot_be_regraded(self): self.capture_is("false") - self.assertEqual(self.check(f"echo 1 > {self.logs}/reward.txt\n"), 0) - self.assertFalse((self.logs / "model.patch").exists()) - self.assertTrue(self.score()["passed"]) + with self.assertRaises(subprocess.CalledProcessError): + self.check(f"echo 1 > {self.logs}/reward.txt\n") + self.assertFalse((self.logs / "reward.txt").exists()) + + def test_reward_comes_from_regrading_and_the_original_score_is_kept(self): + original = self.root / "original" + original.mkdir() + (original / "reward.txt").write_text("1") + (self.logs / "reward.txt").write_text("0") + result = self.driver.score("unit", str(self.root), [], "", verified={"dir": str(self.logs), + "in_place": {"dir": str(original), "exit": 0, "timed_out": False}}) + self.assertEqual(result["reward"], 0) + self.assertFalse(result["passed"]) + self.assertEqual(result["detail"]["in_place"]["reward"], 1) def test_a_pin_keeps_its_tag_for_pins_and_is_pulled_by_its_digest(self): image = self.driver.setup("unit", str(self.root))["image"] @@ -196,20 +214,9 @@ def test_a_pin_keeps_its_tag_for_pins_and_is_pulled_by_its_digest(self): class MultilingualPatch(Patch): - """The same cases over SWE-bench Multilingual's driver, whose check also tells the JVM of the tests' proxy.""" + """The same cases over SWE-bench Multilingual's driver, with proxy handling supplied by the container backend.""" DRIVER = BENCHMARKS / "swe-bench-multilingual/driver.py" - def test_check_tells_the_jvm_of_the_proxy_it_is_given(self): - self.eval.write_text('printf %s "${JAVA_TOOL_OPTIONS-unset}" > jvm\n') - plain = {k: v for k, v in os.environ.items() if k not in ("HTTPS_PROXY", "JAVA_TOOL_OPTIONS")} - self.capture(env=plain) - self.assertEqual((self.repo / "jvm").read_text(), "unset") - host, port = container.EGRESS_ALIAS, container.EGRESS_PORT - self.capture(env={**plain, **container.proxy_env(), "JAVA_TOOL_OPTIONS": "-Xmx1g"}) - self.assertEqual((self.repo / "jvm").read_text(), - f"-Xmx1g -Dhttp.proxyHost={host} -Dhttp.proxyPort={port} -Dhttps.proxyHost={host} -Dhttps.proxyPort={port} " - "-Daether.connector.http.useSystemProperties=true") - def test_change_in_another_encoding_is_still_scored(self): (self.repo / "edit").write_bytes(b"caf\xe9\n") patch = self.capture() diff --git a/docs/benchmarks/supported/swe-bench-multilingual.md b/docs/benchmarks/supported/swe-bench-multilingual.md index 8a7afc5d5..5ae66e664 100644 --- a/docs/benchmarks/supported/swe-bench-multilingual.md +++ b/docs/benchmarks/supported/swe-bench-multilingual.md @@ -54,7 +54,6 @@ Software engineering: fix a real GitHub issue in one of nine programming languag - On Nullius, the agent can reach only its model, so it cannot run the tests of the 26 instances that download their test runner. The tests get internet access after the agent ends. - mini-SWE-agent runs here with its general prompt and no step or cost limit of its own. The leaderboard runs it with its SWE-bench prompt, 250 steps, 3 USD per instance and internet access. - On Nullius, the recorded patch is all that differs from the base commit, including what the image's build left there: an agent that changes nothing can still show a patch. -- On Nullius, axios__axios-5085 cannot be resolved: one of its tests calls a public service through axios, and the tests' proxy refuses that request. - SWE-agent, the paper's agent, is not offered: it needs a python command in the instance's image, which 42 of the 300 images have. - Only instances of apache/druid, fmtlib/fmt, gin-gonic/gin, preactjs/preact, reactivex/rxjava and vuejs/core have been run through Nullius. diff --git a/docs/benchmarks/supported/swe-bench-pro.md b/docs/benchmarks/supported/swe-bench-pro.md index 043f6baf2..f4ccdb8cf 100644 --- a/docs/benchmarks/supported/swe-bench-pro.md +++ b/docs/benchmarks/supported/swe-bench-pro.md @@ -37,6 +37,7 @@ Software engineering: change a real repository as a pull request describes, so i ## Good to know +- The reward is the authors’ re-grade: the captured patch replayed in a fresh image. The in-container score is kept beside it, with both test outputs. - Agents work with no internet and their web tools off, as the authors' locked protocol requires. Its commands use high reasoning effort: set the same to compare. - Each task gives the agent 50 minutes. A task cut there is still scored on what the agent changed, except with mini-swe-agent. - V2 scores do not compare with v1 numbers: 89 tasks were dropped, 529 statements rewritten and the tests revised. @@ -51,7 +52,6 @@ Software engineering: change a real repository as a pull request describes, so i ## Nullius limitations -- The tests run in the container the agent worked in. The authors' authoritative score re-grades the agent's diff on a fresh image; Nullius keeps the diff as verifier/model.patch and does not re-grade. - mini-swe-agent runs mini's own config with no cost limit, where the protocol's file adds high effort, a named model class and its own error template; a task cut at 50 minutes is its timeout and not scored, where the protocol grades its diff. - The tests reach the internet through an HTTP and HTTPS proxy to public addresses, where the protocol gives them open access. - Tasks of element-web, navidrome, openlibrary, teleport, tutanota, vuls and webclients have not been run through Nullius. diff --git a/docs/benchmarks/supported/terminal-bench-pro.md b/docs/benchmarks/supported/terminal-bench-pro.md index 3869e54e7..9d7ff8cc8 100644 --- a/docs/benchmarks/supported/terminal-bench-pro.md +++ b/docs/benchmarks/supported/terminal-bench-pro.md @@ -53,11 +53,9 @@ Terminal tasks in a container, in eight balanced categories. ## Nullius limitations -- optimize-product-search-query and retrieve-vault-root-token are left out: their image starts a service from its ENTRYPOINT, which Nullius replaces and Harbor keeps. -- Nullius gives public internet access to 23 tasks, those whose reference solution downloads something, during the agent or reference solution. The other 175 keep only their model route; Harbor gives it to every task. -- On Nullius, the tests get internet access after the agent ends. What the agent left running is stopped first, except in the 12 tasks whose tests need it. -- fix-jni-unsatisfiedlinkerror-path cannot pass on Nullius: its tests download a Maven plugin, and Maven ignores the proxy variables that are the tests' only way out. -- The 195 tasks that build on the authors' registry have not been run through Nullius. +- Nullius gives public internet access to 23 tasks, those whose reference solution downloads something, during the agent or reference solution. The other 177 keep only their model route; Harbor gives it to every task. +- On Nullius, the tests get internet access after the agent ends. What the agent left running is stopped first, except in the 14 tasks whose tests need it. +- The 197 tasks that build on the authors' registry have not been run through Nullius. ## Cite diff --git a/docs/standard.md b/docs/standard.md index 3c748c723..742797022 100644 --- a/docs/standard.md +++ b/docs/standard.md @@ -318,6 +318,7 @@ A benchmark whose tasks are containers (their own Dockerfile and `FROM`) says so | Field | Meaning | | --- | --- | | `image.build` | A folder of the upstream holding a Dockerfile, its whole context: `nullius/own--:`, the sha256 of every file the build reads. On Podman, a short name in its `FROM` may fail under `short-name-mode = "enforcing"`: name the image in full | +| `image.keep_entrypoint` | `true`: keep the image’s ENTRYPOINT and pass the keep-alive as its command. It must reach that command within 10 seconds; otherwise setup fails. Services present then survive preparation and verification | | `image.pull` | A reference pinned by its digest (`name@sha256:...`) | | `image.memory_mb`, `image.cpus` | The task's limits; a machine's [constraint](settings/run-hosts.md#constraints) wins when lower | | `workdir` | The session's `cwd` when not the image's working directory | @@ -327,7 +328,9 @@ A benchmark whose tasks are containers (their own Dockerfile and `FROM`) says so | `env` | Task variables for the agent: uppercase names and string values, no model settings or credentials. The run's variables take precedence; `PATH` contains absolute folders prepended to the image's path | | `verify.copy` | Folders of the upstream copied in only after the agent ends | | `verify.write` | `{absolute path inside: text}`, written in only after the agent ends | -| `verify.run` | In the working directory, same container | +| `verify.run` | In the working directory; same container unless `capture` requests a fresh one | +| `verify.capture` | A step with `run` and `collect`, run after the agent ends. Its collected folder is transferred to the same path in a fresh container of the same image and limits, without agent mounts or writes. A failed capture refuses verification | +| `verify.in_place` | Optional check step beside `capture`, run in the original container after capture; its evidence is kept under `verifier/in-place/` and sent as `verified.in_place`. The fresh check alone supplies the primary result | | `verify.collect` | A folder inside, copied into the trial's `verifier/` beside `verifier/test-stdout.txt` | | `verify.seconds` | The check's time limit | | `verify.network` | `true`: the check gets a proxy to public addresses | @@ -340,9 +343,9 @@ A benchmark whose tasks are containers (their own Dockerfile and `FROM`) says so | A runtime the image cannot start | Tried once before the agent; a failure (glibc in a musl image) is a setup error: "not run: the agent's runtime (node) needs glibc; this task's image is musl-based" | | A preparation leaves no way out | Its `network: true` is the check's proxy; the proxy container is removed and shown gone, and what the step left running is stopped, before the agent starts. `setup/prepare.txt` and `setup/egress.log` keep its output. A failure, or a way out that cannot be closed, is an `EnvironmentSetupError` | | Task internet ends before the check | When `internet: true`, `HTTP_PROXY`/`HTTPS_PROXY` name the proxy; internal relay and benchmark server aliases remain direct through `NO_PROXY`. `agent/egress.log` records allowed and refused traffic. The proxy is removed before verification, also after failed or cancelled work; failure to remove it prevents verification | -| The check runs where the work is | `score` is sent `verified: {exit, timed_out, output, dir, collected}`; the driver never runs docker. What changed in the container is `agent/container-changes.txt` | -| Nothing of the agent runs during the check | Every process but init and the keep-alive is stopped, then killed; `verifier/stopped.txt` names each, one that cannot be stopped is a `VerifierError`. `keep_processes: true` lets them run on, free to alter the tests | -| The check's way out is a proxy | `network: true` adds a proxy container as `egress`, told to the check's command alone (`HTTP_PROXY`, `HTTPS_PROXY`); it connects only to global addresses, never `169.254.0.0/16`, `100.64.0.0/10`, private ranges, loopback or the docker bridge. `verifier/egress.log` keeps what it let through and refused. A download has to honour the proxy variables | +| The check’s result | `score` is sent `verified: {exit, timed_out, output, dir, collected}`; the driver never runs docker. What changed in the container is `agent/container-changes.txt` | +| Nothing of the agent runs during the check | Every process but init, the keep-alive and preserved ENTRYPOINT services is stopped, then killed; `verifier/stopped.txt` names each, one that cannot be stopped is a `VerifierError`. `keep_processes: true` lets them run on, free to alter the tests | +| The check's way out is a proxy | `network: true` adds a proxy container as `egress`, told to the check's command alone (`HTTP_PROXY`, `HTTPS_PROXY`); it connects only to global addresses, never `169.254.0.0/16`, `100.64.0.0/10`, private ranges, loopback or the docker bridge. `verifier/egress.log` keeps what it let through and refused. JVM and Maven commands also receive proxy system properties, preserving existing `JAVA_TOOL_OPTIONS`. A download has to honour these proxy settings | | Controls | `nop` leaves the image as it is; `oracle` replies `{"answer": "", "solve": {copy, write, run, seconds}}`, run in the container. Neither needs the container backend, both need Docker or Podman | | Where it cannot run | An agent's unit needs the container backend (never `local_ok`); a Module benchmark has no own image |