Skip to content
Open
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 52 additions & 23 deletions resources_servers/r2e_gym/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@

from nemo_gym.client import SESSION_ID_KEY
from nemo_gym.config import get_global_config_dict
from nemo_gym.core import SESSION_LOST
from nemo_gym.core import SESSION_LOST, VERIFIER_ERROR
from nemo_gym.sandbox import (
AsyncSandbox,
SandboxResources,
Expand Down Expand Up @@ -75,8 +75,10 @@
run_verification,
verification_files,
)
from resources_servers.swebench.agent_network import AgentNetworkConfig
from resources_servers.swebench.anti_cheat import apply_anti_cheat_setup
from resources_servers.swebench.patch_capture import (
CaptureCommandError,
PatchCapture,
PatchCaptureMode,
capture_model_patch,
Expand All @@ -85,7 +87,7 @@
from resources_servers.swebench.sandbox_sessions import SandboxSessionResourcesServer


class R2EGymResourcesServerConfig(BaseResourcesServerConfig):
class R2EGymResourcesServerConfig(BaseResourcesServerConfig, AgentNetworkConfig):
is_verifying_golden_patch: bool = False
# "worktree" (diff of the working tree) or "committed" (committed work only); see swebench/patch_capture.py.
patch_capture_mode: PatchCaptureMode = "worktree"
Expand Down Expand Up @@ -156,6 +158,8 @@ class R2EGymResourcesServer(SandboxSessionResourcesServer):

def model_post_init(self, context: Any, /) -> None:
super().model_post_init(context)
if self.config.enforce_agent_no_network:
self.config.check_agent_network_provider(get_global_config_dict())
self._session_id_to_sandbox: dict[str, AsyncSandbox] = {}
self._session_id_to_pristine_untracked: dict[str, frozenset[str]] = {}

Expand Down Expand Up @@ -202,7 +206,7 @@ async def _create_sandbox(
"language": body.language[:63],
},
resources=sandbox_resources,
provider_options=self.config.sandbox_config.get("provider_options", {}),
provider_options=self.config.sandbox_provider_options(provider_config, for_agent=session_id is not None),
)
sandbox = AsyncSandbox(provider_config)
if session_id is not None:
Expand Down Expand Up @@ -338,32 +342,30 @@ async def _verify(self, request: Request, body: R2EGymVerifyRequest) -> R2EGymVe
capture = PatchCapture.static(body.patch, mode, "golden")
else:

async def capture_or_fallback() -> tuple[PatchCapture, str | None]:
async def capture_or_fallback() -> tuple[PatchCapture, str | None, bool]:
try:
return await self._extract_model_patch(session_id, REPO_DIRECTORY), None
return await self._extract_model_patch(session_id, REPO_DIRECTORY), None, False
except CaptureCommandError as exc:
# Git itself exiting non-zero can reflect a repository the agent damaged, so that keeps its
# empty-patch grading. Execution the provider could not complete is the infrastructure's.
incomplete = exc.error_type is not None or not isinstance(exc.return_code, int)
Comment thread
yfw marked this conversation as resolved.
Resolved
return PatchCapture.static("", mode, "none"), f"Failed to extract model patch: {exc}", incomplete
except Exception as exc:
return PatchCapture.static("", mode, "none"), f"Failed to extract model patch: {exc}"
return PatchCapture.static("", mode, "none"), f"Failed to extract model patch: {exc}", True

# The fallback is saved with the session too, so a retry after the task sandbox stopped grades it again.
capture, extraction_error = await self.capture_task_sandbox_patch(session_id, capture_or_fallback)
capture, extraction_error, capture_incomplete = await self.capture_task_sandbox_patch(
session_id, capture_or_fallback
)
await self.stop_task_sandbox_after_capture(session_id)
if capture_incomplete:
# An unavailable patch is not evidence that the agent submitted an empty one.
return self._incomplete_response(body, extraction_error, capture)

inputs = self._inputs(body, capture.patch)
if not inputs.expected:
# Without the expected statuses there is nothing to compare against; the row cannot be graded.
return self._response(
body,
reward=0.0,
evaluation_completed=False,
resolved=False,
patch_applied=False,
test_results=None,
test_output="",
error="row has no expected_output_json",
eval_sandbox_start_time_taken=0.0,
patch_verification_time_taken=0.0,
**capture.response_fields(self.config.include_model_patch_in_response),
)
return self._incomplete_response(body, "row has no expected_output_json", capture)

log_dir = Path(__file__).parent / "logs" / body.instance_id
files = verification_files(inputs)
Expand Down Expand Up @@ -399,22 +401,49 @@ async def capture_or_fallback() -> tuple[PatchCapture, str | None]:
flush=True,
)

error = extraction_error or result.error
return self._response(
body,
# An unresolved-but-completed run is a real 0. An incomplete run is also 0, but
# evaluation_completed distinguishes them so a broken row is not read as a hard task.
# An unresolved-but-completed run is a real 0. An incomplete run (no verdict) is masked, so a broken row
# or a verifier outage is not trained as a hard task.
reward=1.0 if result.resolved else 0.0,
evaluation_completed=result.completed,
**(
{"mask_sample": True, "failure_kind": VERIFIER_ERROR, "failure_reason": error or "No verdict"}
if not result.completed
else {}
),
resolved=result.resolved,
patch_applied=result.patch_applied,
test_results=result.test_results,
test_output=result.test_output[-100_000:],
error=extraction_error or result.error,
error=error,
eval_sandbox_start_time_taken=start_time_taken,
patch_verification_time_taken=verification_time_taken,
**capture.response_fields(self.config.include_model_patch_in_response),
)

def _incomplete_response(
self, body: R2EGymVerifyRequest, reason: str, capture: PatchCapture
) -> R2EGymVerifyResponse:
"""A verification that produced no verdict: masked, so it is neither trained nor read as a hard task."""
return self._response(
body,
reward=0.0,
evaluation_completed=False,
mask_sample=True,
failure_kind=VERIFIER_ERROR,
failure_reason=reason,
resolved=False,
patch_applied=False,
test_results=None,
test_output="",
error=reason,
eval_sandbox_start_time_taken=0.0,
patch_verification_time_taken=0.0,
**capture.response_fields(self.config.include_model_patch_in_response),
)


if __name__ == "__main__":
R2EGymResourcesServer.run_webserver()
Expand Down
4 changes: 4 additions & 0 deletions resources_servers/r2e_gym/configs/r2e_gym.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ r2e_gym_resources_server:
apply_anti_cheating: true

sandbox_provider: sandbox
enforce_agent_no_network: false
sandbox_model_server: null
sandbox_config:
ttl_s: 18000
ready_timeout_s: 1200
Expand Down Expand Up @@ -56,6 +58,8 @@ r2e_gym_golden_patch_resources_server:
num_workers: 8

sandbox_provider: sandbox
enforce_agent_no_network: false
sandbox_model_server: null
sandbox_config:
ttl_s: 18000
ready_timeout_s: 1200
Expand Down
157 changes: 157 additions & 0 deletions resources_servers/r2e_gym/tests/test_agent_network.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from unittest.mock import MagicMock

import pytest
from fastapi import HTTPException
from pydantic import ValidationError

import resources_servers.r2e_gym.app as app
import resources_servers.swebench.agent_network as agent_network
from nemo_gym.client import ServerClient
from nemo_gym.config import ModelServerRef


# The sandbox created for a session is the agent's; the evaluation sandbox is created for a verifier session.
AGENT_SANDBOX = {"session_id": "session"}
EVAL_SANDBOX = {"verifier_session_id": "session"}
INSTANCE = dict(instance_id="o__r-1", repo_name="o/r", image_name="img")
MODEL_SERVER = ModelServerRef(type="responses_api_models", name="policy_model")


class _Started(Exception):
"""Raised by the recording sandbox once it has the spec, so a seed stops before its setup commands."""


class _RecordingAsyncSandbox:
def __init__(self, provider_config) -> None:
self.spec = None

async def start(self, spec) -> None:
self.spec = spec
if _RecordingAsyncSandbox.raise_on_start:
raise _Started(spec)

async def exec(self, *args, **kwargs) -> None:
return None

async def stop(self) -> None:
return None


_RecordingAsyncSandbox.raise_on_start = False


@pytest.fixture
def make_server(monkeypatch):
def make(*, enforce=True, provider="opensandbox", model_url="http://10.1.2.3:8000", sandbox_config=None):
monkeypatch.setattr(app, "AsyncSandbox", _RecordingAsyncSandbox)
monkeypatch.setattr(app, "get_global_config_dict", lambda: {})
monkeypatch.setattr(app, "resolve_provider_config", lambda *_: {provider: {}})
monkeypatch.setattr(app, "resolve_provider_metadata", lambda *_: {})
monkeypatch.setattr(agent_network, "resolve_provider_config", lambda *_: {provider: {}})
monkeypatch.setattr(agent_network, "get_server_url", lambda name: model_url)
config = app.R2EGymResourcesServerConfig(
host="",
port=0,
name="r2e_gym",
entrypoint="",
sandbox_provider="sandbox",
sandbox_config=sandbox_config or {},
enforce_agent_no_network=enforce,
sandbox_model_server=MODEL_SERVER if enforce else None,
)
return app.R2EGymResourcesServer(config=config, server_client=MagicMock(spec=ServerClient))

return make


async def _create(server, sandbox_kwargs):
return await server._create_sandbox(app.R2EGymInstanceRequest(**INSTANCE), **sandbox_kwargs)


def test_disabled_network_check_does_not_load_global_cli_config(make_server, monkeypatch) -> None:
server = make_server(enforce=False)

def unexpected_global_config():
raise AssertionError("Disabled network enforcement must not parse process arguments")

monkeypatch.setattr(app, "get_global_config_dict", unexpected_global_config)
type(server)(config=server.config, server_client=server.server_client)


async def test_off_by_default(make_server) -> None:
sandbox = await _create(make_server(enforce=False), AGENT_SANDBOX)
assert "network_policy" not in sandbox.spec.provider_options


async def test_agent_sandbox_allows_only_the_model_host(make_server) -> None:
sandbox = await _create(make_server(), AGENT_SANDBOX)
assert sandbox.spec.provider_options["network_policy"] == {
"defaultAction": "deny",
"egress": [{"action": "allow", "target": "10.1.2.3"}],
}


async def test_seeding_blocks_the_agent_sandbox_egress(make_server, monkeypatch) -> None:
server = make_server()
monkeypatch.setattr(_RecordingAsyncSandbox, "raise_on_start", True)
with pytest.raises(_Started) as started:
await server._start_task_sandbox("session", app.R2EGymInstanceRequest(**INSTANCE))
assert started.value.args[0].provider_options["network_policy"]["defaultAction"] == "deny"


async def test_eval_sandbox_keeps_its_network(make_server) -> None:
sandbox = await _create(make_server(), EVAL_SANDBOX)
assert "network_policy" not in sandbox.spec.provider_options


async def test_other_provider_options_are_kept(make_server) -> None:
sandbox_config = {"provider_options": {"platform": "linux/amd64"}}
sandbox = await _create(make_server(sandbox_config=sandbox_config), AGENT_SANDBOX)
assert sandbox.spec.provider_options["platform"] == "linux/amd64"
assert sandbox.spec.provider_options["network_policy"]["defaultAction"] == "deny"
assert "network_policy" not in sandbox_config["provider_options"], "the shared config must not be mutated"


async def test_unreachable_model_host_refuses_the_seed(make_server) -> None:
server = make_server(model_url="http://127.0.0.1:8000")
with pytest.raises(HTTPException) as refused:
await _create(server, AGENT_SANDBOX)
assert refused.value.status_code == 422


def test_startup_refuses_a_provider_without_network_policies(make_server) -> None:
with pytest.raises(ValueError, match="OpenSandbox"):
make_server(provider="docker")


def test_config_refuses_the_flag_without_a_model_server_or_with_a_set_policy() -> None:
base = dict(host="", port=0, name="r2e_gym", entrypoint="", sandbox_provider="sandbox")
with pytest.raises(ValidationError, match="needs sandbox_model_server"):
app.R2EGymResourcesServerConfig(**base, sandbox_config={}, enforce_agent_no_network=True)
with pytest.raises(ValidationError, match="not both"):
app.R2EGymResourcesServerConfig(
**base,
sandbox_config={"provider_options": {"network_policy": {"defaultAction": "deny"}}},
enforce_agent_no_network=True,
sandbox_model_server=MODEL_SERVER,
)


def test_config_fields_default_to_open_egress() -> None:
fields = app.R2EGymResourcesServerConfig.model_fields
assert fields["enforce_agent_no_network"].default is False
assert fields["sandbox_model_server"].default is None
19 changes: 17 additions & 2 deletions resources_servers/r2e_gym/tests/test_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -352,8 +352,8 @@ def test_the_server_applies_the_drop_to_every_candidate_patch(self) -> None:


class _FakeSandbox:
def __init__(self, stdout: str, return_code: int = 0, stderr: str = "") -> None:
self.result = SimpleNamespace(stdout=stdout, stderr=stderr, return_code=return_code)
def __init__(self, stdout: str, return_code: int = 0, stderr: str = "", error_type: str | None = None) -> None:
self.result = SimpleNamespace(stdout=stdout, stderr=stderr, return_code=return_code, error_type=error_type)

async def exec(self, command: str, timeout_s=None, cwd=None):
return self.result
Expand Down Expand Up @@ -382,6 +382,21 @@ async def test_a_wrong_image_is_incomplete_not_a_zero(self, code) -> None:
result = await run_verification(_FakeSandbox("", return_code=code), _inputs())
assert result.completed is False and result.test_results is None

@pytest.mark.asyncio
async def test_a_provider_failure_of_the_test_run_is_incomplete_not_a_zero(self) -> None:
"""No exit status from the provider: the partial log cannot grade the run, so it has no verdict."""
log = f"{TEST_OUTPUT_BEGIN}\nshort test summary info\nPASSED r2e_tests/test_1.py::TestContextHandler::test_fast_save\n"
result = await run_verification(_FakeSandbox(log, return_code=125, error_type="sandbox"), _inputs())
assert result.completed is False and result.resolved is False and result.test_results is None
assert result.error.startswith("test run did not finish (sandbox)")

@pytest.mark.asyncio
async def test_a_timed_out_test_run_is_still_a_graded_zero(self) -> None:
"""A test the patch made hang is the patch's fault, so a timeout keeps grading what the run printed."""
result = await run_verification(_FakeSandbox("", return_code=124, error_type="timeout"), _inputs())
assert result.completed is True and result.resolved is False
assert result.test_results["missing"]

@pytest.mark.asyncio
async def test_only_the_marked_region_reaches_the_parser(self) -> None:
log = (
Expand Down
13 changes: 13 additions & 0 deletions resources_servers/r2e_gym/verification.py
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,19 @@ def _persist_log() -> None:

await asyncio.to_thread(_persist_log)

error_type = getattr(result, "error_type", None)
if error_type not in (None, "timeout"):
# The provider ended the eval script without an exit status (a dropped stream, a provider error), so the
# partial log cannot grade the run: it is no verdict. A timeout stays a verdict, as before: a test the patch
# made hang still scores 0.
return VerificationResult(
False,
False,
False,
None,
output,
f"test run did not finish ({error_type}): {(result.stderr or '')[-500:]}",
)
if result.return_code == EXIT_NO_REPO:
return VerificationResult(False, False, False, None, output, f"{REPO_DIRECTORY} is not present in the image")
if result.return_code == EXIT_NO_TESTS:
Expand Down
6 changes: 4 additions & 2 deletions resources_servers/scale_swe/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -137,5 +137,7 @@ names the session for `/verify`, and `/close_session` ends it.
progress gets that long to finish, and then its sandboxes are stopped anyway. A stop that fails is logged,
and the provider's TTL reclaims the sandbox.

The cookie path that an Agent's `/run` uses is unchanged: it does not replay or mask, the stops inside its
requests are not bounded, and the sandboxes it still holds at shutdown are left to the provider's TTL.
The cookie path that an Agent's `/run` uses grades and masks the same way: a verification without a verdict
(including a capture lost to infrastructure) is masked with a `failure_kind`, and a repository the agent broke
scores a completed 0. It does not replay. Its task sandbox stop gets the same bounded wait, but its verifier
sandbox stops do not. The sandboxes it still holds at shutdown are left to the provider's TTL.
Loading
Loading