From 59cd386c490a248cf8301f0eba30c4d118513f3a Mon Sep 17 00:00:00 2001 From: zhaopenghao Date: Fri, 4 Dec 2026 03:37:03 +0000 Subject: [PATCH] feat(rl): run complete sandbox Trials with owned resources Add declarative named resources, command and cleanup receipts, OpenSandbox and EnvGateway clients, and an adaptive quota gate. Run Trials under an owned local or CPU Ray task with one deadline and no replay. --- .dev_scripts/smoke_sandbox_cleanup.py | 174 ++ tests/rl/fixtures/opensandbox/exit7.events | 5 + .../opensandbox/oom_native_status.json | 41 + .../service_oom_while_main_running.json | 24 + tests/rl/named_sandbox_http_fixture.py | 92 + tests/rl/sandbox_http_fixture.py | 78 + tests/rl/test_attempt_contract.py | 34 + tests/rl/test_attempt_ray.py | 204 ++ tests/rl/test_process_monitor_recovery.py | 193 ++ tests/rl/test_sandbox_cleanup_protocol.py | 534 +++++ tests/rl/test_sandbox_runtime_v3.py | 1841 +++++++++++++++++ tests/rl/test_service_endpoint.py | 56 + tests/rl/test_trial_context.py | 100 + xtuner/v1/rl/agent_loop/__init__.py | 34 +- .../rl/agent_loop/trial_agent_loop/README.md | 126 ++ .../agent_loop/trial_agent_loop/__init__.py | 1 + .../agent_loop/trial_agent_loop/admission.py | 201 ++ .../trial_agent_loop/error_handling.py | 175 ++ .../trial_agent_loop/observation.py | 118 ++ .../trial_agent_loop/sandbox/__init__.py | 1 + .../trial_agent_loop/sandbox/client.py | 833 ++++++++ .../trial_agent_loop/sandbox/jobs.py | 359 ++++ .../sandbox/process_monitor.py | 132 ++ .../trial_agent_loop/sandbox/runtime.py | 1484 +++++++++++++ .../trial_agent_loop/sandbox/types.py | 197 ++ .../trial_agent_loop/trial/__init__.py | 6 + .../agent_loop/trial_agent_loop/trial/base.py | 175 ++ .../trial_agent_loop/trial/execution.py | 238 +++ .../trial_agent_loop/trial/sandbox_trial.py | 374 ++++ xtuner/v1/rl/utils/async_utils.py | 39 + 30 files changed, 7856 insertions(+), 13 deletions(-) create mode 100644 .dev_scripts/smoke_sandbox_cleanup.py create mode 100644 tests/rl/fixtures/opensandbox/exit7.events create mode 100644 tests/rl/fixtures/opensandbox/oom_native_status.json create mode 100644 tests/rl/fixtures/opensandbox/service_oom_while_main_running.json create mode 100644 tests/rl/named_sandbox_http_fixture.py create mode 100644 tests/rl/sandbox_http_fixture.py create mode 100644 tests/rl/test_attempt_contract.py create mode 100644 tests/rl/test_attempt_ray.py create mode 100644 tests/rl/test_process_monitor_recovery.py create mode 100644 tests/rl/test_sandbox_cleanup_protocol.py create mode 100644 tests/rl/test_sandbox_runtime_v3.py create mode 100644 tests/rl/test_service_endpoint.py create mode 100644 tests/rl/test_trial_context.py create mode 100644 xtuner/v1/rl/agent_loop/trial_agent_loop/README.md create mode 100644 xtuner/v1/rl/agent_loop/trial_agent_loop/__init__.py create mode 100644 xtuner/v1/rl/agent_loop/trial_agent_loop/admission.py create mode 100644 xtuner/v1/rl/agent_loop/trial_agent_loop/error_handling.py create mode 100644 xtuner/v1/rl/agent_loop/trial_agent_loop/observation.py create mode 100644 xtuner/v1/rl/agent_loop/trial_agent_loop/sandbox/__init__.py create mode 100644 xtuner/v1/rl/agent_loop/trial_agent_loop/sandbox/client.py create mode 100644 xtuner/v1/rl/agent_loop/trial_agent_loop/sandbox/jobs.py create mode 100644 xtuner/v1/rl/agent_loop/trial_agent_loop/sandbox/process_monitor.py create mode 100644 xtuner/v1/rl/agent_loop/trial_agent_loop/sandbox/runtime.py create mode 100644 xtuner/v1/rl/agent_loop/trial_agent_loop/sandbox/types.py create mode 100644 xtuner/v1/rl/agent_loop/trial_agent_loop/trial/__init__.py create mode 100644 xtuner/v1/rl/agent_loop/trial_agent_loop/trial/base.py create mode 100644 xtuner/v1/rl/agent_loop/trial_agent_loop/trial/execution.py create mode 100644 xtuner/v1/rl/agent_loop/trial_agent_loop/trial/sandbox_trial.py diff --git a/.dev_scripts/smoke_sandbox_cleanup.py b/.dev_scripts/smoke_sandbox_cleanup.py new file mode 100644 index 0000000000..97c992de3a --- /dev/null +++ b/.dev_scripts/smoke_sandbox_cleanup.py @@ -0,0 +1,174 @@ +"""Opt-in real DBox lifecycle smoke; only delete IDs created by this invocation.""" + +import argparse +import asyncio +import json +import socket +from datetime import datetime, timezone +from pathlib import Path +from uuid import uuid4 + +import httpx +from aiohttp import web +from mini_agent import Failure, HarnessSpec, ModelSettings, SequenceLimits + +from xtuner.v1.rl.agent_loop.trial_agent_loop.sandbox.runtime import SandboxRuntime +from xtuner.v1.rl.agent_loop.trial_agent_loop.sandbox.types import SandboxConfig, cmd +from xtuner.v1.rl.agent_loop.trial_agent_loop.trial.base import Budgets, ResourceSpec, TaskInput, TrialContext + + +async def smoke(args: argparse.Namespace) -> None: + args.output_dir.mkdir(parents=True, exist_ok=True) + run_id = "worker4-cleanup-" + uuid4().hex + events, created, absent = [], {}, {} + phase = "normal" + b_created, a_deleted, release_b = (asyncio.Event() for _ in range(3)) + key = args.credential_file.read_text().strip() + + def record(event: str, **fields: object) -> None: + row = {"at": datetime.now(timezone.utc).isoformat(), "event": event, "phase": phase, **fields} + events.append(row) + with (args.output_dir / "http-events.jsonl").open("a") as stream: + stream.write(json.dumps(row) + "\n") + + async with httpx.AsyncClient( + headers={"OPEN-SANDBOX-API-KEY": key}, + trust_env=False, + timeout=120, + ) as backend: + + async def proxy(request: web.Request) -> web.Response: + body = await request.read() + response = await backend.request( + request.method, + args.endpoint.rstrip("/") + str(request.rel_url), + content=body, + headers={ + name: value + for name, value in request.headers.items() + if name.lower() not in {"host", "content-length", "connection"} + }, + ) + record("platform_response", method=request.method, path=request.path, status=response.status_code) + if request.method == "POST" and request.path == "/v1/sandboxes" and response.is_success: + sid = response.json()["id"] + created.setdefault(phase, []).append(sid) + (args.output_dir / "created-ids.json").write_text(json.dumps(created, indent=2) + "\n") + record("created", sandbox_id=sid) + if phase == "concurrent" and len(created[phase]) == 2: + b_created.set() + await release_b.wait() # Hold only B's reply, after its real POST has completed. + record("late_create_reply", sandbox_id=sid) + if phase == "concurrent" and request.method == "DELETE" and created.get(phase): + if request.path == "/v1/sandboxes/" + created[phase][0]: + record("ready_a_delete_before_b_reply", sandbox_id=created[phase][0]) + a_deleted.set() + release_b.set() + return web.Response( + body=response.content, + status=response.status_code, + headers={"Content-Type": response.headers.get("content-type", "application/json")}, + ) + + app = web.Application() + app.router.add_route("*", "/{path:.*}", proxy) + runner = web.AppRunner(app) + await runner.setup() + with socket.socket() as sock: + sock.bind(("127.0.0.1", 0)) + sock.listen() + await web.SockSite(runner, sock).start() + endpoint = "http://127.0.0.1:" + str(sock.getsockname()[1]) + + def runtime(name: str) -> SandboxRuntime: + sid = run_id + "-" + name + return SandboxRuntime( + ctx=TrialContext( + TaskInput(("smoke", name), "cleanup lifecycle", {}), + sid, + args.output_dir / name, + Budgets(attempt=300, create_rpc=120, request=30, verifier=30, cleanup=90, sandbox_ttl=600), + ModelSettings("http://unused", sid, "cpu-lifecycle", {}, SequenceLimits(100, 100, 10)), + None, + ), + sandbox_cfg=SandboxConfig( + endpoint=endpoint, + project=args.project, + credential_file=str(args.credential_file), + command_mode="native", + ), + default_resources=ResourceSpec(cpus=1, memory_mb=2048), + harness=HarnessSpec("mini_swe"), + max_turns=1, + tool_user=None, + tool_env={}, + ) + + owner = None + try: + async with runtime("normal") as sb: + resource = await sb.acquire("main", image=args.image) + assert not isinstance(resource, Failure), resource + result = await sb.verify( + resource, command=cmd("bash", "-lc", "printf worker4-native-smoke"), outputs=[] + ) + assert not isinstance(result, Failure) and result.return_code == 0, result + record("native_command_completed", sandbox_id=resource.id, return_code=result.return_code) + + phase = "concurrent" + + async def attempt() -> None: + async with runtime("concurrent") as sb: + ready = await sb.acquire("A", image=args.image) + assert not isinstance(ready, Failure), ready + record("a_ready", sandbox_id=ready.id) + await sb.acquire("B", image=args.image) + + owner = asyncio.create_task(attempt()) + await asyncio.wait_for(b_created.wait(), 300) + owner.cancel("body cancellation") + await asyncio.wait_for(a_deleted.wait(), 90) + owner.cancel("cleanup wait cancellation") + try: + await owner + except asyncio.CancelledError: + record("requested_cancellation_propagated") + else: + raise AssertionError("concurrent cancellation did not propagate") + finally: + release_b.set() + if owner is not None: + if not owner.done(): + owner.cancel() + await asyncio.gather(owner, return_exceptions=True) + # The independent control-plane GET is the acceptance evidence. + # Emergency cleanup, when needed, can touch only our recorded IDs. + for sandbox_id in [sid for ids in created.values() for sid in ids]: + url = args.endpoint.rstrip("/") + "/v1/sandboxes/" + sandbox_id + response = await backend.get(url) + record("independent_absence_check", sandbox_id=sandbox_id, status=response.status_code) + absent[sandbox_id] = response.status_code + if response.status_code != 404: + await backend.delete(url) + async with asyncio.timeout(120): + while (await backend.get(url)).status_code != 404: + await asyncio.sleep(0.5) + record("emergency_delete_confirmed", sandbox_id=sandbox_id, status=404) + (args.output_dir / "absence-checks.json").write_text(json.dumps(absent, indent=2) + "\n") + await runner.cleanup() + assert len(created.get("normal", [])) == 1 and len(created.get("concurrent", [])) == 2, created + assert all(status == 404 for status in absent.values()), absent + assert next(i for i, row in enumerate(events) if row["event"] == "ready_a_delete_before_b_reply") < next( + i for i, row in enumerate(events) if row["event"] == "late_create_reply" + ) + print(json.dumps({"status": "passed", "run_id": run_id, "created": created, "GET_statuses": absent})) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--endpoint", required=True) + parser.add_argument("--project", required=True) + parser.add_argument("--credential-file", required=True, type=Path) + parser.add_argument("--image", required=True) + parser.add_argument("--output-dir", required=True, type=Path) + asyncio.run(smoke(parser.parse_args())) diff --git a/tests/rl/fixtures/opensandbox/exit7.events b/tests/rl/fixtures/opensandbox/exit7.events new file mode 100644 index 0000000000..5d85dcc69f --- /dev/null +++ b/tests/rl/fixtures/opensandbox/exit7.events @@ -0,0 +1,5 @@ +{"type":"init","text":"460e3d20924c44d7bb7444d5e6600c42","timestamp":1795803178565} + +{"type":"ping","text":"pong","timestamp":1795803178565} + +{"type":"error","timestamp":1795803178567,"error":{"ename":"CommandExecError","evalue":"7","traceback":["exit status 7"]}} diff --git a/tests/rl/fixtures/opensandbox/oom_native_status.json b/tests/rl/fixtures/opensandbox/oom_native_status.json new file mode 100644 index 0000000000..8f1f92fa14 --- /dev/null +++ b/tests/rl/fixtures/opensandbox/oom_native_status.json @@ -0,0 +1,41 @@ +{ + "at": "2026-11-28T04:03:29.475972+00:00", + "run_id": "v3_obs_swe_10step_20261128_0347", + "session_id": "235705224469154673298270696689259849771", + "task_key": [ + "swe", + "django__django-11740" + ], + "sandbox_id": "cprod2-0zn9nbzfg5yx23i8h8ng", + "native_command_id": "77cd1631ce2f444f8bcf35f740a71b64", + "calls": [ + { + "kind": "sandbox", + "status": 200, + "body": { + "id": "cprod2-0zn9nbzfg5yx23i8h8ng", + "status": { + "state": "Failed", + "reason": "pod sandbox-project-ailab-llmit/cprod2-0zn9nbzfg5yx23i8h8ng runtime failed: phase=Running: container sandbox terminated reason=OOMKilled exitCode=137", + "message": "pod sandbox-project-ailab-llmit/cprod2-0zn9nbzfg5yx23i8h8ng runtime failed: phase=Running: container sandbox terminated reason=OOMKilled exitCode=137" + }, + "state": "failed", + "createdAt": "2026-11-28T03:55:16.891196826Z", + "expiresAt": "2026-11-28T16:25:22.756134688Z" + } + }, + { + "kind": "ping", + "status": 409, + "body": "sandbox route not active", + "request_id": null + }, + { + "kind": "command_status", + "status": 409, + "body": "sandbox route not active", + "request_id": null + } + ], + "mutation_count": 0 +} \ No newline at end of file diff --git a/tests/rl/fixtures/opensandbox/service_oom_while_main_running.json b/tests/rl/fixtures/opensandbox/service_oom_while_main_running.json new file mode 100644 index 0000000000..df7f261bac --- /dev/null +++ b/tests/rl/fixtures/opensandbox/service_oom_while_main_running.json @@ -0,0 +1,24 @@ +[ + { + "session_id": "120792514149776376778144722155987294166", + "resource_name": "task-server", + "sandbox_id": "cprod3-2de88bhp3qw6dnx8fd5f", + "http_status": 200, + "state": "failed", + "status": { + "state": "Failed", + "reason": "pod sandbox-project-ailab-llmit/cprod3-2de88bhp3qw6dnx8fd5f runtime failed: phase=Running: container sandbox terminated reason=OOMKilled exitCode=137", + "message": "pod sandbox-project-ailab-llmit/cprod3-2de88bhp3qw6dnx8fd5f runtime failed: phase=Running: container sandbox terminated reason=OOMKilled exitCode=137" + } + }, + { + "session_id": "120792514149776376778144722155987294166", + "resource_name": "main", + "sandbox_id": "cprod3-aj6j52oci4zuknlysj98", + "http_status": 200, + "state": "running", + "status": { + "state": "Running" + } + } +] diff --git a/tests/rl/named_sandbox_http_fixture.py b/tests/rl/named_sandbox_http_fixture.py new file mode 100644 index 0000000000..ea1ba12f15 --- /dev/null +++ b/tests/rl/named_sandbox_http_fixture.py @@ -0,0 +1,92 @@ +"""Native platform responses for exercising the public named Trial through HTTP.""" + +import asyncio +import json + +from aiohttp import web +from mini_agent import AgentReport, encode_worker_result + + +class NamedSandboxPlatform: + def __init__(self, *, proof=b"proof\r\n", fault=None): + self.proof, self.fault = proof, fault + self.creates, self.commands, self.files, self.deletes, self.calls = [], {}, {}, [], [] + self.deleted, self.settled, self.workspaces = set(), False, {} + self.delete_started, self.finish_delete = asyncio.Event(), asyncio.Event() + + @staticmethod + def events(*rows): + return web.Response(text="".join(json.dumps(row) + "\n" for row in rows)) + + async def __call__(self, req): + self.calls.append((req.method, req.path)) + if req.path == "/v1/sandboxes" and req.method == "POST": + payload = await req.json() + sid = f"box{len(self.creates)}" + self.creates.append(payload) + self.files[sid] = {} + return web.json_response({"id": sid}, status=202) + sid = req.path.split("/")[3] + if req.path == f"/v1/sandboxes/{sid}": + if req.method == "DELETE": + self.deletes.append(sid) + self.delete_started.set() + if self.fault == "cancel-delete": + await self.finish_delete.wait() + if self.fault != f"release-{sid}" or self.deletes.count(sid) > 1: + self.deleted.add(sid) + return web.Response(status=204) + return web.Response(status=404) if sid in self.deleted else web.json_response({"state": "running"}) + assert sid not in self.deleted + if req.path.endswith("/ping"): + return web.json_response({"ok": True}) + if "/endpoints/" in req.path: + return web.json_response({"endpoint": "http://lookup.test:8080"}) + assert req.headers["X-EXECD-ACCESS-TOKEN"] + if req.path.endswith("/files/upload"): + parts = await req.multipart() + metadata, content = {}, b"" + async for part in parts: + if part.name == "metadata": + metadata = json.loads(await part.read()) + elif part.name == "file": + content = await part.read() + path = metadata["path"] + self.files[sid][path] = content + if path.endswith("/request.json"): + self.workspaces[sid] = json.loads(content)["workspace"] + if path.endswith("/private-grader"): + assert self.settled, "private grader uploaded before model settlement" + return web.Response(status=204) + if req.path.endswith("/files/download"): + target = req.query["path"] + if target == self.workspaces.get(sid, "") + "/work/a": + return web.Response(status=404) if self.fault == "missing" else web.Response(body=self.proof) + if target.endswith("/worker-fatal.txt"): + return web.Response(status=404) + if target.endswith("/results/grade.json"): + return web.json_response({"score": 1}) + if target.endswith("/result.json"): + return web.Response( + body=encode_worker_result(AgentReport("MaxTurns", None, ["observed-a", "observed-b"])) + ) + return ( + web.Response(body=self.files[sid][target]) if target in self.files[sid] else web.Response(status=404) + ) + if req.path.endswith("/command"): + body = await req.json() + command = body["command"] + if not body.get("background"): + stdout = "LANG=C.UTF-8\0" if "env -0" in command else "" + return self.events({"type": "stdout", "text": stdout}, {"type": "execution_complete"}) + cid = str(len(self.commands)) + self.commands[cid] = (sid, command) + return self.events({"type": "init", "text": cid}) + if "/command/status/" in req.path: + _, command = self.commands[req.path.rsplit("/", 1)[-1]] + return web.json_response({"running": "serve-fixture" in command, "exit_code": 0}) + if req.path.endswith("/command/interrupt"): + return web.Response(status=204) + if req.path.endswith("/logs"): + return web.Response(text="") + raise AssertionError((req.method, req.path)) diff --git a/tests/rl/sandbox_http_fixture.py b/tests/rl/sandbox_http_fixture.py new file mode 100644 index 0000000000..b90ad607e0 --- /dev/null +++ b/tests/rl/sandbox_http_fixture.py @@ -0,0 +1,78 @@ +"""External sandbox HTTP fixture backed by real local shell/file operations.""" + +import asyncio +import json +import re +from pathlib import Path + +from aiohttp import web + + +class SandboxPlatform: + def __init__(self, root, on_upload=None): + self.root = Path(root) + self.root.mkdir() + self.deleted = False + self.calls = [] + self.on_upload = on_upload + + def path(self, value): + return re.sub(r"/private(?=/|\s|$)", lambda _: str(self.root / "private"), value) + + async def __call__(self, request): + self.calls.append((request.method, request.path)) + if request.path.endswith("/files/upload"): + parts = await request.multipart() + metadata, content = {}, b"" + async for part in parts: + if part.name == "metadata": + metadata = json.loads(await part.read()) + elif part.name == "file": + content = await part.read() + if self.on_upload is not None: + await self.on_upload(metadata["path"]) + path = Path(self.path(metadata["path"])) + if path.suffix == ".sh": + content = self.path(content.decode()).encode() + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(content) + return web.json_response({"ok": True}) + if request.path.endswith("/files/download"): + path = Path(self.path(request.query["path"])) + return web.Response(body=path.read_bytes()) if path.exists() else web.Response(status=404) + if request.path.endswith("/command"): + body = await request.json() + process = await asyncio.create_subprocess_exec( + "bash", + "-c", + self.path(body["command"]), + cwd=self.path(body["cwd"]), + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + ) + stdout, stderr = await process.communicate() + events = [ + {"type": "stdout", "timestamp": 0, "text": stdout.decode()}, + {"type": "stderr", "timestamp": 0, "text": stderr.decode()}, + ] + if process.returncode: + events.append( + { + "type": "error", + "timestamp": 0, + "error": {"ename": "CommandExecError", "evalue": str(process.returncode)}, + } + ) + events.append({"type": "execution_complete", "timestamp": 0}) + return web.Response( + text="".join("data: " + json.dumps(item) + "\n\n" for item in events), content_type="text/event-stream" + ) + if request.method == "POST": + self.deleted = False + return web.json_response({"id": "owned-main"}) + if request.method == "DELETE": + self.deleted = True + return web.Response(status=204) + if request.path.endswith("/ping"): + return web.json_response({"ok": True}) + return web.Response(status=404) if self.deleted else web.json_response({"state": "running"}) diff --git a/tests/rl/test_attempt_contract.py b/tests/rl/test_attempt_contract.py new file mode 100644 index 0000000000..e48037e295 --- /dev/null +++ b/tests/rl/test_attempt_contract.py @@ -0,0 +1,34 @@ +"""Public declarative contracts need no legacy Agent runtime.""" + +import json + +from xtuner.v1.rl.agent_loop.trial_agent_loop.trial.base import ResourceSpec, TaskInput, resolve_resources + + +def test_native_loop_import_does_not_load_legacy_runtime(): + import subprocess + import sys + + subprocess.run( + [ + sys.executable, + "-c", + "import sys; import xtuner.v1.rl.agent_loop.trial_agent_loop.trial_agent_loop; " + "assert not any(name.startswith(('lagent', 'xtuner.v1.rl.agent_loop.sandbox_agent_loop')) " + "for name in sys.modules)", + ], + check=True, + ) + + +def test_task_json_preserves_identity_and_merges_per_field_resources(): + task = TaskInput(("swe", "case-1"), "fix", {"main": {"image": "test"}}, ResourceSpec(memory_mb=8192)) + restored = TaskInput.from_dict(json.loads(json.dumps(task.to_dict()))) + assert restored == task + assert resolve_resources( + restored.resources, ResourceSpec(cpus=2, memory_mb=2048, storage_mb=1000) + ) == ResourceSpec( + cpus=2, + memory_mb=8192, + storage_mb=1000, + ) diff --git a/tests/rl/test_attempt_ray.py b/tests/rl/test_attempt_ray.py new file mode 100644 index 0000000000..bf2012f21b --- /dev/null +++ b/tests/rl/test_attempt_ray.py @@ -0,0 +1,204 @@ +"""Real CPU Ray execution, placement, cancellation and no replay.""" + +import asyncio +import json +import os +import sys +from builtins import BaseExceptionGroup +from uuid import uuid4 + +import pytest +import ray +from mini_agent import ModelSettings, SequenceLimits +from ray.util import get_current_placement_group + +from xtuner.v1.rl.agent_loop.trial_agent_loop.trial.base import ( + Budgets, + TaskInput, + Trial, + TrialConfig, + TrialContext, + TrialResult, +) +from xtuner.v1.rl.agent_loop.trial_agent_loop.trial.execution import start_trial + + +class RecordingRunner(Trial): + def __init__(self, cfg, ctx): + super().__init__(cfg, ctx) + self.mode = cfg.mode + + async def run(self): + task, ctx = self.ctx.task, self.ctx + ctx.output_dir.mkdir(parents=True, exist_ok=True) + with (ctx.output_dir / "starts").open("a") as stream: + stream.write("started\n") + (ctx.output_dir / "started.json").write_text( + json.dumps( + { + "pid": os.getpid(), + "gpus": ray.get_runtime_context().get_accelerator_ids().get("GPU", []), + "placement_group": get_current_placement_group() is not None, + } + ) + ) + if self.mode == "crash": + os._exit(17) + try: + if self.mode == "wait": + await asyncio.Event().wait() + return TrialResult(0.5, observed_request_ids=["server-turn"]) + finally: + await asyncio.sleep(0.2) + (ctx.output_dir / "cleaned").write_text(task.instruction) + + +class RecordingConfig(TrialConfig): + mode: str = "complete" + + def build(self, ctx): + return RecordingRunner(self, ctx) + + +@pytest.fixture(scope="module") +def cpu_ray(): + # Ship the test Runner by value; production code is imported normally in + # the independent worker, including declarative Pydantic configs. + ray.cloudpickle.register_pickle_by_value(sys.modules[__name__]) + ray.init( + address="local", + num_cpus=2, + num_gpus=0, + include_dashboard=False, + _temp_dir="/tmp/ray-mini-agent-" + uuid4().hex[:8], + log_to_driver=False, + ) + yield + ray.shutdown() + ray.cloudpickle.unregister_pickle_by_value(sys.modules[__name__]) + + +def context(path, task): + return TrialContext( + task, + "attempt-1", + path, + Budgets(attempt=10), + ModelSettings("http://model", "attempt-1", "test", {}, SequenceLimits(100, 100, 10)), + None, + ) + + +def test_full_attempt_runs_on_independent_cpu_worker(cpu_ray, tmp_path): + async def scenario(): + outcome = await start_trial( + RecordingConfig(), + context(tmp_path, task=TaskInput(("test", "1"), "real worker", {})), + dispatch_mode="ray_task", + trial_cpus=0.5, + ) + assert outcome == TrialResult(0.5, observed_request_ids=["server-turn"]) + info = json.loads((tmp_path / "started.json").read_text()) + assert info["pid"] != os.getpid() + assert info["gpus"] == [] + assert info["placement_group"] is False + assert (tmp_path / "cleaned").read_text() == "real worker" + assert (tmp_path / "starts").read_text().splitlines() == ["started"] + + asyncio.run(scenario()) + + +def test_repeated_cancel_waits_for_original_cpu_trials_finally(cpu_ray, tmp_path): + async def scenario(): + owner = start_trial( + RecordingConfig(mode="wait"), context(tmp_path, task=TaskInput(("test", "1"), "cleanup", {})) + ) + async with asyncio.timeout(15): + while not (tmp_path / "started.json").exists(): + await asyncio.sleep(0.02) + owner.cancel() + await asyncio.sleep(0.05) + owner.cancel() + with pytest.raises(BaseExceptionGroup) as caught: + await asyncio.wait_for(owner, 10) + assert len(caught.value.exceptions) == 2 + assert all(isinstance(error, asyncio.CancelledError) for error in caught.value.exceptions) + assert (tmp_path / "cleaned").read_text() == "cleanup" + assert (tmp_path / "starts").read_text().splitlines() == ["started"] + + asyncio.run(scenario()) + + +def test_cancel_before_owner_starts_does_not_launch_an_orphan_trial(cpu_ray, tmp_path): + async def scenario(): + await start_trial(RecordingConfig(), context(tmp_path / "warm", task=TaskInput(("test", "warm"), "warm", {}))) + owner = start_trial(RecordingConfig(), context(tmp_path, task=TaskInput(("test", "1"), "never start", {}))) + owner.cancel() + with pytest.raises(asyncio.CancelledError): + await owner + await asyncio.sleep(0.5) + assert not (tmp_path / "starts").exists() + + asyncio.run(scenario()) + + +def test_queue_timeout_cancels_pending_trial_without_starting_it(cpu_ray, tmp_path): + async def scenario(): + from ray.util.placement_group import placement_group, remove_placement_group + + reserved = placement_group([{"CPU": 2}], strategy="PACK") + await asyncio.wait_for(reserved.ready(), 10) + try: + with pytest.raises(TimeoutError): + async with asyncio.timeout(0.2): + await start_trial( + RecordingConfig(), context(tmp_path, task=TaskInput(("test", "1"), "queued", {})) + ) + finally: + remove_placement_group(reserved) + await asyncio.sleep(0.4) + assert not (tmp_path / "starts").exists() + + asyncio.run(scenario()) + + +def test_worker_crash_is_reported_without_automatic_task_replay(cpu_ray, tmp_path): + async def scenario(): + with pytest.raises(ray.exceptions.WorkerCrashedError): + await start_trial( + RecordingConfig(mode="crash"), context(tmp_path, task=TaskInput(("test", "1"), "crash", {})) + ) + assert (tmp_path / "starts").read_text().splitlines() == ["started"] + + asyncio.run(scenario()) + + +@ray.remote(num_cpus=1, max_restarts=0) +class PlacementDriver: + async def run(self, cfg, ctx): + (ctx.output_dir / "parent-started").write_text("parent has entered its PG") + return await start_trial(cfg, ctx, trial_cpus=1) + + +def test_trial_escapes_a_fully_occupied_parent_placement_group(cpu_ray, tmp_path): + from ray.util.placement_group import placement_group, remove_placement_group + from ray.util.scheduling_strategies import PlacementGroupSchedulingStrategy + + group = placement_group([{"CPU": 1}], strategy="PACK") + ray.get(group.ready(), timeout=10) + actor = PlacementDriver.options( + scheduling_strategy=PlacementGroupSchedulingStrategy( + placement_group=group, + placement_group_capture_child_tasks=True, + ) + ).remote() + try: + outcome = ray.get( + actor.run.remote(RecordingConfig(), context(tmp_path, TaskInput(("test", "1"), "outside group", {}))), + timeout=45, + ) + assert outcome.score == 0.5 + assert json.loads((tmp_path / "started.json").read_text())["placement_group"] is False + finally: + ray.kill(actor, no_restart=True) + remove_placement_group(group) diff --git a/tests/rl/test_process_monitor_recovery.py b/tests/rl/test_process_monitor_recovery.py new file mode 100644 index 0000000000..ab5416d036 --- /dev/null +++ b/tests/rl/test_process_monitor_recovery.py @@ -0,0 +1,193 @@ +"""Bounded PID and exit-code recovery for native detached Trial jobs.""" + +import asyncio +import time +import unittest +from types import SimpleNamespace + +import httpx +import pytest +from mini_agent import Failure + +from xtuner.v1.rl.agent_loop.trial_agent_loop.sandbox import process_monitor as monitor +from xtuner.v1.rl.agent_loop.trial_agent_loop.sandbox.jobs import DetachedJob +from xtuner.v1.rl.agent_loop.trial_agent_loop.sandbox.types import ResourceHandle +from xtuner.v1.rl.agent_loop.trial_agent_loop.trial.base import Budgets + + +class RecoveryTests(unittest.IsolatedAsyncioTestCase): + def client(self, outcomes, state="running"): + values = iter(outcomes) + + async def probe(pid): + value = next(values, outcomes[-1]) + if isinstance(value, BaseException): + raise value + return value + + async def lifecycle(): + return state + + return SimpleNamespace(is_pid_running=probe, get_lifecycle_state=lifecycle) + + async def run_monitor(self, client, rc=None, **kw): + async def read_rc(): + return rc + + return await monitor.observe_process( + client, + pid=123, + timeout=kw.get("timeout", 0.5), + recovery_timeout=kw.get("recovery_timeout", 0.1), + poll_interval=0.01, + retry_interval=0.01, + rc_wait_timeout=0.03, + rc_poll_interval=0.01, + read_rc=read_rc, + ) + + async def test_more_than_three_errors_can_recover(self): + result = await self.run_monitor(self.client([httpx.RemoteProtocolError("fixture")] * 5 + [False]), rc=0) + # rc is already trusted, so completion can occur before probe recovery. + self.assertEqual(result[0], "entry_completed") + seen = 0 + client = self.client([httpx.RemoteProtocolError("fixture")] * 5 + [False]) + + async def read_rc(): + nonlocal seen + seen += 1 + return 0 if seen > 5 else None + + result = await monitor.observe_process( + client, + pid=123, + timeout=0.5, + recovery_timeout=0.2, + poll_interval=0.01, + retry_interval=0.01, + rc_wait_timeout=0.03, + rc_poll_interval=0.01, + read_rc=read_rc, + ) + self.assertEqual(result[0], "entry_completed") + self.assertEqual(result[2]["pid_check_errors_total"], 5) + + async def test_persistent_unknown_and_terminal(self): + started = time.monotonic() + result = await self.run_monitor(self.client([httpx.ReadError("fixture")]), recovery_timeout=0.05) + self.assertEqual(result[0], "pid_monitor_error") + self.assertLess(time.monotonic() - started, 0.2) + self.assertTrue(result[2]["recovery_deadline_reached"]) + result = await self.run_monitor(self.client([httpx.ReadError("fixture")], state="failed")) + self.assertEqual(result[0], "sandbox_unavailable") + + async def test_entry_deadline_and_cancellation(self): + result = await self.run_monitor(self.client([httpx.ReadError("fixture")]), timeout=0.04, recovery_timeout=120) + self.assertEqual(result[0], "pid_monitor_error") + self.assertTrue(result[2]["deadline_reached"]) + with self.assertRaises(asyncio.CancelledError): + await self.run_monitor(self.client([asyncio.CancelledError()])) + + async def test_exit_rc_missing_zombie_and_unknown_boolean(self): + self.assertEqual((await self.run_monitor(self.client([False]), rc=7))[:2], ("entry_failed", 7)) + self.assertEqual((await self.run_monitor(self.client([False])))[0], "rc_missing") + self.assertEqual((await self.run_monitor(self.client([True]), timeout=0.03))[0], "timeout") + self.assertEqual((await self.run_monitor(self.client([None]), recovery_timeout=0.03))[0], "pid_monitor_error") + + async def test_rc_errors_are_not_missing_and_good_pid_does_not_reset_budget(self): + async def read_rc(): + raise httpx.ReadTimeout("fixture") + + for recovery in (0, 0.04): + result = await monitor.observe_process( + self.client([False]), + pid=123, + timeout=0.3, + recovery_timeout=recovery, + poll_interval=0.01, + retry_interval=0.01, + rc_wait_timeout=0.01, + rc_poll_interval=0.01, + read_rc=read_rc, + ) + self.assertEqual(result[0], "pid_monitor_error") + self.assertEqual(result[2]["probe_kind"], "rc") + self.assertLessEqual(len(result[2]["rc_checks"]), 3) + + async def test_python310_asyncio_timeout_is_an_unknown_observation(self): + from unittest.mock import patch + + class LegacyAsyncioTimeout(Exception): + pass + + with patch.object(monitor.asyncio, "TimeoutError", LegacyAsyncioTimeout): + result = await self.run_monitor(self.client([LegacyAsyncioTimeout()]), recovery_timeout=0.03) + self.assertEqual(result[0], "pid_monitor_error") + self.assertGreater(result[2]["pid_check_errors_total"], 0) + + async def test_rc_recovers_after_read_outage(self): + reads = iter([httpx.ReadError("fixture"), None, 0]) + + async def read_rc(): + value = next(reads) + if isinstance(value, Exception): + raise value + return value + + result = await monitor.observe_process( + self.client([False]), + pid=123, + timeout=0.3, + recovery_timeout=0.1, + poll_interval=0.01, + retry_interval=0.01, + rc_wait_timeout=0.05, + rc_poll_interval=0.01, + read_rc=read_rc, + ) + self.assertEqual(result[:2], ("entry_completed", 0)) + self.assertEqual(result[2]["rc_check_errors_total"], 1) + + +def detached_job(tmp_path, pid_result, rc): + directory = "/private/jobs/fixture" + + async def exec_command(_, command, **kwargs): + assert command == "kill -0 123 2>/dev/null" + return pid_result + + async def download(_, path, **kwargs): + assert path in {directory + "/pid", directory + "/rc"} + return b"123" if path.endswith("/pid") else rc + + return DetachedJob( + id="fixture", + resource=ResourceHandle("main", "sandbox"), + kind="agent", + directory=directory, + client=SimpleNamespace(exec=exec_command, download=download), + budgets=Budgets(), + output_dir=tmp_path, + ) + + +@pytest.mark.asyncio +async def test_detached_job_uses_exit_code_when_pid_query_is_unavailable(tmp_path): + job = detached_job(tmp_path, Failure("SANDBOX_HTTP", "exec", "PID observation unavailable"), b"7\n") + + assert await job.wait(0.2) == 7 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("rc", "reason"), + [ + (None, "rc_missing"), + (b"broken", "pid_monitor_error"), + (Failure("SANDBOX_HTTP", "download", "capture unavailable"), "pid_monitor_error"), + ], +) +async def test_detached_job_distinguishes_unreadable_and_missing_exit_codes(tmp_path, rc, reason): + job = detached_job(tmp_path, SimpleNamespace(return_code=1), rc) + + assert await job.wait(0.05) == Failure("JOB_LOST", "monitor", reason) diff --git a/tests/rl/test_sandbox_cleanup_protocol.py b/tests/rl/test_sandbox_cleanup_protocol.py new file mode 100644 index 0000000000..47b82f6d27 --- /dev/null +++ b/tests/rl/test_sandbox_cleanup_protocol.py @@ -0,0 +1,534 @@ +"""Cleanup ownership through public Runtime/Job APIs and external HTTP faults.""" + +import asyncio +import json +from builtins import BaseExceptionGroup +from collections import Counter +from dataclasses import replace + +import httpx +import pytest +from aiohttp import web +from mini_agent import Failure, HarnessSpec +from sandbox_http_fixture import SandboxPlatform +from test_sandbox_runtime_v3 import context, platform_server + +from xtuner.v1.rl.agent_loop.trial_agent_loop.sandbox.jobs import NativeJob +from xtuner.v1.rl.agent_loop.trial_agent_loop.sandbox.runtime import SandboxRuntime +from xtuner.v1.rl.agent_loop.trial_agent_loop.sandbox.types import SandboxConfig, cmd +from xtuner.v1.rl.agent_loop.trial_agent_loop.trial.base import ResourceSpec +from xtuner.v1.rl.observability import Observation + + +def runtime( + path, url, *, fail_fast=False, backend="opensandbox", platform="dbox", require_clean_exit=False, **budgets +): + key = path / "key" + key.write_text("external-test-key") + return SandboxRuntime( + ctx=replace(context(path, **budgets), fail_fast=fail_fast), + sandbox_cfg=SandboxConfig( + endpoint=url, + project="test", + credential_file=str(key), + backend=backend, + platform=platform, + command_mode="native" if backend == "opensandbox" else "detached", + ), + default_resources=ResourceSpec(), + harness=HarnessSpec("mini_swe"), + max_turns=1, + tool_user=None, + tool_env={}, + require_clean_exit=require_clean_exit, + ) + + +def leaves(error): + if isinstance(error, BaseExceptionGroup): + return [leaf for item in error.exceptions for leaf in leaves(item)] + return [error] + + +def test_ready_resource_is_deleted_while_another_original_create_is_pending(tmp_path): + async def scenario(): + slow_post, deleted_a = asyncio.Event(), asyncio.Event() + calls, deleted = Counter(), set() + + async def platform(request): + if request.method == "POST": + name = (await request.json())["image"]["uri"] + calls[name] += 1 + if name == "B": + slow_post.set() + # Cross the handoff window without blocking A's deletion. + await asyncio.sleep(0.3) + return web.json_response({"id": name}) + sid = request.path.split("/")[3] + if request.method == "DELETE": + deleted.add(sid) + deleted_a.set() + return web.Response(status=204) + if request.path.endswith("/ping"): + return web.json_response({"ok": True}) + return web.Response(status=404) if sid in deleted else web.json_response({"state": "running"}) + + async with platform_server(platform) as url: + sb = runtime(tmp_path, url, cleanup=0.15, create_rpc=1) + + async def attempt(): + async with sb: + assert not isinstance(await sb.acquire("A", image="A"), Failure) + await sb.acquire("B", image="B") + + owner = asyncio.create_task(attempt()) + await asyncio.wait_for(slow_post.wait(), 2) + owner.cancel("body cancellation") + try: + await asyncio.wait_for(deleted_a.wait(), 0.1) + owner.cancel("cleanup wait cancellation") + with pytest.raises(asyncio.CancelledError): + await owner + finally: + await asyncio.gather(owner, return_exceptions=True) + assert deleted == {"A"} and calls == {"A": 1, "B": 1} + report = json.loads((tmp_path / "cleanup.json").read_text()) + assert report["remaining_ids"] == [] and set(report["unresolved_creates"]) == {"B"} + + asyncio.run(scenario()) + + +def test_concurrent_and_repeated_exit_share_deletion_and_keep_each_waiter_cancel(tmp_path, monkeypatch): + async def scenario(): + deleting, release = asyncio.Event(), asyncio.Event() + calls = Counter() + + async def platform(request): + calls[request.method] += 1 + if request.method == "POST": + return web.json_response({"id": "same-remote-id"}) + if request.method == "DELETE": + deleting.set() + await release.wait() + return web.Response(status=204) + if request.path.endswith("/ping"): + return web.json_response({"ok": True}) + return web.Response(status=404) if release.is_set() else web.json_response({"state": "running"}) + + async with platform_server(platform) as url: + sb = runtime(tmp_path, url, cleanup=2) + close_http = httpx.AsyncClient.aclose + + async def aclose(client): + if client is sb.client.http: + calls["aclose"] += 1 + await close_http(client) + + monkeypatch.setattr(httpx.AsyncClient, "aclose", aclose) + await sb.__aenter__() + first, again, second = await asyncio.gather( + sb.acquire("A", image="test"), sb.acquire("A", image="test"), sb.acquire("B", image="test") + ) + assert first == again and second.id == first.id + one, two = asyncio.create_task(sb._close()), asyncio.create_task(sb._close()) + await asyncio.wait_for(deleting.wait(), 2) + one.cancel("only first waiter") + await asyncio.sleep(0) + assert not one.done() and not two.done() + with pytest.raises(asyncio.CancelledError): + await sb.acquire("late", image="test") + with pytest.raises(asyncio.CancelledError): + await sb.verify(first, command=cmd("true"), outputs=[]) + release.set() + with pytest.raises(asyncio.CancelledError, match="only first waiter"): + await one + await two + await sb._close() + assert await sb.__aexit__(None, None, None) is False + assert calls["POST"] == 2 and calls["DELETE"] == 1 and calls["aclose"] == 1 + + asyncio.run(scenario()) + + +@pytest.mark.parametrize("overlap", [False, True]) +def test_explicit_release_and_exit_share_remote_id_and_keep_release_waiter_cancel(tmp_path, overlap): + async def scenario(): + deleting, finish_delete = asyncio.Event(), asyncio.Event() + calls = Counter() + deleted = False + + async def platform(request): + nonlocal deleted + calls[request.method] += 1 + if request.method == "POST": + return web.json_response({"id": "shared-id"}) + if request.method == "DELETE": + deleting.set() + await finish_delete.wait() + deleted = True + return web.Response(status=204) + if request.path.endswith("/ping"): + return web.json_response({"ok": True}) + return web.Response(status=404) if deleted else web.json_response({"state": "running"}) + + async with platform_server(platform) as url: + sb = runtime(tmp_path, url, require_clean_exit=True, cleanup=1) + await asyncio.gather(sb.acquire("A", image="test"), sb.acquire("B", image="test")) + release = asyncio.create_task(sb.release("A")) + await asyncio.wait_for(deleting.wait(), 2) + close = asyncio.create_task(sb.__aexit__(None, None, None)) if overlap else None + release.cancel("release waiter cancelled") + await asyncio.sleep(0) + release.cancel("release waiter cancelled again") + assert not release.done() + finish_delete.set() + with pytest.raises(asyncio.CancelledError, match="release waiter cancelled"): + await release + if close is not None: + await close + await sb.__aexit__(None, None, None) + assert await sb.release("A") is None + assert sb.cleanup_failure is None + report = json.loads((tmp_path / "cleanup.json").read_text()) + assert calls["POST"] == 2 and calls["DELETE"] == 1 + assert report["release_status"] == {"A": "DELETED", "B": "DELETED"} + receipts = report["released_resources"] + assert receipts["A"]["source"] == "explicit" and receipts["B"]["source"] == "close" + assert {receipt["sandbox_id"] for receipt in receipts.values()} == {"shared-id"} + assert report["errors"] == [] + + with Observation(tmp_path / "observability", {"session_id": "release-race"}).activate(): + asyncio.run(scenario()) + events = [ + json.loads(line) + for path in (tmp_path / "observability").glob("events.*.jsonl") + for line in path.read_text().splitlines() + ] + created = { + row["data"]["resource_name"]: row["data"]["operation_id"] + for row in events + if row["event"] == "resource_create_started" + } + released = [row["data"] for row in events if row["event"] == "resource_released"] + assert Counter(row["resource_name"] for row in released) == {"A": 1, "B": 1} + assert all( + row["operation_id"] == created[row["resource_name"]] and row["sandbox_id"] == "shared-id" for row in released + ) + + +@pytest.mark.parametrize("fault", ["exception", "cancel"]) +@pytest.mark.parametrize("overlap", [False, True]) +def test_release_original_delete_error_survives_exit_even_when_isolated(tmp_path, monkeypatch, fault, overlap): + async def scenario(): + platform = SandboxPlatform(tmp_path / "platform") + delete_started, finish_delete = asyncio.Event(), asyncio.Event() + async with platform_server(platform) as url: + sb = runtime(tmp_path, url, require_clean_exit=True, cleanup=1) + request_http = httpx.AsyncClient.request + original_error = ValueError("external DELETE bug") + + async def request(client, method, request_url, *args, **kwargs): + if client is sb.client.http and method == "DELETE": + delete_started.set() + await finish_delete.wait() + if fault == "cancel": + raise asyncio.CancelledError("DELETE self cancellation") + raise original_error + return await request_http(client, method, request_url, *args, **kwargs) + + monkeypatch.setattr(httpx.AsyncClient, "request", request) + await sb.acquire("A", image="test") + release = asyncio.create_task(sb.release("A")) + await asyncio.wait_for(delete_started.wait(), 2) + close = asyncio.create_task(sb.__aexit__(None, None, None)) if overlap else None + finish_delete.set() + with pytest.raises(BaseException) as release_error: + await release + if close is None: + close = asyncio.create_task(sb.__aexit__(None, None, None)) + if fault == "cancel": + with pytest.raises(BaseException) as close_error: + await close + assert any(isinstance(error, asyncio.CancelledError) for error in leaves(release_error.value)) + assert any(isinstance(error, asyncio.CancelledError) for error in leaves(close_error.value)) + assert sb.cleanup_failure is None + else: + await close + assert original_error in leaves(release_error.value) + assert sb.cleanup_failure.code == "TRIAL_CLEANUP_EXCEPTION" + report = json.loads((tmp_path / "cleanup.json").read_text()) + assert report["release_status"] == {"A": "TTL"} and report["released_resources"] == {} + assert any("release/A" in error for error in report["errors"]) + + asyncio.run(scenario()) + + +@pytest.mark.parametrize("strict", [False, True]) +def test_strict_exit_requires_a_written_cleanup_report_after_confirmed_release(tmp_path, monkeypatch, strict): + async def scenario(): + platform = SandboxPlatform(tmp_path / "platform") + async with platform_server(platform) as url: + sb = runtime(tmp_path, url, require_clean_exit=strict, cleanup=1) + write_text = type(tmp_path).write_text + + def write(path, *args, **kwargs): + if path == tmp_path / "cleanup.json": + raise OSError("external disk full") + return write_text(path, *args, **kwargs) + + monkeypatch.setattr(type(tmp_path), "write_text", write) + async with sb: + await sb.acquire("A", image="test") + assert await sb.release("A") is None + assert platform.deleted and not (tmp_path / "cleanup.json").exists() + assert (sb.cleanup_failure.code if sb.cleanup_failure else None) == ( + "SANDBOX_CLEANUP_UNCONFIRMED" if strict else None + ) + + asyncio.run(scenario()) + + +@pytest.mark.parametrize("fail_fast", [False, True]) +@pytest.mark.parametrize("strict", [False, True]) +def test_client_close_timeout_alone_is_unconfirmed_and_propagates(tmp_path, monkeypatch, fail_fast, strict): + async def scenario(): + platform = SandboxPlatform(tmp_path / "platform") + async with platform_server(platform) as url: + sb = runtime(tmp_path, url, fail_fast=fail_fast, require_clean_exit=strict, cleanup=0.1) + close_http = httpx.AsyncClient.aclose + calls = 0 + + async def aclose(client): + nonlocal calls + if client is sb.client.http: + calls += 1 + try: + await asyncio.Event().wait() + finally: + await close_http(client) + else: + await close_http(client) + + monkeypatch.setattr(httpx.AsyncClient, "aclose", aclose) + with pytest.raises(TimeoutError): + async with sb: + await sb.acquire("main", image="test") + assert platform.deleted and calls == 1 and sb.cleanup_failure is None + + asyncio.run(scenario()) + + +@pytest.mark.parametrize("platform_name,contained", [("dbox", False), ("hbox", True)]) +@pytest.mark.parametrize("fail_fast", [False, True]) +@pytest.mark.parametrize("strict", [False, True]) +def test_delete_without_receipt_requires_the_ttl_actually_sent(tmp_path, platform_name, contained, fail_fast, strict): + async def scenario(): + bodies = [] + + async def platform(request): + if request.method == "POST": + bodies.append(await request.json()) + return web.json_response({"id": "owned", "accessToken": "server-token"}) + if request.method == "DELETE": + return web.Response(status=503) + if request.path.endswith("/ping"): + return web.json_response({"ok": True}) + return web.json_response({"state": "running", "status": {"state": "Running"}}) + + async with platform_server(platform) as url: + sb = runtime( + tmp_path, + url, + platform=platform_name, + fail_fast=fail_fast, + require_clean_exit=strict, + sandbox_ttl=0.1, + cleanup=0.04, + ) + + async def attempt(): + async with sb: + assert not isinstance(await sb.acquire("main", image="test"), Failure) + + if contained: + await attempt() + assert bodies[0]["lifecycleMinutes"] == 1 + else: + with pytest.raises(RuntimeError, match="no delete receipt or expiry"): + await attempt() + assert bodies[0]["timeout"] == 0 + report = json.loads((tmp_path / "cleanup.json").read_text()) + assert report["remaining_ids"] == ["owned"] + assert (sb.cleanup_failure.code if sb.cleanup_failure else None) == ( + "SANDBOX_CLEANUP_UNCONFIRMED" if contained and strict else None + ) + + asyncio.run(scenario()) + + +@pytest.mark.parametrize("bad_url", [None, 17, "", "not-an-http-url"]) +def test_gateway_partial_receipt_keeps_valid_id_for_delete(tmp_path, bad_url): + async def scenario(): + deleted = [] + + async def platform(request): + if request.method == "POST": + return web.json_response({"env": {"env_id": "known-env", "url": bad_url}}) + if request.method == "DELETE": + deleted.append(request.path.rsplit("/", 1)[-1]) + return web.json_response({"ok": True}) + raise AssertionError("invalid connection parameters must not be used") + + async with platform_server(platform) as url: + async with runtime(tmp_path, url, backend="env_gateway", cleanup=0.1) as sb: + result = await sb.acquire("main", image="test") + assert isinstance(result, Failure) and result.code == "CREATE_FAILED" + assert deleted == ["known-env"] + report = json.loads((tmp_path / "cleanup.json").read_text()) + assert report["remaining_ids"] == [] and report["unresolved_creates"] == {} + + asyncio.run(scenario()) + + +@pytest.mark.parametrize("backend", ["opensandbox", "env_gateway"]) +def test_empty_remote_id_stays_unknown_and_is_never_deleted(tmp_path, backend): + async def scenario(): + calls = Counter() + + async def platform(request): + calls[request.method] += 1 + return web.json_response({"id": "", "env": {"env_id": "", "url": "http://unusable"}}) + + async with platform_server(platform) as url: + async with runtime(tmp_path, url, backend=backend, cleanup=0.1, attempt=0.05) as sb: + result = await sb.acquire("main", image="test") + assert isinstance(result, Failure) and result.code == "CREATE_FAILED" + assert calls == {"POST": 1} + report = json.loads((tmp_path / "cleanup.json").read_text()) + assert report["remaining_ids"] == [] and set(report["unresolved_creates"]) == {"main"} + + asyncio.run(scenario()) + + +@pytest.mark.parametrize("fault", ["unseen_error", "seen_error", "self_cancel"]) +@pytest.mark.parametrize("fail_fast", [False, True]) +def test_native_launch_original_outcome_survives_resource_cleanup(tmp_path, monkeypatch, fault, fail_fast): + async def scenario(): + platform = SandboxPlatform(tmp_path / "platform") + launched, release, finished = asyncio.Event(), asyncio.Event(), asyncio.Event() + send = httpx.AsyncClient.send + starts = 0 + + async def exchange(client, request, *args, **kwargs): + nonlocal starts + if ( + request.method == "POST" + and request.url.path.endswith("/command") + and json.loads(request.content).get("background") + ): + starts += 1 + launched.set() + await release.wait() + finished.set() + if fault == "self_cancel": + raise asyncio.CancelledError("launch cancelled itself") + raise RuntimeError("original launch failed") + return await send(client, request, *args, **kwargs) + + monkeypatch.setattr(httpx.AsyncClient, "send", exchange) + async with platform_server(platform) as url: + sb = runtime(tmp_path, url, fail_fast=fail_fast, cleanup=0.1, request=5) + + async def attempt(): + async with sb: + resource = await sb.acquire("main", image="test") + start = asyncio.create_task( + sb.start_service(resource, command=cmd("true"), port=80, ready=("true",)) + ) + await asyncio.wait_for(launched.wait(), 2) + if fault == "seen_error": + release.set() + with pytest.raises(RuntimeError, match="original launch failed"): + await start + else: + start.cancel() + with pytest.raises(asyncio.CancelledError): + await start + release.set() + await finished.wait() + await asyncio.sleep(0) + + if fault == "self_cancel": + with pytest.raises(asyncio.CancelledError): + await attempt() + elif fault == "unseen_error" and fail_fast: + with pytest.raises(RuntimeError, match="original launch failed"): + await attempt() + else: + await attempt() + assert (sb.cleanup_failure is not None) is (fault == "unseen_error") + assert platform.deleted and starts == 1 + + asyncio.run(scenario()) + + +@pytest.mark.parametrize("fail_fast", [False, True]) +def test_job_close_raising_cannot_be_isolated_as_a_launch_error(tmp_path, fail_fast): + class UnconfirmedCloseJob(NativeJob): + async def close(self): + await super().close() + raise RuntimeError("job close did not acknowledge completion") + + async def scenario(): + platform = SandboxPlatform(tmp_path / "platform") + + async def provider(request): + if request.method == "POST" and request.path.endswith("/command"): + if (await request.json()).get("background"): + return web.Response(text='data: {"type":"init","text":"native-id"}\n\n') + if "/command/status/" in request.path: + return web.json_response({"running": False, "exit_code": 0}) + if request.path.endswith("/logs"): + return web.Response(text="command completed") + return await platform(request) + + async with platform_server(provider) as url: + sb = runtime(tmp_path, url, fail_fast=fail_fast, cleanup=0.1) + # A Job implementation can itself fail to close. Keep native launch, + # execution and HTTP cleanup real while exercising that contract. + sb._job_type = UnconfirmedCloseJob + with pytest.raises(RuntimeError, match="job close did not acknowledge"): + async with sb: + resource = await sb.acquire("main", image="test") + evidence = await sb.verify(resource, command=cmd("true"), outputs=[]) + assert evidence.return_code == 0 + assert platform.deleted and sb.cleanup_failure is None + + asyncio.run(scenario()) + + +@pytest.mark.parametrize("backend", ["opensandbox", "env_gateway"]) +def test_delete_does_not_reclassify_an_unrelated_timeout(tmp_path, monkeypatch, backend): + async def scenario(): + async def platform(request): + return web.Response(status=503) + + async with platform_server(platform) as url: + sb = runtime(tmp_path, url, backend=backend) + sleep = asyncio.sleep + + async def interrupted_sleep(delay, *args, **kwargs): + if delay == 0.5: + raise TimeoutError("inner transport deadline") + return await sleep(delay, *args, **kwargs) + + # Simulate an unrelated timer failure after the real HTTP response; + # only expiration of delete's own scope may become DELETE_FAILED. + monkeypatch.setattr(asyncio, "sleep", interrupted_sleep) + try: + with pytest.raises(TimeoutError, match="inner transport deadline"): + await sb.client.delete("owned", timeout=1) + finally: + await sb.client.aclose() + + asyncio.run(scenario()) diff --git a/tests/rl/test_sandbox_runtime_v3.py b/tests/rl/test_sandbox_runtime_v3.py new file mode 100644 index 0000000000..eee9a2bd9c --- /dev/null +++ b/tests/rl/test_sandbox_runtime_v3.py @@ -0,0 +1,1841 @@ +"""Runtime lifecycle through a real HTTP connection to an external platform double.""" + +import asyncio +import json +import socket +from builtins import BaseExceptionGroup +from contextlib import asynccontextmanager +from pathlib import Path + +import pytest +from aiohttp import web +from mini_agent import HarnessSpec, ModelSettings, SequenceLimits + +from xtuner.v1.rl.agent_loop.trial_agent_loop.sandbox.runtime import SandboxRuntime +from xtuner.v1.rl.agent_loop.trial_agent_loop.sandbox.types import SandboxConfig +from xtuner.v1.rl.agent_loop.trial_agent_loop.trial.base import Budgets, ResourceSpec, TaskInput, TrialContext + + +@asynccontextmanager +async def platform_server(handler): + app = web.Application() + app.router.add_route("*", "/{path:.*}", handler) + runner = web.AppRunner(app) + await runner.setup() + with socket.socket() as sock: + sock.bind(("127.0.0.1", 0)) + sock.listen() + await web.SockSite(runner, sock).start() + try: + yield "http://127.0.0.1:" + str(sock.getsockname()[1]) + finally: + await runner.cleanup() + + +def context(path, task=TaskInput(("test", "runtime"), "lifecycle", {}), **budgets): + return TrialContext( + task, + "attempt-1", + path, + Budgets(**budgets), + ModelSettings("http://model", "attempt-1", "test", {}, SequenceLimits(100, 100, 10)), + None, + ) + + +def test_hbox_opensandbox_lifecycle_files_and_native_commands(tmp_path): + from xtuner.v1.rl.agent_loop.trial_agent_loop.sandbox.client import OpenSandboxCommands, make_sandbox_client + from xtuner.v1.rl.agent_loop.trial_agent_loop.sandbox.types import ResourceHandle + + async def scenario(): + creates, deleted, files = [], [], {} + + async def platform(req): + if "/proxy/" in req.path: + assert "project" not in req.query + else: + assert req.query["project"] == "hbox-project" + assert req.headers["OPEN-SANDBOX-API-KEY"] == "external-key" + if req.path == "/v1/sandboxes": + creates.append(await req.json()) + return web.json_response( + {"id": "hbox-owned", "status": {"state": "Pending"}, "accessToken": "server-sat"}, + status=202, + ) + if req.method == "DELETE" and req.path == "/v1/sandboxes/hbox-owned": + deleted.append("hbox-owned") + return web.Response(status=204) + if req.path == "/v1/sandboxes/hbox-owned": + return web.Response(status=404) if deleted else web.json_response({"status": {"state": "Running"}}) + assert req.headers["X-Sandbox-Access-Token"] == "server-sat" + if req.path.endswith("/ping"): + return web.json_response({"ok": True}) + if req.path.endswith("/files/upload"): + parts = await req.multipart() + metadata = json.loads(await (await parts.next()).text()) + files[metadata["path"]] = bytes(await (await parts.next()).read()) + return web.Response(status=204) + if req.path.endswith("/files/download"): + return web.Response(body=files[req.query["path"]]) + if req.path.endswith("/command"): + body = await req.json() + events = [{"type": "init", "text": "native-id"}] + if not body.get("background"): + events += [{"type": "stdout", "text": "hbox-ok"}, {"type": "execution_complete"}] + return web.Response(text="\n".join(json.dumps(event) for event in events)) + if "/command/status/" in req.path: + return web.json_response({"running": False, "exit_code": 7}) + if req.path.endswith("/logs"): + return web.Response(text="native-output") + raise AssertionError(req.path) + + key = tmp_path / "key" + key.write_text("external-key") + async with platform_server(platform) as url: + client = make_sandbox_client( + SandboxConfig( + backend="opensandbox", + platform="hbox", + endpoint=url, + project="hbox-project", + credential_file=str(key), + command_mode="native", + ), + "attempt-1", + ) + try: + created = await client.create( + image="swe-image", + ports=(), + resources=ResourceSpec(cpus=2, memory_mb=8192), + ttl=45000, + token="execd-token", + op_id="one-create", + timeout=2, + ) + assert created == ("hbox-owned", "") + handle = ResourceHandle("main", created[0], token="execd-token") + assert await client.wait_ready(handle, timeout=2) is None + assert await client.upload(handle, "/tmp/data", b"actual-bytes", timeout=2) is None + assert await client.download(handle, "/tmp/data", timeout=2) == b"actual-bytes" + execution = await client.exec(handle, "printf hbox-ok", cwd="/tmp", timeout=2) + assert execution.return_code == 0 and execution.stdout == "hbox-ok" + native = OpenSandboxCommands(client, handle, request_seconds=2) + assert await native.start_command("exit 7", "/tmp", 2) == "native-id" + assert await native.get_command_status("native-id") == {"running": False, "return_code": 7} + assert (await native.get_command_output("native-id"))["stdout"] == "native-output" + assert await client.delete(handle.id, timeout=2) is None + finally: + await client.aclose() + assert len(creates) == 1 and deleted == ["hbox-owned"] + assert creates[0]["resources"] == {"cpu": "2", "memory": "8192Mi"} + assert creates[0]["lifecycleMinutes"] == 750 + assert creates[0]["env"] == {"EXECD_ACCESS_TOKEN": "execd-token"} + + asyncio.run(scenario()) + + +@pytest.mark.parametrize("sat_present", [False, True]) +def test_hbox_failed_or_missing_sat_keeps_known_id_for_cleanup(tmp_path, sat_present): + from mini_agent import Failure + + async def scenario(): + deleted = [] + + async def platform(req): + assert req.query["project"] == "test" + if req.method == "POST": + body = {"id": "hbox-failed", "status": {"state": "Pending"}} + if sat_present: + body["accessToken"] = "sat" + return web.json_response(body, status=202) + if req.method == "DELETE": + deleted.append("hbox-failed") + return web.Response(status=204) + return web.Response(status=404) if deleted else web.json_response({"status": {"state": "Failed"}}) + + key = tmp_path / "key" + key.write_text("external-key") + async with platform_server(platform) as url: + async with SandboxRuntime( + ctx=context(tmp_path, attempt=2, cleanup=2), + sandbox_cfg=SandboxConfig(platform="hbox", endpoint=url, project="test", credential_file=str(key)), + default_resources=ResourceSpec(cpus=2, memory_mb=8192), + harness=HarnessSpec("mini_swe"), + max_turns=1, + tool_user=None, + tool_env={}, + ) as runtime: + result = await runtime.acquire("main", image="swe-image") + assert isinstance(result, Failure) + assert result.code == ("SANDBOX_NOT_READY" if sat_present else "SANDBOX_RESPONSE_INVALID") + assert deleted == ["hbox-failed"] + cleanup = json.loads((tmp_path / "cleanup.json").read_text()) + assert cleanup["remaining_ids"] == [] and cleanup["unresolved_creates"] == {} + + asyncio.run(scenario()) + + +@pytest.mark.parametrize("status", [400, 429, 503]) +def test_create_rejection_is_distinct_from_unknown_creation_in_cleanup(tmp_path, status): + from dataclasses import asdict + + from mini_agent import Failure + + from xtuner.v1.rl.observability import Observation, TrialObservation, read_report + + async def scenario(): + calls = [] + + async def platform(req): + calls.append(req.method) + return web.json_response( + {"detail": {"code": "QUOTA_EXCEEDED", "message": "CPU quota exceeded"}}, status=status + ) + + key = tmp_path / "key" + key.write_text("external-test-key") + observation = Observation(tmp_path / "observability", {"run_id": "runtime", "session_id": "attempt-1"}) + async with platform_server(platform) as url: + cfg = SandboxConfig(endpoint=url, project="test", credential_file=str(key)) + with TrialObservation(observation) as attempt: + async with SandboxRuntime( + ctx=context(tmp_path), + sandbox_cfg=cfg, + default_resources=ResourceSpec(cpus=1, memory_mb=64), + harness=HarnessSpec("mini_swe"), + max_turns=1, + tool_user=None, + tool_env={}, + ) as runtime: + result = await runtime.acquire("main", image="test") + assert isinstance(result, Failure) + if status == 429: + assert result.code == "RESOURCE_RATE_LIMITED" + assert "QUOTA_EXCEEDED" in result.detail and "CPU quota exceeded" in result.detail + attempt.result = {"status": "failed", "error": asdict(result), "score": None} + assert calls == ["POST"] # Neither replay a rejected POST nor delete an unknown ID. + cleanup = json.loads((tmp_path / "cleanup.json").read_text()) + assert len(cleanup["unresolved_creates"]) == int(status == 503) + assert cleanup["remaining_ids"] == [] and cleanup["errors"] == [] + report = read_report(tmp_path) + assert report["resources"]["cleanup"]["resources"]["unknown_creates"] == int(status == 503) + + asyncio.run(scenario()) + + +def test_platform_rpc_and_native_logs_use_requested_deadline(tmp_path): + from mini_agent import Failure + + from xtuner.v1.rl.agent_loop.trial_agent_loop.sandbox.client import OpenSandboxClient, OpenSandboxCommands + from xtuner.v1.rl.agent_loop.trial_agent_loop.sandbox.types import ResourceHandle + + async def scenario(): + async def platform(req): + await req.read() + # Exercise the real former 20s deadline, within the caller's 25s. + delay = 20.2 if req.method == "POST" else 5.2 if req.path.endswith("/logs") else 0.2 + await asyncio.sleep(delay) + return web.Response(body=b"complete") + + key = tmp_path / "key" + key.write_text("external-test-key") + async with platform_server(platform) as url: + client = OpenSandboxClient( + SandboxConfig(endpoint=url, project="test", credential_file=str(key)), "rpc-budget" + ) + try: + handle = ResourceHandle("main", "test-id", token="exec-token") + uploaded = await client.upload(handle, "/tmp/request", b"payload", timeout=25) + assert uploaded is None + logs = await OpenSandboxCommands(client, handle, request_seconds=6).get_command_output("known-command") + assert logs == {"stdout": "complete", "stderr": ""} + # A larger HTTP allowance must still respect a short RPC budget. + downloaded = await client.download(handle, "/tmp/request", timeout=0.02) + assert isinstance(downloaded, Failure) and downloaded.code == "SANDBOX_IO" + finally: + await client.aclose() + + asyncio.run(scenario()) + + +@pytest.mark.parametrize("backend", ["opensandbox", "env_gateway"]) +@pytest.mark.parametrize("invalid", ["json", "array", "field"]) +def test_malformed_readiness_is_failure_and_known_resource_is_deleted(tmp_path, backend, invalid): + from mini_agent import Failure + + async def scenario(): + creates, deleted = [], [] + + async def platform(req): + if req.method == "POST": + creates.append(await req.json()) + return web.json_response( + {"id": "bad-ready"} + if backend == "opensandbox" + else {"env": {"env_id": "bad-ready", "url": "http://unused"}} + ) + if req.method == "DELETE": + deleted.append("bad-ready") + return web.json_response({"ok": True}) + if deleted: + return web.Response(status=404) + return ( + web.Response(text="{") + if invalid == "json" + else web.json_response([] if invalid == "array" else {"state": [], "status": []}) + ) + + key = tmp_path / "key" + key.write_text("external-key") + async with platform_server(platform) as url: + async with SandboxRuntime( + ctx=context(tmp_path, attempt=2, cleanup=2), + sandbox_cfg=SandboxConfig(backend=backend, endpoint=url, project="test", credential_file=str(key)), + default_resources=ResourceSpec(), + harness=HarnessSpec("mini_swe"), + max_turns=1, + tool_user=None, + tool_env={}, + ) as runtime: + result = await runtime.acquire("main", image="test-image") + assert isinstance(result, Failure) and result.code == "SANDBOX_RESPONSE_INVALID" + assert len(creates) == 1 and deleted == ["bad-ready"] + assert json.loads((tmp_path / "cleanup.json").read_text())["remaining_ids"] == [] + + asyncio.run(scenario()) + + +def test_acquire_is_owned_once_and_deletion_is_confirmed(tmp_path): + async def scenario(): + creates, deleted = [], [] + + async def platform(req): + if req.method == "POST": + creates.append(await req.json()) + return web.json_response({"id": "owned-main"}) + if req.method == "DELETE": + deleted.append("owned-main") + return web.Response(status=204) + if req.path.endswith("/ping"): + return web.json_response({"ok": True}) + return web.Response(status=404) if deleted else web.json_response({"state": "running"}) + + key = tmp_path / "platform-key" + key.write_text("external-test-key") + async with platform_server(platform) as url: + cfg = SandboxConfig(endpoint=url, project="test", credential_file=str(key)) + async with SandboxRuntime( + ctx=context(tmp_path), + sandbox_cfg=cfg, + default_resources=ResourceSpec(cpus=2, memory_mb=4096), + harness=HarnessSpec("mini_swe"), + max_turns=1, + tool_user=None, + tool_env={}, + ) as sb: + one = await sb.acquire("main", image="native-image", resources=ResourceSpec(memory_mb=8192)) + two = await sb.acquire("main", image="native-image", resources=ResourceSpec(memory_mb=8192)) + with pytest.raises(ValueError, match="conflicting sandbox"): + await sb.acquire("main", image="different-image") + assert one.id == two.id == "owned-main" + assert len(creates) == 1 + assert creates[0]["resourceRequests"] == {"cpu": "2", "memory": "8192Mi"} + assert deleted == ["owned-main"] + cleanup = json.loads((tmp_path / "cleanup.json").read_text()) + assert cleanup["remaining_ids"] == [] + assert cleanup["errors"] == [] + + asyncio.run(scenario()) + + +@pytest.mark.parametrize("phase", ["upload", "delete", "command"]) +@pytest.mark.parametrize("body", ["{", "[]", '{"ok": "true"}']) +def test_gateway_malformed_operation_response_is_explicit_failure(tmp_path, phase, body): + from mini_agent import Failure + + from xtuner.v1.rl.agent_loop.trial_agent_loop.sandbox.client import EnvGatewayClient + from xtuner.v1.rl.agent_loop.trial_agent_loop.sandbox.types import ResourceHandle + + async def scenario(): + async def platform(req): + return web.Response(text=body, content_type="application/json") + + key = tmp_path / "key" + key.write_text("external-key") + async with platform_server(platform) as url: + client = EnvGatewayClient( + SandboxConfig(backend="env_gateway", endpoint=url, project="test", credential_file=str(key)) + ) + handle = ResourceHandle("main", "known", url=url + "/env?token=public-test") + try: + if phase == "upload": + result = await client.upload(handle, "/tmp/test", b"test", timeout=1) + elif phase == "delete": + result = await client.delete(handle.id, timeout=1) + else: + result = await client.exec(handle, "true", cwd="/tmp", timeout=1) + assert isinstance(result, Failure) + assert result.code in {"SANDBOX_RESPONSE_INVALID", "COMMAND_UNKNOWN"} + finally: + await client.aclose() + + asyncio.run(scenario()) + + +@pytest.mark.parametrize("failure_mode", ["missing", "http_error", "cancelled"]) +def test_verify_retains_partial_artifacts_when_later_download_fails(tmp_path, failure_mode): + from mini_agent import Failure + from sandbox_http_fixture import SandboxPlatform + + from xtuner.v1.rl.agent_loop.trial_agent_loop.sandbox.types import RESULT_DIR, cmd + from xtuner.v1.rl.observability import Observation, read_report + + async def scenario(): + platform = SandboxPlatform(tmp_path / "platform") + downloads = [] + second_started, release_second = asyncio.Event(), asyncio.Event() + + async def sandbox_api(request): + if request.path.endswith("/files/download") and request.query["path"].endswith("missing.txt"): + second_started.set() + if failure_mode == "cancelled": + await release_second.wait() + response = web.Response(status=503 if failure_mode == "http_error" else 404) + else: + response = await platform(request) + if request.path.endswith("/files/download"): + downloads.append((request.query["path"], response.status)) + return response + + key = tmp_path / "key" + key.write_text("external-test-key") + observation = Observation(tmp_path / "observability", {"run_id": "partial", "session_id": "attempt-1"}) + async with platform_server(sandbox_api) as url: + with observation.activate(role="trial"): + async with SandboxRuntime( + ctx=context(tmp_path, attempt=5, verifier=5, request=2), + sandbox_cfg=SandboxConfig(endpoint=url, project="test", credential_file=str(key)), + default_resources=ResourceSpec(), + harness=HarnessSpec("mini_swe"), + max_turns=1, + tool_user=None, + tool_env={}, + ) as runtime: + resource = await runtime.acquire("main", image="test") + owner = asyncio.create_task( + runtime.verify( + resource, + command=cmd( + "bash", "-c", 'printf evidence > "$1/diagnostic.txt"; exit 7', "_", RESULT_DIR + ), + outputs=["diagnostic.txt", "missing.txt"], + ) + ) + try: + if failure_mode == "cancelled": + await asyncio.wait_for(second_started.wait(), 5) + owner.cancel() + with pytest.raises(asyncio.CancelledError): + await owner + else: + result = await owner + assert isinstance(result, Failure) + assert result.code == ( + "DOWNLOAD_FAILED" if failure_mode == "http_error" else "RESULT_MISSING" + ) + finally: + release_second.set() + report = read_report(tmp_path) + job = next(item for item in report["attempts"]["attempt-1"]["jobs"].values() if item["kind"] == "grader") + assert job["return_code"] == 7 + assert Path(job["artifact_paths"]["diagnostic.txt"]).read_bytes() == b"evidence" + assert job["artifact_errors"] == {} + assert len([path for path, _ in downloads if path.endswith("diagnostic.txt")]) == 1 + assert platform.deleted + assert json.loads((tmp_path / "cleanup.json").read_text())["remaining_ids"] == [] + + asyncio.run(scenario()) + + +def test_cancel_during_create_retains_late_id_through_repeated_cancel(tmp_path): + import pytest + + async def scenario(): + started, return_create, deleting, return_delete = (asyncio.Event() for _ in range(4)) + deleted, calls = [], [] + + async def platform(req): + calls.append(req.method) + if req.method == "POST": + started.set() + await return_create.wait() + return web.json_response({"id": "late-owned-id"}) + if req.method == "DELETE": + deleting.set() + await return_delete.wait() + deleted.append("late-owned-id") + return web.Response(status=204) + return web.Response(status=404 if deleted else 200) + + key = tmp_path / "key" + key.write_text("external-test-key") + async with platform_server(platform) as url: + cfg = SandboxConfig(endpoint=url, project="test", credential_file=str(key)) + + async def attempt(): + async with SandboxRuntime( + ctx=context(tmp_path, cleanup=2, create_rpc=1), + sandbox_cfg=cfg, + default_resources=ResourceSpec(), + harness=HarnessSpec("mini_swe"), + max_turns=1, + tool_user=None, + tool_env={}, + ) as sb: + await sb.acquire("main", image="test") + + owner = asyncio.create_task(attempt()) + await asyncio.wait_for(started.wait(), 3) + owner.cancel() + return_create.set() + await asyncio.wait_for(deleting.wait(), 3) + owner.cancel() + await asyncio.sleep(0.02) + assert not owner.done() + return_delete.set() + with pytest.raises(asyncio.CancelledError): + await owner + assert calls.count("POST") == 1 + assert deleted == ["late-owned-id"] + assert json.loads((tmp_path / "cleanup.json").read_text())["remaining_ids"] == [] + + asyncio.run(scenario()) + + +def test_platform_exec_requires_completion_and_preserves_a_real_nonzero_exit(tmp_path): + from xtuner.v1.rl.agent_loop.trial_agent_loop.sandbox.client import OpenSandboxClient + from xtuner.v1.rl.agent_loop.trial_agent_loop.sandbox.types import ResourceHandle + + async def scenario(): + replies = [ + [{"type": "stdout", "timestamp": 0, "text": "partial"}], + (Path(__file__).parent / "fixtures/opensandbox/exit7.events").read_bytes() + b"\n", + ] + calls = [] + + async def platform(req): + calls.append(await req.json()) + events = replies.pop(0) + if isinstance(events, bytes): + return web.Response(body=events, content_type="text/event-stream") + return web.Response( + text="".join("data: " + json.dumps(item) + "\n\n" for item in events), content_type="text/event-stream" + ) + + key = tmp_path / "key" + key.write_text("external-test-key") + async with platform_server(platform) as url: + client = OpenSandboxClient( + SandboxConfig(endpoint=url, project="test", credential_file=str(key)), "attempt-1" + ) + try: + partial = await client.exec( + ResourceHandle("main", "test-id", token="exec-token"), "echo partial", cwd="/tmp", timeout=1 + ) + assert partial.code == "COMMAND_UNKNOWN" + result = await client.exec( + ResourceHandle("main", "test-id", token="exec-token"), "exit 7", cwd="/tmp", timeout=1 + ) + assert result.return_code == 7 + assert len(calls) == 2 + finally: + await client.aclose() + + asyncio.run(scenario()) + + +def test_prepare_and_verify_run_real_shell_and_preserve_nonzero_grade_evidence(tmp_path): + from sandbox_http_fixture import SandboxPlatform + + from xtuner.v1.rl.agent_loop.trial_agent_loop.sandbox.types import RESULT_DIR, WORKSPACE, cmd + from xtuner.v1.rl.observability import Observation, read_report + + async def scenario(): + platform = SandboxPlatform(tmp_path / "platform") + key = tmp_path / "key" + key.write_text("external-test-key") + workspace = str(tmp_path / "workspace") + async with platform_server(platform) as url: + cfg = SandboxConfig(endpoint=url, project="test", credential_file=str(key)) + async with SandboxRuntime( + ctx=context(tmp_path, attempt=5, verifier=5, request=1), + sandbox_cfg=cfg, + default_resources=ResourceSpec(), + harness=HarnessSpec("mini_swe"), + max_turns=1, + tool_user=None, + tool_env={}, + ) as sb: + main = await sb.acquire("main", image="test") + ws = await sb.prepare( + main, + workspace=workspace, + setup=cmd("bash", "-c", 'mkdir -p "$1"; printf prepared > "$1/marker"', "_", WORKSPACE), + ) + assert ws.path == workspace + evidence = await sb.verify( + main, + workspace=ws.path, + command=cmd("bash", "-c", 'cat "$1/marker" > "$2/grade"; exit 1', "_", WORKSPACE, RESULT_DIR), + outputs=["grade"], + ) + assert evidence.return_code == 1 + assert evidence.files == {"grade": b"prepared"} + assert platform.deleted + + observation = Observation(tmp_path / "observability", {"run_id": "runtime", "session_id": "attempt-1"}) + with observation.activate(role="trial"): + asyncio.run(scenario()) + jobs = read_report(tmp_path)["attempts"]["attempt-1"]["jobs"] + assert {job["kind"] for job in jobs.values()} == {"setup", "grader"} + assert sorted(job["return_code"] for job in jobs.values()) == [0, 1] + assert all(job["sandbox_id"] == "owned-main" for job in jobs.values()) + assert all(Path(job["diagnostic_path"]).is_file() for job in jobs.values()) + grader = next(job for job in jobs.values() if job["kind"] == "grader") + assert Path(grader["artifact_paths"]["grade"]).read_bytes() == b"prepared" + assert grader["artifact_errors"] == {} + + +def test_runner_setup_failure_deletes_sandbox_and_never_uploads_private_verifier(tmp_path): + from mini_agent import Failure + from sandbox_http_fixture import SandboxPlatform + + from xtuner.v1.rl.agent_loop.trial_agent_loop.sandbox.types import cmd + from xtuner.v1.rl.agent_loop.trial_agent_loop.trial.base import TaskInput + from xtuner.v1.rl.agent_loop.trial_agent_loop.trial.sandbox_trial import SandboxTrialConfig + + def decode(evidence, options): + raise AssertionError("failed setup must not be graded") + + async def scenario(): + platform = SandboxPlatform(tmp_path / "platform") + key = tmp_path / "key" + key.write_text("external-test-key") + private = tmp_path / "private-verifier.py" + private.write_text("raise AssertionError('must not run')") + async with platform_server(platform) as url: + cfg = SandboxTrialConfig( + sandbox=SandboxConfig(endpoint=url, project="test", credential_file=str(key)), + harness=HarnessSpec("mini_swe"), + decode_grade=decode, + ) + task = TaskInput( + ("test", "failed-setup"), + "never starts", + { + "services": [], + "sandboxes": {"main": {"image": "test"}}, + "prepare": { + "main": { + "workspace": str(tmp_path / "workspace"), + "public_bundle": None, + "setup": cmd("bash", "-c", "exit 3"), + } + }, + "run_agent": {"sandbox": "main"}, + "verify": { + "sandbox": "main", + "command": cmd("python", "private-verifier.py", files={"private-verifier.py": str(private)}), + "outputs": [], + }, + "grade_options": {}, + }, + ) + result = await cfg.build(context(tmp_path, attempt=5, request=1, task=task)).run() + assert isinstance(result, Failure) and result.code == "SETUP_FAILED" + assert platform.deleted + assert not list(platform.root.rglob("private-verifier.py")) + + asyncio.run(scenario()) + + +def test_http_429_remains_visible_after_setup_failure_and_cleanup(tmp_path): + from dataclasses import asdict + + from mini_agent import Failure + from sandbox_http_fixture import SandboxPlatform + + from xtuner.v1.rl.agent_loop.trial_agent_loop.sandbox.types import cmd + from xtuner.v1.rl.agent_loop.trial_agent_loop.trial.base import TaskInput + from xtuner.v1.rl.agent_loop.trial_agent_loop.trial.sandbox_trial import SandboxTrialConfig + from xtuner.v1.rl.observability import Observation, TrialObservation, read_report + + async def scenario(): + async def limited_upload(path): + raise web.HTTPTooManyRequests(headers={"Retry-After": "2", "X-Request-ID": "rate-limit-request"}) + + platform = SandboxPlatform(tmp_path / "platform", on_upload=limited_upload) + key = tmp_path / "key" + key.write_text("external-test-key") + async with platform_server(platform) as url: + cfg = SandboxTrialConfig( + sandbox=SandboxConfig(endpoint=url, project="test", credential_file=str(key)), + harness=HarnessSpec("mini_swe"), + decode_grade=lambda *_: 1, + ) + task = TaskInput( + ("test", "rate-limited"), + "unused", + { + "services": [], + "sandboxes": {"main": {"image": "test"}}, + "prepare": { + "main": { + "workspace": str(tmp_path / "workspace"), + "public_bundle": None, + "setup": cmd("bash", "-c", "true"), + } + }, + "run_agent": {"sandbox": "main"}, + "verify": {"sandbox": "main", "command": cmd("unused"), "outputs": []}, + "grade_options": {}, + }, + ) + observation = Observation(tmp_path / "observability", {"run_id": "runtime", "session_id": "attempt-1"}) + with TrialObservation(observation) as attempt: + result = await cfg.build(context(tmp_path, attempt=5, cleanup=2, task=task)).run() + assert isinstance(result, Failure) and result.code == "UPLOAD_FAILED" + attempt.result = {"status": "failed", "error": asdict(result), "score": None} + assert platform.deleted + report = read_report(tmp_path) + assert report["sandbox_http"]["status_counts"]["429"] == 1 + assert report["sandbox_http"]["affected_attempts_by_status"]["429"] == 1 + samples = report["attempts"]["attempt-1"]["http_errors"] + limited = next(item for item in samples if item["status"] == 429) + assert limited["retry_after"] == "2" and limited["request_id"] == "rate-limit-request" + assert limited["operation"].endswith("/files/upload") + assert limited["phase"] == "job/setup" + + asyncio.run(scenario()) + + +def test_gateway_preserves_query_token_and_does_not_treat_service_failure_as_missing_file(tmp_path): + from mini_agent import Failure + + from xtuner.v1.rl.agent_loop.trial_agent_loop.sandbox.client import make_sandbox_client + from xtuner.v1.rl.agent_loop.trial_agent_loop.sandbox.types import ResourceHandle + + async def scenario(): + calls = [] + + async def platform(req): + calls.append((req.path, req.query.get("token"))) + if req.path.endswith("/exec"): + return web.json_response({"return_code": 1, "stdout": "failed assertion", "stderr": ""}) + return web.json_response({"ok": False}, status=503) + + key = tmp_path / "key" + key.write_text("external-test-key") + async with platform_server(platform) as url: + client = make_sandbox_client( + SandboxConfig(backend="env_gateway", endpoint=url, project="test", credential_file=str(key)), + "attempt-1", + ) + try: + handle = ResourceHandle("main", "test-id", url=url + "/runtime?token=hbox-token") + execution = await client.exec(handle, "exit 1", cwd="/tmp", timeout=1) + assert execution.return_code == 1 + content = await client.download(handle, "/result", timeout=1) + assert isinstance(content, Failure) and content.code == "DOWNLOAD_FAILED" + with pytest.raises(ValueError, match="env_gateway does not expose service ports"): + await client.resolve_endpoint(handle, 8765, timeout=1) + assert calls == [("/runtime/exec", "hbox-token"), ("/runtime/download", "hbox-token")] + finally: + await client.aclose() + + asyncio.run(scenario()) + + +def test_native_command_ids_need_no_pid_files_and_missing_exit_is_a_failure(tmp_path): + from mini_agent import Failure + + from xtuner.v1.rl.agent_loop.trial_agent_loop.sandbox.types import cmd + + async def scenario(exit_code, folder): + folder.mkdir() + calls, uploads, deleted, polls = [], [], [], [] + + async def platform(req): + calls.append(req.path) + if req.path.endswith("/files/upload"): + parts = await req.multipart() + async for part in parts: + if part.name == "metadata": + uploads.append(json.loads(await part.read())["path"]) + return web.json_response({"ok": True}) + if req.method == "POST" and req.path.endswith("/command"): + body = await req.json() + event = ( + {"type": "init", "text": "native-id", "timestamp": 0} + if body.get("background") + else {"type": "execution_complete", "timestamp": 0} + ) + return web.Response(text=json.dumps(event) + "\n", content_type="text/event-stream") + if "/command/status/" in req.path: + polls.append(req.path) + if len(polls) == 1: + # A failed proxy read is recoverable while the control + # plane still reports Running; it is not proof of OOM. + return web.Response(status=409, text="sandbox route not active") + status = {"running": False, "exit_code": exit_code} + if exit_code == -1: + # Production returned -1 with empty worker output. Keep + # its status evidence without interpreting the cause. + status.update( + started_at="2026-11-28T05:31:00Z", + finished_at="2026-11-28T05:32:00Z", + content="DO_NOT_RECORD_COMMAND_CONTENT", + ) + return web.json_response(status) + if req.path.endswith("/logs"): + return web.Response(text="native provider output") + if req.path.endswith("/ping"): + return web.json_response({"ok": True}) + if req.method == "POST": + return web.json_response({"id": "owned-main"}) + if req.method == "DELETE": + deleted.append(True) + return web.Response(status=204) + return web.Response(status=404) if deleted else web.json_response({"state": "running"}) + + key = folder / "key" + key.write_text("external-test-key") + async with platform_server(platform) as url: + cfg = SandboxConfig(endpoint=url, project="test", credential_file=str(key), command_mode="native") + async with SandboxRuntime( + ctx=context(folder), + sandbox_cfg=cfg, + default_resources=ResourceSpec(), + harness=HarnessSpec("mini_swe"), + max_turns=1, + tool_user=None, + tool_env={}, + ) as sb: + main = await sb.acquire("main", image="test") + evidence = await sb.verify(main, command=cmd("true"), outputs=[]) + if exit_code is None: + assert isinstance(evidence, Failure) and evidence.code == "EXIT_CODE_MISSING" + else: + assert evidence.return_code == exit_code + assert not any(path.endswith(("/pid", "/rc", "/job.sh")) for path in uploads) + assert not any(path.endswith(("/pid", "/rc")) for path in calls) + + async def run(): + for rc in (0, 1, None, -1): + await scenario(rc, tmp_path / str(rc)) + + from xtuner.v1.rl.observability import Observation, read_report + + observation = Observation(tmp_path / "observability", {"run_id": "native", "session_id": "attempt-1"}) + with observation.activate(): + asyncio.run(run()) + recorded = read_report(tmp_path)["sandbox_commands"] + assert recorded["status_observations"] == {"not_running_without_exit_code": 1, "negative_exit_code": 1} + assert recorded["samples"][0]["observed_fields"] == {"running": False, "exit_code": None} + assert recorded["samples"][0]["native_command_id"] == "native-id" + assert recorded["samples"][1]["observed_fields"] == { + "running": False, + "exit_code": -1, + "started_at": "2026-11-28T05:31:00Z", + "finished_at": "2026-11-28T05:32:00Z", + } + assert "DO_NOT_RECORD_COMMAND_CONTENT" not in json.dumps(recorded) + + +def test_upload_uses_permission_digits_and_roundtrips_binary_content(tmp_path): + from xtuner.v1.rl.agent_loop.trial_agent_loop.sandbox.client import OpenSandboxClient + from xtuner.v1.rl.agent_loop.trial_agent_loop.sandbox.types import ResourceHandle + + async def scenario(): + uploaded = {} + + async def platform(req): + if req.method == "GET": + return web.Response(body=uploaded["content"]) + parts = await req.multipart() + async for part in parts: + if part.name == "metadata": + uploaded["metadata"] = json.loads(await part.read()) + else: + uploaded["content"] = await part.read() + if uploaded["metadata"]["mode"] != 600: + return web.json_response( + {"code": "INVALID_REQUEST_BODY", "message": "mode contains non-octal digits"}, status=400 + ) + return web.Response(status=200) + + key = tmp_path / "key" + key.write_text("external-test-key") + async with platform_server(platform) as url: + client = OpenSandboxClient( + SandboxConfig(endpoint=url, project="test", credential_file=str(key)), "attempt-1" + ) + handle = ResourceHandle("main", "owned-main", token="exec-token") + try: + assert await client.upload(handle, "/tmp/binary", b"exact\x00payload", timeout=1) is None + assert await client.download(handle, "/tmp/binary", timeout=1) == b"exact\x00payload" + finally: + await client.aclose() + + asyncio.run(scenario()) + + +@pytest.mark.parametrize("stop", ["cancel", "timeout"]) +def test_native_cancel_during_launch_waits_for_id_and_terminal_without_relaunch(tmp_path, stop): + import pytest + + from xtuner.v1.rl.agent_loop.trial_agent_loop.sandbox.types import cmd + from xtuner.v1.rl.observability import Observation, read_report + + async def scenario(): + launch_started, release_id, interrupted, allow_terminal = (asyncio.Event() for _ in range(4)) + launches, deleted, events = [], [], [] + + async def platform(req): + if req.method == "POST" and req.path.endswith("/command"): + body = await req.json() + if body.get("background"): + launches.append(body) + launch_started.set() + await release_id.wait() + event = {"type": "init", "timestamp": 0, "text": "original-id"} + else: + event = {"type": "execution_complete", "timestamp": 0} + return web.Response(text=json.dumps(event) + "\n", content_type="text/event-stream") + if req.method == "DELETE" and req.path.endswith("/command"): + assert req.query["id"] == "original-id" + events.append("interrupt") + interrupted.set() + return web.Response(status=204) + if "/command/status/" in req.path: + if allow_terminal.is_set(): + events.append("terminal") + return web.json_response( + {"running": not allow_terminal.is_set(), "exit_code": 7 if allow_terminal.is_set() else None} + ) + if req.method == "POST": + return web.json_response({"id": "owned-main"}) + if req.method == "DELETE": + events.append("delete") + deleted.append(True) + return web.Response(status=204) + if req.path.endswith("/ping"): + return web.json_response({"ok": True}) + return web.Response(status=404) if deleted else web.json_response({"state": "running"}) + + key = tmp_path / "key" + key.write_text("external-test-key") + async with platform_server(platform) as url: + cfg = SandboxConfig(endpoint=url, project="test", credential_file=str(key), command_mode="native") + + async def attempt(): + async with SandboxRuntime( + ctx=context(tmp_path, verifier=0.1 if stop == "timeout" else 300, request=1), + sandbox_cfg=cfg, + default_resources=ResourceSpec(), + harness=HarnessSpec("mini_swe"), + max_turns=1, + tool_user=None, + tool_env={}, + ) as sb: + main = await sb.acquire("main", image="test") + outcome = await sb.verify(main, command=cmd("sleep", "60"), outputs=[]) + if stop == "timeout": + assert outcome.code == "JOB_TIMEOUT" + + owner = asyncio.create_task(attempt()) + await asyncio.wait_for(launch_started.wait(), 3) + if stop == "cancel": + owner.cancel() + await asyncio.sleep(0.02) + owner.cancel() + else: + await asyncio.sleep(0.15) + release_id.set() + await asyncio.wait_for(interrupted.wait(), 3) + assert not owner.done() + allow_terminal.set() + if stop == "cancel": + with pytest.raises(BaseExceptionGroup) as caught: + await asyncio.wait_for(owner, 3) + assert len(caught.value.exceptions) == 2 + assert all(isinstance(error, asyncio.CancelledError) for error in caught.value.exceptions) + else: + await asyncio.wait_for(owner, 3) + assert len(launches) == 1 + assert events == ["interrupt", "terminal", "delete"] + + with Observation(tmp_path / "observability", {"session_id": "attempt-1"}).activate(): + asyncio.run(scenario()) + report = read_report(tmp_path) + assert report["timing"]["tools/stop_native"]["count"] == 1 + assert next(iter(report["attempts"]["attempt-1"]["jobs"].values()))["return_code"] == 7 + + +def test_cleanup_deletes_resources_in_parallel_under_one_budget(tmp_path): + async def scenario(): + created, deleted = [], [] + + async def platform(req): + if req.method == "POST": + sid = "owned-" + str(len(created)) + created.append(sid) + return web.json_response({"id": sid}) + sid = req.path.split("/")[3] + if req.method == "DELETE": + await asyncio.sleep(0.1) + deleted.append(sid) + return web.Response(status=204) + if req.path.endswith("/ping"): + return web.json_response({"ok": True}) + return web.Response(status=404) if sid in deleted else web.json_response({"state": "running"}) + + key = tmp_path / "key" + key.write_text("external-test-key") + async with platform_server(platform) as url: + cfg = SandboxConfig(endpoint=url, project="test", credential_file=str(key)) + async with SandboxRuntime( + ctx=context(tmp_path, cleanup=0.17), + sandbox_cfg=cfg, + default_resources=ResourceSpec(), + harness=HarnessSpec("mini_swe"), + max_turns=1, + tool_user=None, + tool_env={}, + ) as sb: + await sb.acquire("one", image="test") + await sb.acquire("two", image="test") + assert sorted(deleted) == sorted(created) + assert json.loads((tmp_path / "cleanup.json").read_text())["remaining_ids"] == [] + + asyncio.run(scenario()) + + +def test_cleanup_budget_includes_pending_create_handoff_and_records_unconfirmed_delete(tmp_path): + async def scenario(): + started = asyncio.Event() + deleted = [] + + async def platform(req): + if req.method == "POST": + started.set() + await asyncio.sleep(0.12) + return web.json_response({"id": "late-owned-id"}) + if req.method == "DELETE": + await asyncio.sleep(0.12) + deleted.append(True) + return web.Response(status=204) + return web.Response(status=404) if deleted else web.json_response({"state": "running"}) + + key = tmp_path / "key" + key.write_text("external-test-key") + async with platform_server(platform) as url: + cfg = SandboxConfig(endpoint=url, project="test", credential_file=str(key)) + + async def attempt(): + async with SandboxRuntime( + ctx=context(tmp_path, cleanup=0.2, create_rpc=1), + sandbox_cfg=cfg, + default_resources=ResourceSpec(), + harness=HarnessSpec("mini_swe"), + max_turns=1, + tool_user=None, + tool_env={}, + ) as sb: + await sb.acquire("main", image="test") + + owner = asyncio.create_task(attempt()) + await asyncio.wait_for(started.wait(), 2) + owner.cancel() + with pytest.raises(asyncio.CancelledError): + await owner + cleanup = json.loads((tmp_path / "cleanup.json").read_text()) + assert cleanup["remaining_ids"] == ["late-owned-id"] + assert cleanup["errors"] == ["sandbox cleanup timed out"] + + asyncio.run(scenario()) + + +def test_native_job_preserves_confirmed_sandbox_oom_without_recovery_or_replay(tmp_path): + from time import monotonic + + from mini_agent import Failure + + from xtuner.v1.rl.agent_loop.trial_agent_loop.sandbox.types import cmd + from xtuner.v1.rl.observability import Observation, read_report + + # Captured by local GETs against the original production sandbox/command. + captured = json.loads((Path(__file__).parent / "fixtures/opensandbox/oom_native_status.json").read_text()) + failed = captured["calls"][0]["body"] + native_id = captured["native_command_id"] + sandbox_id = captured["sandbox_id"] + + async def scenario(): + launched, deleted = False, False + launches, interrupts, polls = [], [], [] + + async def platform(req): + nonlocal launched, deleted + if req.path.endswith("/files/upload"): + await req.read() + return web.json_response({"ok": True}) + if req.method == "POST" and req.path.endswith("/command"): + data = await req.json() + if data.get("background"): + launched = True + launches.append(data) + event = {"type": "init", "text": native_id, "timestamp": 0} + else: + event = {"type": "execution_complete", "timestamp": 0} + return web.Response(text=json.dumps(event) + "\n", content_type="text/event-stream") + if "/command/status/" in req.path: + polls.append(req.path) + return web.Response(status=409, text=captured["calls"][2]["body"]) + if req.method == "DELETE" and req.path.endswith("/command"): + interrupts.append(req.path) + return web.Response(status=409) + if req.path.endswith("/ping"): + return web.json_response({"ok": True}) + if req.method == "POST": + return web.json_response({"id": sandbox_id}) + if req.method == "DELETE": + deleted = True + return web.Response(status=204) + if deleted: + return web.Response(status=404) + return web.json_response(failed if launched else {"state": "running"}) + + key = tmp_path / "key" + key.write_text("external-test-key") + observation = Observation(tmp_path / "observability", {"run_id": "native-oom", "session_id": "attempt-1"}) + async with platform_server(platform) as url: + with observation.activate(): + async with SandboxRuntime( + ctx=context(tmp_path, verifier=1, read_recovery=300, cleanup=0.5), + sandbox_cfg=SandboxConfig( + endpoint=url, project="test", credential_file=str(key), command_mode="native" + ), + default_resources=ResourceSpec(), + harness=HarnessSpec("mini_swe"), + max_turns=1, + tool_user=None, + tool_env={}, + ) as sb: + main = await sb.acquire("main", image="test") + started = monotonic() + result = await sb.verify(main, command=cmd("true"), outputs=[]) + assert isinstance(result, Failure) and result.code == "SANDBOX_TERMINATED", result + assert "OOMKilled" in result.detail and "137" in result.detail + assert monotonic() - started < 1 + assert deleted and len(launches) == 1 and len(polls) == 1 and not interrupts + cleanup = json.loads((tmp_path / "cleanup.json").read_text()) + assert cleanup["remaining_ids"] == [] and cleanup["errors"] == [] + report = read_report(tmp_path) + assert report["resources"]["runtime_failures"]["by_cause"] == {"OOMKilled": 1} + + asyncio.run(scenario()) + + +@pytest.mark.parametrize("service_failed", [True, False]) +def test_native_job_stops_for_confirmed_service_oom_but_retains_running_service_unknown(tmp_path, service_failed): + from mini_agent import Failure + + from xtuner.v1.rl.agent_loop.trial_agent_loop.sandbox.types import cmd + from xtuner.v1.rl.observability import Observation, read_report + + captured = json.loads( + (Path(__file__).parent / "fixtures/opensandbox/service_oom_while_main_running.json").read_text() + ) + service = next(item for item in captured if item["resource_name"] == "task-server") + main = next(item for item in captured if item["resource_name"] == "main") + + async def scenario(): + launched, deleted, interrupted = [], set(), [] + main_polls = 0 + + async def platform(req): + nonlocal main_polls + if req.path.endswith("/files/upload"): + await req.read() + return web.json_response({"ok": True}) + if req.path.endswith("/ping"): + return web.json_response({"ok": True}) + if "/endpoints/" in req.path: + return web.json_response({"endpoint": "/service"}) + if req.method == "POST" and req.path.endswith("/command"): + body = await req.json() + if body.get("background"): + kind = "service" if service["sandbox_id"] in req.path else "main" + launched.append(kind) + event = {"type": "init", "text": kind + "-command", "timestamp": 0} + else: + event = {"type": "execution_complete", "timestamp": 0} + return web.Response(text=json.dumps(event) + "\n", content_type="text/event-stream") + if "/command/status/service-command" in req.path: + return web.Response(status=503, text="inactive route") + if "/command/status/main-command" in req.path: + main_polls += 1 + running = not interrupted and (service_failed or main_polls < 2) + return web.json_response({"running": running, "exit_code": None if running else 7}) + if req.method == "DELETE" and req.path.endswith("/command"): + interrupted.append("main" if main["sandbox_id"] in req.path else "service") + return web.Response(status=204) + if req.path.endswith("/logs"): + return web.Response(text="command output") + if req.method == "POST": + body = await req.json() + resource = service if body["image"]["uri"] == "service-image" else main + return web.json_response({"id": resource["sandbox_id"]}) + if req.method == "DELETE": + deleted.add(req.path.rsplit("/", 1)[-1]) + return web.Response(status=204) + sid = req.path.rsplit("/", 1)[-1] + if sid in deleted: + return web.Response(status=404) + if sid == service["sandbox_id"] and "main" in launched and service_failed: + return web.json_response({"state": service["state"], "status": service["status"]}) + return web.json_response({"state": "running"}) + + key = tmp_path / "key" + key.write_text("external-test-key") + observation = Observation(tmp_path / "observability", {"run_id": "service-oom", "session_id": "attempt-1"}) + async with platform_server(platform) as url: + with observation.activate(): + async with SandboxRuntime( + ctx=context(tmp_path, verifier=0.8, read_recovery=300, cleanup=1), + sandbox_cfg=SandboxConfig( + endpoint=url, project="test", credential_file=str(key), command_mode="native" + ), + default_resources=ResourceSpec(), + harness=HarnessSpec("mini_swe"), + max_turns=1, + tool_user=None, + tool_env={}, + ) as sb: + resource = await sb.acquire("task-server", image="service-image") + endpoint = await sb.start_service(resource, command=cmd("service"), port=9111, ready=["ready"]) + assert not isinstance(endpoint, Failure), endpoint + resource = await sb.acquire("main", image="main-image") + result = await sb.verify(resource, command=cmd("main"), outputs=[]) + if service_failed: + assert isinstance(result, Failure) and result.code == "SANDBOX_TERMINATED", result + assert service["sandbox_id"] in result.detail and "OOMKilled" in result.detail + else: + assert result.return_code == 7 and result.files == {}, result + assert launched == ["service", "main"] + assert deleted == {service["sandbox_id"], main["sandbox_id"]} + assert interrupted == (["main"] if service_failed else []) + cleanup = json.loads((tmp_path / "cleanup.json").read_text()) + assert cleanup["remaining_ids"] == [] and cleanup["errors"] == [] + failures = read_report(tmp_path)["resources"]["runtime_failures"] + assert failures["confirmed"] == int(service_failed) + assert failures["by_resource_name"] == ({"task-server": 1} if service_failed else {}) + + asyncio.run(scenario()) + + +def test_native_interrupt_uses_execd_delete_command_contract(tmp_path): + from xtuner.v1.rl.agent_loop.trial_agent_loop.sandbox.client import OpenSandboxClient, OpenSandboxCommands + from xtuner.v1.rl.agent_loop.trial_agent_loop.sandbox.types import ResourceHandle + + async def scenario(): + calls = [] + + async def platform(req): + calls.append((req.method, req.path, dict(req.query))) + # Execd's generated SDK operation uses DELETE /command?id=...; + # the unused adapter constant names a nonexistent POST endpoint. + if req.method == "DELETE" and req.path.endswith("/proxy/44772/command"): + assert req.query["id"] == "26a7fb50efc7409e832534e043b7960c" + return web.Response(status=200) + return web.Response(status=404) + + key = tmp_path / "key" + key.write_text("external-test-key") + async with platform_server(platform) as url: + client = OpenSandboxClient( + SandboxConfig(endpoint=url, project="test", credential_file=str(key)), "attempt-1" + ) + try: + commands = OpenSandboxCommands(client, ResourceHandle("main", "owned-main", token="exec-token"), 1) + assert await commands.interrupt_command("26a7fb50efc7409e832534e043b7960c") is None + finally: + await client.aclose() + assert calls == [ + ("DELETE", "/v1/sandboxes/owned-main/proxy/44772/command", {"id": "26a7fb50efc7409e832534e043b7960c"}) + ] + + asyncio.run(scenario()) + + +@pytest.mark.parametrize( + "command_mode,failed_read", [("native", "artifact"), ("native", "logs"), ("detached", "artifact")] +) +def test_known_job_exit_survives_later_output_read_failure(tmp_path, command_mode, failed_read): + from mini_agent import Failure + from sandbox_http_fixture import SandboxPlatform + + from xtuner.v1.rl.agent_loop.trial_agent_loop.sandbox.types import cmd + from xtuner.v1.rl.observability import Observation, read_report + + async def scenario(): + deleted = False + + async def native_platform(req): + nonlocal deleted + if req.path.endswith("/files/upload"): + await req.read() + return web.json_response({"ok": True}) + if req.method == "POST" and req.path.endswith("/command"): + body = await req.json() + event = ( + {"type": "init", "timestamp": 0, "text": "completed-command"} + if body.get("background") + else {"type": "execution_complete", "timestamp": 0} + ) + return web.Response(text=json.dumps(event) + "\n", content_type="text/event-stream") + if "/command/status/" in req.path: + return web.json_response({"running": False, "exit_code": 7}) + if req.path.endswith("/logs"): + return web.Response(status=500) if failed_read == "logs" else web.Response(text="exit 7") + if req.path.endswith("/files/download"): + return web.Response(status=404) + if req.path.endswith("/ping"): + return web.json_response({"ok": True}) + if req.method == "POST": + return web.json_response({"id": "owned-main"}) + if req.method == "DELETE": + deleted = True + return web.Response(status=204) + return web.Response(status=404) if deleted else web.json_response({"state": "running"}) + + platform = native_platform if command_mode == "native" else SandboxPlatform(tmp_path / "platform") + key = tmp_path / "key" + key.write_text("external-test-key") + observation = Observation(tmp_path / "observability", {"run_id": "known-exit", "session_id": "attempt-1"}) + async with platform_server(platform) as url: + with observation.activate(): + async with SandboxRuntime( + ctx=context(tmp_path, verifier=3), + sandbox_cfg=SandboxConfig( + endpoint=url, project="test", credential_file=str(key), command_mode=command_mode + ), + default_resources=ResourceSpec(), + harness=HarnessSpec("mini_swe"), + max_turns=1, + tool_user=None, + tool_env={}, + ) as sb: + resource = await sb.acquire("main", image="test") + result = await sb.verify(resource, command=cmd("bash", "-c", "exit 7"), outputs=["missing.txt"]) + assert isinstance(result, Failure), result + assert result.code == ("COMMAND_UNKNOWN" if failed_read == "logs" else "RESULT_MISSING"), result + assert json.loads((tmp_path / "cleanup.json").read_text())["remaining_ids"] == [] + report = read_report(tmp_path) + job = next(job for job in report["attempts"]["attempt-1"]["jobs"].values() if job["kind"] == "grader") + assert job["return_code"] == 7 + assert job["error"]["code"] == result.code + + asyncio.run(scenario()) + + +@pytest.mark.parametrize("platform", ["dbox", "hbox"]) +@pytest.mark.parametrize("status", [202, 429, 503]) +def test_create_time_network_policy_and_ready_budget(tmp_path, platform, status): + from mini_agent import Failure + + async def scenario(): + creates, deleted = [], set() + + async def provider(req): + if req.method == "POST": + creates.append(await req.json()) + if status != 202: + return web.json_response({"message": "capacity exhausted"}, status=status) + return web.json_response({"id": "owned", "accessToken": "sat"}, status=202) + if req.method == "DELETE": + deleted.add("owned") + return web.Response(status=204) + if deleted: + return web.Response(status=404) + body = {"state": "pending"} if platform == "dbox" else {"status": {"state": "Pending"}} + return web.json_response(body) + + key = tmp_path / "key" + key.write_text("external-key") + async with platform_server(provider) as url: + async with SandboxRuntime( + ctx=context(tmp_path, attempt=3, ready=0.03, cleanup=1), + sandbox_cfg=SandboxConfig(platform=platform, endpoint=url, project="test", credential_file=str(key)), + default_resources=ResourceSpec(cpus=2, memory_mb=8192), + harness=HarnessSpec("mini_swe"), + max_turns=1, + tool_user=None, + tool_env={}, + ) as rt: + result = await rt.acquire( + "solver", + image="lean-digest", + network_policy={"default_action": "deny", "egress": [{"ref": "model_host"}]}, + ) + assert isinstance(result, Failure) + assert ( + result.code + == {202: "SANDBOX_NOT_READY", 429: "RESOURCE_RATE_LIMITED", 503: "CREATE_FAILED"}[status] + ) + # A repeated acquire observes the original outcome and never replays POST. + assert ( + await rt.acquire( + "solver", + image="lean-digest", + network_policy={"default_action": "deny", "egress": [{"ref": "model_host"}]}, + ) + == result + ) + assert len(creates) == 1 + payload = creates[0] + assert payload["networkPolicy"] == { + "defaultAction": "deny", + "egress": [{"action": "allow", "target": "model"}], + } + if platform == "dbox": + assert payload["extensions"]["sandboxGroup"] == "attempt-1" + assert payload["extensions"]["disableProjectDataMount"] == "true" + else: + assert "extensions" not in payload and payload["lifecycleMinutes"] == 180 + receipts = list(tmp_path.glob("network/*/network_policy.json")) + assert len(receipts) == 1 + policy = json.loads(receipts[0].read_bytes()) + assert policy["http_status"] == status and policy["resource_name"] == "solver" + assert policy["sandbox_id"] == ("owned" if status == 202 else None) + assert policy["time"] > 0 + assert deleted == ({"owned"} if status == 202 else set()) + + asyncio.run(scenario()) + + +def test_unsupported_policy_backend_fails_without_a_post(tmp_path): + async def scenario(): + calls = [] + + async def provider(req): + calls.append(req.method) + return web.Response(status=500) + + key = tmp_path / "key" + key.write_text("external-key") + async with platform_server(provider) as url: + async with SandboxRuntime( + ctx=context(tmp_path), + sandbox_cfg=SandboxConfig( + backend="env_gateway", endpoint=url, project="test", credential_file=str(key) + ), + default_resources=ResourceSpec(cpus=1), + harness=HarnessSpec("mini_swe"), + max_turns=1, + tool_user=None, + tool_env={}, + ) as rt: + with pytest.raises(ValueError, match="create-time network policy"): + await rt.acquire("judge", image="lean", network_policy={"default_action": "deny", "egress": []}) + assert calls == [] + + asyncio.run(scenario()) + + +def named_task(*, shared=False, service_box=None): + from xtuner.v1.rl.agent_loop.trial_agent_loop.sandbox.types import RESULT_DIR, WORKSPACE, cmd, service_url + + boxes = {name: {"image": "same-digest", "release": "after_last_use"} for name in ("solver", "judge", "unused")} + prep = {"solver": {"workspace": "/workspace"}, "judge": {"workspace": "/review"}} + services = [] + if service_box: + boxes.setdefault(service_box, {"image": "same-digest", "release": "after_last_use"}) + prep.setdefault(service_box, {"workspace": "/lookup"}) + services = [ + { + "name": "lookup", + "sandbox": service_box, + "command": cmd("serve-fixture", WORKSPACE), + "port": 8080, + "ready": ["true"], + } + ] + return { + "sandboxes": boxes, + "prepare": prep, + "services": services, + "run_agent": {"sandbox": "solver", "outputs": {"candidate": "work/a"}}, + "verify": { + "sandbox": "solver" if shared else "judge", + "command": cmd("grade-fixture", RESULT_DIR, *([service_url("lookup")] if service_box else [])), + "inputs": {"input/b": "candidate", "input/c": "candidate"}, + "outputs": ["grade.json"], + }, + "grade_options": {}, + } + + +async def run_named_trial(tmp_path, data, platform, *, strict=True): + from types import SimpleNamespace + + from xtuner.v1.rl.agent_loop.trial_agent_loop.trial.sandbox_trial import SandboxTrialConfig + from xtuner.v1.rl.observability import Observation + + async def finish(*_): + platform.settled = True + + def decode(evidence, options): + import hashlib + + expected = hashlib.sha256(platform.proof).hexdigest() + assert evidence.input_sha256 == {"input/b": expected, "input/c": expected} + # Both required releases have already reached GET 404 before decoder runs. + assert set(platform.files) == platform.deleted + return json.loads(evidence.files["grade.json"])["score"] + + key = tmp_path / "key" + key.write_text("external-key") + async with platform_server(platform) as url: + cfg = SandboxTrialConfig( + sandbox=SandboxConfig(endpoint=url, project="test", credential_file=str(key), command_mode="native"), + harness=HarnessSpec("mini_swe"), + decode_grade=decode, + require_clean_exit=strict, + ) + task = TaskInput.from_dict(json.loads(json.dumps(TaskInput(("test", "named"), "solve", data).to_dict()))) + ctx = TrialContext( + task, + "named-sid", + tmp_path / "attempt", + Budgets(attempt=2, agent=1, cleanup=0.06, request=1), + ModelSettings("http://model", "named-sid", "test", {}, SequenceLimits(100, 100, 10)), + SimpleNamespace(finish_agent_session=SimpleNamespace(remote=finish)), + ) + with Observation(tmp_path / "observability", {"run_id": "named", "session_id": "named-sid"}).activate(): + return await cfg.build(ctx).run() + + +@pytest.mark.parametrize( + "shared,service_box,count", + [(True, None, 1), (False, None, 2), (False, "solver", 2), (False, "judge", 2), (False, "third", 3)], +) +@pytest.mark.parametrize("proof", [b"proof\r\n", b""]) +def test_named_trial_reuses_resources_services_and_hands_off_original_bytes( + tmp_path, shared, service_box, count, proof +): + from named_sandbox_http_fixture import NamedSandboxPlatform + + from xtuner.v1.rl.agent_loop.trial_agent_loop.trial.base import TrialResult + + platform = NamedSandboxPlatform(proof=proof) + result = asyncio.run(run_named_trial(tmp_path, named_task(shared=shared, service_box=service_box), platform)) + assert result == TrialResult(1, "MaxTurns", ["observed-a", "observed-b"]) + assert len(platform.creates) == len(set(platform.deletes)) == count + assert len({payload["env"]["EXECD_ACCESS_TOKEN"] for payload in platform.creates}) == count + assert sum("mini_agent.worker" in command for _, command in platform.commands.values()) == 1 + assert [ + blob + for files in platform.files.values() + for path, blob in files.items() + if path.endswith(("/input/b", "/input/c")) + ] == [proof, proof] + assert (tmp_path / "attempt/snapshot/work/a").read_bytes() == proof + cleanup = json.loads((tmp_path / "attempt/cleanup.json").read_bytes()) + assert cleanup["errors"] == [] and cleanup["remaining_ids"] == [] + assert len(cleanup["released_resources"]) == count + if service_box: + owner = next( + payload for payload in platform.creates if any(port["containerPort"] == 8080 for port in payload["ports"]) + ) + assert owner["image"]["uri"] == "same-digest" + if not shared and not service_box: + paths = platform.calls + assert ( + paths.index(("DELETE", "/v1/sandboxes/box0")) + < [i for i, call in enumerate(paths) if call == ("POST", "/v1/sandboxes")][1] + ) + + +@pytest.mark.parametrize( + "fault,expected,count", + [ + ("release-box0", "RESOURCE_RELEASE_UNCONFIRMED", 1), + ("release-box1", "RESOURCE_RELEASE_UNCONFIRMED", 2), + ("missing", "ARTIFACT_MISSING", 1), + ], +) +def test_named_trial_blocks_following_stage_or_score_on_missing_evidence(tmp_path, fault, expected, count): + from mini_agent import Failure + from named_sandbox_http_fixture import NamedSandboxPlatform + + platform = NamedSandboxPlatform(fault=fault) + result = asyncio.run(run_named_trial(tmp_path, named_task(), platform)) + assert isinstance(result, Failure) and result.code == expected + assert len(platform.creates) == count and len(platform.deleted) == count + assert json.loads((tmp_path / "attempt/cleanup.json").read_bytes())["errors"] == [] + + +@pytest.mark.parametrize( + "fault", + [ + "unknown", + "duplicate-port", + "forward-service", + "unbound-artifact", + "source-path", + "target-path", + "mixed", + "old-format", + "invalid-port-type", + "invalid-release", + "invalid-image-type", + "static-collision", + "no-workspace", + ], +) +def test_task_spec_rejects_invalid_declarations_before_creating(tmp_path, fault): + from mini_agent import Failure + from named_sandbox_http_fixture import NamedSandboxPlatform + + from xtuner.v1.rl.agent_loop.trial_agent_loop.sandbox.types import cmd, service_url + + data = named_task(service_box="solver") + if fault == "unknown": + data["verify"]["sandbox"] = "missing" + elif fault == "duplicate-port": + data["services"].append({**data["services"][0], "name": "second"}) + elif fault == "forward-service": + data["services"][0]["command"] = cmd("serve-fixture", service_url("lookup")) + elif fault == "unbound-artifact": + data["verify"]["inputs"]["input/b"] = "missing" + elif fault == "source-path": + data["run_agent"]["outputs"]["candidate"] = "../a" + elif fault == "target-path": + data["verify"]["inputs"]["/absolute"] = "candidate" + elif fault == "mixed": + data["main"] = {} + elif fault == "old-format": + data = {"main": {}, "services": [], "verifier": {}, "grade_options": {}} + elif fault == "invalid-port-type": + data["services"][0]["port"] = True + elif fault == "invalid-release": + data["sandboxes"]["solver"]["release"] = "now" + elif fault == "invalid-image-type": + data["sandboxes"]["solver"]["image"] = 1234 + elif fault == "static-collision": + data["verify"]["command"]["files"]["input/b"] = str(tmp_path / "private-grader") + else: + data["prepare"].pop("solver") + platform = NamedSandboxPlatform() + result = asyncio.run(run_named_trial(tmp_path, data, platform)) + assert isinstance(result, Failure) and result.code == "TRIAL_EXECUTION_EXCEPTION" + assert platform.calls == [] + + +def test_agent_input_binding_detects_tampered_snapshot(tmp_path): + import hashlib + + from mini_agent import Failure + + from xtuner.v1.rl.agent_loop.trial_agent_loop.trial.sandbox_trial import bind_agent_inputs + + path = tmp_path / "snapshot/work/a" + path.parent.mkdir(parents=True) + path.write_bytes(b"original") + (tmp_path / "snapshot_sha256.json").write_text(json.dumps({"work/a": hashlib.sha256(b"original").hexdigest()})) + path.write_bytes(b"changed") + outcome = bind_agent_inputs(tmp_path, {"candidate": "work/a"}, {"work/a": str(path)}, {"input/b": "candidate"}) + assert isinstance(outcome, Failure) and outcome.code == "SNAPSHOT_MISMATCH" + + +def test_explicit_release_receives_late_id_and_stops_only_readiness(tmp_path): + from mini_agent import Failure + + async def scenario(): + started, handoff = asyncio.Event(), asyncio.Event() + posts, deleted = [], [] + + async def provider(req): + if req.method == "POST": + posts.append(await req.json()) + started.set() + await handoff.wait() + return web.json_response({"id": "late-owned"}) + if req.method == "DELETE": + deleted.append("late-owned") + return web.Response(status=204) + return web.Response(status=404) if deleted else web.json_response({"state": "pending"}) + + key = tmp_path / "key" + key.write_text("external-key") + async with platform_server(provider) as url: + async with SandboxRuntime( + ctx=context(tmp_path, cleanup=1, create_rpc=1), + sandbox_cfg=SandboxConfig(endpoint=url, project="test", credential_file=str(key)), + default_resources=ResourceSpec(), + harness=HarnessSpec("mini_swe"), + max_turns=1, + tool_user=None, + tool_env={}, + require_clean_exit=True, + ) as rt: + acquisition = asyncio.create_task(rt.acquire("solver", image="lean")) + await started.wait() + release = asyncio.create_task(rt.release("solver")) + handoff.set() + assert await release is None + result = (await asyncio.gather(acquisition, return_exceptions=True))[0] + assert isinstance(result, (asyncio.CancelledError, Failure)) + assert await rt.release("solver") is None + with pytest.raises(ValueError, match="already released"): + await rt.acquire("solver", image="lean") + assert len(posts) == 1 and deleted == ["late-owned"] + cleanup = json.loads((tmp_path / "cleanup.json").read_bytes()) + assert cleanup["errors"] == [] and cleanup["released_resources"]["solver"]["source"] == "explicit" + assert rt.cleanup_failure is None + + asyncio.run(scenario()) + + +def test_twice_cancelled_explicit_release_waits_for_the_original_delete(tmp_path): + from named_sandbox_http_fixture import NamedSandboxPlatform + + async def scenario(): + platform = NamedSandboxPlatform(fault="cancel-delete") + owner = asyncio.create_task(run_named_trial(tmp_path, named_task(), platform)) + await asyncio.wait_for(platform.delete_started.wait(), 2) + owner.cancel() + await asyncio.sleep(0) + owner.cancel() + platform.finish_delete.set() + with pytest.raises(asyncio.CancelledError): + await owner + assert len(platform.creates) == 1 and platform.deletes == ["box0"] + cleanup = json.loads((tmp_path / "attempt/cleanup.json").read_bytes()) + assert cleanup["released_resources"]["solver"]["source"] == "explicit" and cleanup["errors"] == [] + + asyncio.run(scenario()) + + +@pytest.mark.parametrize("strict,unknown", [(False, False), (True, False), (True, True)]) +def test_strict_exit_uses_cleanup_evidence_without_claiming_ttl_as_deletion(tmp_path, strict, unknown): + async def scenario(): + async def provider(req): + if req.method == "POST": + return web.Response(status=503) if unknown else web.json_response({"id": "owned"}) + if req.method == "DELETE": + return web.Response(status=503) + if req.path.endswith("/ping"): + return web.json_response({"ok": True}) + return web.json_response({"state": "running"}) + + key = tmp_path / "key" + key.write_text("external-key") + async with platform_server(provider) as url: + rt = SandboxRuntime( + ctx=context(tmp_path, cleanup=0.03, sandbox_ttl=60), + sandbox_cfg=SandboxConfig(endpoint=url, project="test", credential_file=str(key)), + default_resources=ResourceSpec(), + harness=HarnessSpec("mini_swe"), + max_turns=1, + tool_user=None, + tool_env={}, + require_clean_exit=strict, + ) + + async def execute(): + async with rt: + await rt.acquire("solver", image="lean") + + if unknown: + with pytest.raises(RuntimeError, match="isolation unconfirmed"): + await execute() + else: + await execute() + assert (rt.cleanup_failure.code if rt.cleanup_failure else None) == ( + "SANDBOX_CLEANUP_UNCONFIRMED" if strict else None + ) + cleanup = json.loads((tmp_path / "cleanup.json").read_bytes()) + assert cleanup["released_resources"] == {} + assert bool(cleanup["unresolved_creates"]) == unknown + + asyncio.run(scenario()) + + +@pytest.mark.parametrize("split", [False, True]) +def test_documented_named_task_and_custom_build(tmp_path, split): + import re + from types import SimpleNamespace + + from mini_agent import Failure + from named_sandbox_http_fixture import NamedSandboxPlatform + + from xtuner.v1.rl.agent_loop.trial_agent_loop.sandbox.types import cmd + from xtuner.v1.rl.agent_loop.trial_agent_loop.trial.base import TrialResult + from xtuner.v1.rl.agent_loop.trial_agent_loop.trial.sandbox_trial import SandboxTrial, SandboxTrialConfig + + repo = Path(__file__).resolve().parents[2] + readme = repo / "xtuner/v1/rl/agent_loop/trial_agent_loop/README.md" + (raw,) = re.findall(r"```json\n(.*?)\n```", readme.read_text(), re.S) + row = json.loads(raw) + task = TaskInput.from_dict(row["extra_info"]["task"]) + if split: + task.data["sandboxes"]["judge"] = {"image": "same-digest", "release": "after_last_use"} + task.data["verify"]["sandbox"] = "judge" + platform = NamedSandboxPlatform() + assert asyncio.run(run_named_trial(tmp_path, task.data, platform)) == TrialResult( + 1, "MaxTurns", ["observed-a", "observed-b"] + ) + assert len(platform.creates) == (2 if split else 1) + + # This is the documented task-specific build(ctx) extension, using the same public lifecycle. + class CheckTrial(SandboxTrial): + async def run_task(self, task, rt): + handle = await rt.acquire("review", image=task.data["image"]) + if isinstance(handle, Failure): + return handle + evidence = await rt.verify(handle, command=cmd("grade-fixture"), outputs=["grade.json"]) + if isinstance(evidence, Failure): + return evidence + return TrialResult(json.loads(evidence.files["grade.json"])["score"], observed_request_ids=[]) + + class CheckConfig(SandboxTrialConfig): + def build(self, ctx): + return CheckTrial(self, ctx) + + async def custom(): + external = NamedSandboxPlatform() + async with platform_server(external) as url: + cfg = CheckConfig( + sandbox=SandboxConfig( + endpoint=url, project="test", credential_file=str(tmp_path / "key"), command_mode="native" + ), + harness=HarnessSpec("mini_swe"), + ) + custom_task = TaskInput.from_dict( + {"key": ["example", "check"], "instruction": "", "data": {"image": "same-digest"}} + ) + ctx = TrialContext( + custom_task, + "custom", + tmp_path / "custom", + Budgets(request=1, cleanup=1), + ModelSettings("http://model", "custom", "example", {}, SequenceLimits(100, 100, 10)), + SimpleNamespace(), + ) + assert await cfg.build(ctx).run() == TrialResult(1, observed_request_ids=[]) + assert len(external.creates) == 1 and external.deleted == {"box0"} + + asyncio.run(custom()) diff --git a/tests/rl/test_service_endpoint.py b/tests/rl/test_service_endpoint.py new file mode 100644 index 0000000000..ef792215c9 --- /dev/null +++ b/tests/rl/test_service_endpoint.py @@ -0,0 +1,56 @@ +"""Control-plane TLS must not turn HBox's plain HTTP task ports into HTTPS.""" + +import asyncio + +import httpx +import pytest + +from xtuner.v1.rl.agent_loop.trial_agent_loop.sandbox.client import make_sandbox_client +from xtuner.v1.rl.agent_loop.trial_agent_loop.sandbox.types import ResourceHandle, SandboxConfig + + +@pytest.mark.parametrize( + "platform,address,expected", + [ + ("hbox", "100.98.1.2:9111", "http://100.98.1.2:9111"), + ("dbox", "100.98.1.2:9111", "https://100.98.1.2:9111"), + ("hbox", "https://task.example:9111", "https://task.example:9111"), + ("hbox", "http://task.example:9111", "http://task.example:9111"), + ("hbox", "control.example/brainbox/v1/proxy/9111", "https://control.example/brainbox/v1/proxy/9111"), + ("hbox", "/brainbox/v1/proxy/9111", "https://control.example/brainbox/v1/proxy/9111"), + ], +) +def test_service_address_keeps_business_and_control_protocols_separate(tmp_path, platform, address, expected): + async def scenario(): + key = tmp_path / "key" + key.write_text("external-key") + client = make_sandbox_client( + SandboxConfig( + platform=platform, + endpoint="https://control.example/brainbox", + project="test", + credential_file=str(key), + ), + "service-test", + ) + + def platform_response(request): + assert request.method == "GET" + assert str(request.url).startswith("https://control.example/brainbox/v1/sandboxes/owned/endpoints/9111") + assert request.headers["OPEN-SANDBOX-API-KEY"] == "external-key" + assert request.url.params.get("project") == ("test" if platform == "hbox" else None) + return httpx.Response(200, json={"endpoint": address}) + + # Only the external platform HTTP transport is substituted. Resolution, + # project selection and the public client call use the production path. + await client.http.aclose() + client.http = httpx.AsyncClient( + transport=httpx.MockTransport(platform_response), headers={"OPEN-SANDBOX-API-KEY": "external-key"} + ) + try: + endpoint = await client.resolve_endpoint(ResourceHandle("task-server", "owned"), 9111, timeout=2) + assert endpoint == expected + finally: + await client.aclose() + + asyncio.run(scenario()) diff --git a/tests/rl/test_trial_context.py b/tests/rl/test_trial_context.py new file mode 100644 index 0000000000..09523bd8d4 --- /dev/null +++ b/tests/rl/test_trial_context.py @@ -0,0 +1,100 @@ +"""One reusable config binds independent inputs in the actual executing loop.""" + +import asyncio +import json +import os +import sys + +import pytest +import ray +from mini_agent import ModelSettings, SequenceLimits +from test_attempt_ray import cpu_ray # noqa: F401 + +from xtuner.v1.rl.agent_loop.trial_agent_loop.trial import ( + Budgets, + ResourceSpec, + TaskInput, + Trial, + TrialConfig, + TrialContext, + TrialResult, +) +from xtuner.v1.rl.agent_loop.trial_agent_loop.trial.execution import start_trial + + +class InputTrial(Trial): + def __init__(self, cfg, ctx): + super().__init__(cfg, ctx) + self.build_loop = asyncio.get_running_loop() + self.build_pid = os.getpid() + + async def run(self): + ctx = self.ctx + # A constructor outside the executing loop/process cannot satisfy this. + assert self.build_loop is asyncio.get_running_loop() + assert self.build_pid == os.getpid() + await asyncio.sleep(0.01) + ctx.output_dir.mkdir(exist_ok=True) + (ctx.output_dir / "input.json").write_text( + json.dumps( + { + "task": ctx.task.to_dict(), + "sid": ctx.session_id, + "model_sid": ctx.model.session_id, + "sampling": ctx.model.sampling, + "output_dir": str(ctx.output_dir), + "resources": self.cfg.resolve_task_resources(ctx.task.resources).to_dict(), + "pid": self.build_pid, + } + ) + ) + return TrialResult(ctx.task.data["score"], observed_request_ids=[ctx.session_id + "-turn"]) + + +class InputConfig(TrialConfig): + def build(self, ctx): + return InputTrial(self, ctx) + + +@pytest.mark.parametrize("dispatch_mode", ["local", "ray_task"]) +def test_reused_config_keeps_each_context_independent(cpu_ray, tmp_path, dispatch_mode): # noqa: F811 + ray.cloudpickle.register_pickle_by_value(sys.modules[__name__]) + + async def scenario(): + cfg = InputConfig(default_resources=ResourceSpec(cpus=2, memory_mb=1024)) + before = cfg.model_dump() + contexts = [ + TrialContext( + task=TaskInput(("test", str(index)), f"solve-{index}", {"score": index}, ResourceSpec(cpus=index + 3)), + session_id=f"sid-{index}", + output_dir=tmp_path / f"trial-{index}", + budgets=Budgets(attempt=10), + model=ModelSettings( + "http://unused", + f"sid-{index}", + "model", + {"sampling_seed": index + 42}, + SequenceLimits(100, 100, 10), + ), + rollout_ctl=None, + ) + for index in range(2) + ] + results = await asyncio.gather( + *(start_trial(cfg, ctx, dispatch_mode=dispatch_mode, trial_cpus=0.5) for ctx in contexts) + ) + assert results == [TrialResult(index, observed_request_ids=[f"sid-{index}-turn"]) for index in range(2)] + assert cfg.model_dump() == before + for index, ctx in enumerate(contexts): + record = json.loads((ctx.output_dir / "input.json").read_text()) + assert record["task"] == ctx.task.to_dict() + assert record["sid"] == record["model_sid"] == ctx.session_id + assert record["sampling"] == {"sampling_seed": index + 42} + assert record["output_dir"] == str(ctx.output_dir) + assert record["resources"] == {"cpus": index + 3, "memory_mb": 1024, "storage_mb": None} + assert (record["pid"] == os.getpid()) is (dispatch_mode == "local") + + try: + asyncio.run(scenario()) + finally: + ray.cloudpickle.unregister_pickle_by_value(sys.modules[__name__]) diff --git a/xtuner/v1/rl/agent_loop/__init__.py b/xtuner/v1/rl/agent_loop/__init__.py index 41ac11fe6e..bf4905e4b6 100644 --- a/xtuner/v1/rl/agent_loop/__init__.py +++ b/xtuner/v1/rl/agent_loop/__init__.py @@ -28,16 +28,24 @@ "get_agent_loop_rollout_ctl", ] -try: - from .localhost_agent_loop.agent_in_localhost_loop import AgentInLocalhostLoop, AgentInLocalhostLoopConfig - from .sandbox_agent_loop.agent_in_sandbox_loop import AgentInSandboxLoop, AgentInSandboxLoopConfig -except ModuleNotFoundError as exc: - if exc.name != "lagent" and "lagent" not in str(exc): - raise -else: - __all__ += [ - "AgentInLocalhostLoop", - "AgentInLocalhostLoopConfig", - "AgentInSandboxLoop", - "AgentInSandboxLoopConfig", - ] + +# Legacy runtimes are optional; importing the new sandbox contracts must not +# import their Lagent dependencies as a side effect. +def __getattr__(name: str): + from importlib import import_module + + modules = { + "AgentInLocalhostLoop": "localhost_agent_loop.agent_in_localhost_loop", + "AgentInLocalhostLoopConfig": "localhost_agent_loop.agent_in_localhost_loop", + "AgentInSandboxLoop": "sandbox_agent_loop.agent_in_sandbox_loop", + "AgentInSandboxLoopConfig": "sandbox_agent_loop.agent_in_sandbox_loop", + } + module = modules.get(name) + if module is None: + raise AttributeError(name) + value = getattr(import_module(f"{__name__}.{module}"), name) + globals()[name] = value + return value + + +__all__ += ["AgentInLocalhostLoop", "AgentInLocalhostLoopConfig", "AgentInSandboxLoop", "AgentInSandboxLoopConfig"] diff --git a/xtuner/v1/rl/agent_loop/trial_agent_loop/README.md b/xtuner/v1/rl/agent_loop/trial_agent_loop/README.md new file mode 100644 index 0000000000..a146b7bc54 --- /dev/null +++ b/xtuner/v1/rl/agent_loop/trial_agent_loop/README.md @@ -0,0 +1,126 @@ +# Sandbox Trial 执行 + +可复用的 `TrialConfig` 保存静态策略,`TrialContext` 携带本次 task、SID、模型设置、输出目录、预算与控制面句柄。实际执行进程调用 `cfg.build(ctx).run()`,不再单独传 task,也不把活跃 Trial 或客户端传过 Ray。 + +| 职责 | 模块 | +| --- | --- | +| 共同任务、资源与Trial契约 | `.trial.base` | +| 独立CPU任务与父端所有权 | `.trial.execution` | +| 默认线性Trial | `.trial.sandbox_trial` | +| 平台契约、生命周期与I/O | `.sandbox.types`、`.sandbox.runtime`、`.sandbox.jobs`、`.sandbox.client` | + +旧链路继续使用 `agent_loop.sandbox_agent_loop` 自己的Runner和Ray适配,不重导出新接口;历史冻结源码保持原样。 + +```python +from xtuner.v1.rl.agent_loop.trial_agent_loop.trial import TrialContext + +# trial_cfg 可预先创建并复用;task、SID 和采样参数只在每次执行中绑定。 +ctx = TrialContext( + task=task, session_id=sid, model=model, + output_dir=output_dir, budgets=budgets, rollout_ctl=rollout_ctl, +) +result = await trial_cfg.build(ctx).run() +# 生产侧使用 execute_trial(trial_cfg, ctx, dispatch_mode=..., trial_cpus=...), +# 由其保留总期限、原 Trial 取消与模型兜底结算。 +``` + +## 开发一个沙盒任务 + +优先在任务包实现 `build_task(row) -> TaskInput` 与 `decode_grade(evidence, options) -> float | Failure`。默认线性流程先启动声明的服务,再运行 Agent,最后评分。具名资源的放置、文件交接与释放分别声明。缺少可复用的宿主能力时,小幅扩展字段或原语,并同时验证同箱、分箱;执行顺序由任务动态决定时,在任务包覆写 `run_task`。公共层不按数据集、镜像或题型选分支。 + +```mermaid +flowchart LR + A["任务 JSONL / build_task"] --> B["默认 SandboxTrial.run_task"] + B --> C["Runtime 五个原语与资源账本"] + C --> D["所需释放已确认"] + D --> E["任务 decode_grade"] +``` + +下列完整 JSONL 行使用本仓 CPU HTTP 夹具的镜像与命令;公开回归 `test_documented_named_task_and_custom_build` 会直接读取它。真实任务替换镜像、公开 setup 和私有 grader 即可。`prompt` 供采样器使用,`extra_info.task` 经 `TaskInput.from_dict` 还原,`key` 是题的两个字符串;一次尝试的 SID 由调用方绑定。 + +```json +{"data_source":"example","prompt":[{"role":"user","content":"solve"}],"extra_info":{"task":{"key":["example","named"],"instruction":"solve","resources":null,"data":{"sandboxes":{"solver":{"image":"same-digest","release":"after_last_use"}},"prepare":{"solver":{"workspace":"/workspace"}},"services":[],"run_agent":{"sandbox":"solver","outputs":{"candidate":"work/a"}},"verify":{"sandbox":"solver","command":{"argv":["grade-fixture"],"cwd":".","bundle":null,"files":{},"env":{}},"inputs":{"input/b":"candidate","input/c":"candidate"},"outputs":["grade.json"]},"grade_options":{}}}}} +``` + +| 字段 | 语义 | +| --- | --- | +| `TaskInput.resources` | 样本覆盖;每字段优先级为沙盒资源、样本资源、配方 `default_resources` | +| `sandboxes[name]` | 必填 image;可选 resources、network_policy、release。默认 release 为 on_exit;after_last_use 要求阶段末确认删除 | +| `network_policy` | `{default_action: "deny", egress: [{ref: "model_host"}]}` 在首次 OpenSandbox POST 生效;空 egress 为全拒绝。env_gateway 不支持此字段 | +| `prepare[name]` | 本箱 workspace、可选 setup/public_bundle;首次实际使用时准备一次。Agent 必须声明工作区 | +| `services[]` | name 为服务引用名,sandbox 为资源名;另含 command、port、ready。端口在首次创建前汇总;只允许引用已 ready 服务 | +| `run_agent` | sandbox 选择工作区;outputs 为产物别名到规范相对源路径的映射 | +| `verify` | sandbox、command、outputs 必填;inputs 为私有 job 相对目的路径到产物别名的映射。outputs 仍可使用容器绝对路径 | +| `grade_options` | 只传给任务 decoder 的 JSON 数据 | + +改成分箱,只需增加资源并改评分引用;同一个镜像也会取得独立 ID 与实例凭据。solver 的快照读回、SHA 校验、GET 404 完成后,才首次创建 judge: + +```python +data = row["extra_info"]["task"]["data"] +data["sandboxes"]["judge"] = {"image": "same-digest", "release": "after_last_use"} +data["verify"]["sandbox"] = "judge" +# input/b 与 input/c 消费相同原始 bytes;judge 不借用 solver 的 WORKSPACE。 +task = TaskInput.from_dict(row["extra_info"]["task"]) +result = await cfg.build(ctx).run() # ctx.task=task;示例配置见测试。 +``` + +五个业务原语均异步,预期执行错误返回 `Failure`;调用方立即结束本次业务流程,由父 `run()` 完成根清理。内部不一致继续抛出,不把失败转成 0 分。 + +| 原语 | 参数与成功返回 | +| --- | --- | +| `acquire(name, *, image, ports=(), resources=None, network_policy=None)` | `ResourceHandle`;同名规格必须一致,已释放名称不可重开;未用定义零创建 | +| `prepare(resource, *, workspace, public_bundle=None, setup=None, services={})` | `PreparedWorkspace`;本箱工作区,public_bundle 需要 setup | +| `start_service(resource, *, command, port, ready, services={}, workspace=None)` | ready 后的 URL;服务可与 Agent/评分共享或独占沙盒,并保持到评分结束 | +| `run_agent(workspace, instruction, *, outputs=())` | `AgentResult(report, artifacts)`;先停工具、结算模型,再快照相对路径;空文件合法,缺文件失败 | +| `verify(resource, *, command, outputs, workspace=None, services={}, inputs=None)` | `GradeEvidence(return_code, files, input_sha256)`;对选定 handle 运行一个 grader job,inputs 是宿主 bytes | + +宿主 `release(name) -> Failure | None` 与退出共用同一资源账本;OpenSandbox 只有 GET 404 才记成功。显式屏障失败停止后续阶段,最终追删不能补发被拒绝的分数。`require_clean_exit=True` 还要求完整根回执;默认 False 保持旧任务语义。根 `cleanup.json` 唯一,`released_resources` 保留逻辑名、真实 ID、确认时间、来源 explicit/close 与确认方式。TTL 可证明 SID 隔离,不能证明已删除。创建、释放、根清理与重复取消均等待原操作,不重放 POST。 + +默认 Trial 只接受上面的具名格式。`TaskSpec` 校验字段类型及跨字段引用,首次 POST 前拒绝未知沙盒、服务端口冲突、未就绪的服务引用和未生产的产物。现有编译器直接输出该格式,没有旧格式适配器或中间执行计划。 + +`run_task` 按固定顺序执行服务、Agent 和 verify。唯一 `_use(name, rt)` 入口负责懒创建和工作区准备:同名只做一次。Agent 与 verifier 分箱且 Agent 箱没有常驻服务时,其 `after_last_use` 释放紧随快照交接;同箱及服务箱保持到 verify 结束。之后释放所有已打开且声明 `after_last_use` 的资源,再解码分数。未使用定义零创建,`on_exit` 留给 Runtime 根清理。 + +文件交接拒绝路径冲突,并核对本 SID 的 `snapshot_sha256.json`;`verification_inputs.json` 记录实际发送字节的 SHA。decoder 核对 GradeEvidence 后照实返回合法 0 或 1,评分协议错误返回 Failure。生产 Trial 保留原 AgentReport 的 terminal 和 observed_request_ids,不从文本重建模型请求。 + +仅当任务有专属执行顺序时,配置 `build(ctx)` 返回子类。下面是没有在线 Agent 的离线检查最小例子,同样复用父 `run()` 的唯一 Runtime 与根清理: + +```python +class CheckTrial(SandboxTrial): + async def run_task(self, task, rt): + handle = await rt.acquire("review", image=task.data["image"]) + if isinstance(handle, Failure): + return handle + evidence = await rt.verify(handle, command=cmd("grade-fixture"), outputs=["grade.json"]) + if isinstance(evidence, Failure): + return evidence + return TrialResult(json.loads(evidence.files["grade.json"])["score"], observed_request_ids=[]) + +class CheckConfig(SandboxTrialConfig): + def build(self, ctx): + return CheckTrial(self, ctx) +``` + +例子使用 [公开 HTTP 行为测试](../../../../../tests/rl/test_sandbox_runtime_v3.py) 与 [平台夹具](../../../../../tests/rl/named_sandbox_http_fixture.py),无需外部设计仓或数学数据。自定义流程含在线 Agent 时,必须继续使用 `run_agent` 的工具停止/模型结算屏障,并保留真实报告。创建预算 `Budgets.create_rpc` 只管原创建交接,`ready=None` 默认沿用 attempt;配置 ready 可独立限制就绪。 + +```mermaid +flowchart LR + A["TaskInput 与 TrialContext"] --> B["独立 CPU Ray task"] + B --> C["Trial:服务与工作区准备"] + C --> D["worker 与工具树收尾"] + D --> E["模型会话结算"] + E --> F["私有验证与原始评分"] + F --> G["资源删除及 cleanup.json"] +``` + +- `SandboxTrialConfig` 适用于标准线性流程,任务配方提供 `decode_grade`;复杂任务可以覆盖 `run_task`。资源按字段合并:样本配置优先,其余来自任务集默认值。 +- `execute_trial(..., dispatch_mode="ray_task", trial_cpus=1)` 在模型 placement group 之外运行,不申请 GPU、不自动重放。Ray 排队计入父端 Attempt 总时长;重复取消仍等待原 task 终态。worker 需要能导入配方并访问共享输入和输出路径。业务开始前写入唯一启动交接标记;取消后的 worker 丢失也可能被 Ray 标成 C++ `TASK_CANCELLED`,已启动的此类模糊回执必须上抛。 +- `execute_trial`在提交前计算总期限,直接用剩余预算等待原任务;超时或外层中断后先请求取消,再完成执行和模型结算。local先发起模型结算,与Trial收尾并行;Ray先等待原远端Trial及其finally,再发起父端兜底结算。 +- 结果归并区分原执行异常、执行等待者取消、模型结算异常和模型等待者取消。仅在已记录总超时或外层中断时忽略原work的预期取消;其他真实异常按原顺序保留。 +- `SandboxConfig` 只描述平台连接与命令能力。OpenSandbox 和 env-gateway 均支持窄 I/O;`command_mode="native"` 显式启用 OpenSandbox 命令 ID,不依赖 PID/rc 文件,失败后不切回另一种启动方式。默认 detached 路径复用 #2333 的独立有界观测。 +- OpenSandbox明确创建429仍返回`RESOURCE_RATE_LIMITED`、无分数并沿用占槽退避,保留至多2048字符的服务端响应正文用于区分配额或限流原因;不重放创建、不把它误报为未知创建。正文缺失的历史429保留原因未知,不能用后来的配额快照反推具体维度。 +- HBox直连接口使用`backend="opensandbox"`、`platform="hbox"`、`command_mode="native"`,endpoint为`https://h.pjlab.org.cn/brainbox`。平台适配只在XTuner客户端内完成,不修改OpenSandbox SDK:控制面附加项目查询参数,代理面使用服务端SAT且不附加project,状态由`status.state`归一化;资源使用`resources`、TTL转为`lifecycleMinutes`。默认`platform="dbox"`保留原连接行为。真实HBox已验证文件往返、原生命令非零退出与日志、SWE私有评分和删除。 +- HBox返回的裸`PodIP:port`业务地址使用HTTP,不继承控制面的HTTPS;显式协议、带路径的代理地址和DBox行为保留。真实Gym双沙箱复现确认仅改scheme即可使原setup成功;公开地址契约见`test_service_endpoint.py`。 +- 时间参数统一为秒数。父端拥有 Attempt 总超时;阶段拥有者用一次外层超时覆盖启动、轮询与收集。创建交接和全部并发删除共用一次 cleanup 预算,连接关闭另限 2 秒。记录未确认删除的 ID 与未拿到 ID 的创建操作,平台 TTL 提供最终回收。 +- `Budgets.model_request` 控制 worker 单次模型 HTTP 的总等待,包含换权期间的准入等待和后端生成;未指定时沿用 `request`。长训练批次应覆盖这两个服务端预算之和,平台命令、文件和状态 RPC 继续使用 `request`。 +- 平台 RPC 的外层总预算是唯一取消期限,HTTP 库默认读超时不能提前截断文件上传等调用;原生状态轮询保留短预算,一次性终态日志读取使用调用方请求预算。真实 HTTP 回归见 `test_platform_rpc_and_native_logs_use_requested_deadline`。 +- `run_agent` 成功返回前停止工具、调用 `TrialContext.finish_session()` 并快照产物,之后才投放验证器。模型结算接口由会话组件提供;缺失或未结算会阻止判分,不能用空实现绕过。 diff --git a/xtuner/v1/rl/agent_loop/trial_agent_loop/__init__.py b/xtuner/v1/rl/agent_loop/trial_agent_loop/__init__.py new file mode 100644 index 0000000000..a38f426889 --- /dev/null +++ b/xtuner/v1/rl/agent_loop/trial_agent_loop/__init__.py @@ -0,0 +1 @@ +"""Trial-based native Agent orchestration.""" diff --git a/xtuner/v1/rl/agent_loop/trial_agent_loop/admission.py b/xtuner/v1/rl/agent_loop/trial_agent_loop/admission.py new file mode 100644 index 0000000000..b3aba256fe --- /dev/null +++ b/xtuner/v1/rl/agent_loop/trial_agent_loop/admission.py @@ -0,0 +1,201 @@ +"""One event loop's quota admission ledger; no platform or worker dependencies.""" + +from __future__ import annotations + +import asyncio +import json +import logging +import time +from collections.abc import Awaitable, Callable +from contextlib import asynccontextmanager +from dataclasses import dataclass +from math import floor, isfinite + + +@dataclass(frozen=True) +class QuotaSnapshot: + at: float + free: tuple[float, float, float] # CPU cores, GiB, sandbox count. + hbox: bool = False + + +class QuotaUnavailable(Exception): + def __init__(self, reason: str): + self.reason = reason + super().__init__(reason) + + +@dataclass(eq=False) +class Ticket: + started: float + ended: float | None = None + + +class AdaptiveConcurrencyGate: + def __init__( + self, + maximum: int, + cost: tuple[float, float, int] | None, + probe: Callable[[], Awaitable[QuotaSnapshot]] | None, + *, + mono: Callable[[], float] = time.monotonic, + utc: Callable[[], float] = time.time, + unseen_ttl_s: float = 180.0, + context: dict | None = None, + ): + if isinstance(maximum, bool) or not isinstance(maximum, int) or maximum <= 0: + raise ValueError("maximum must be a positive integer") + if probe is not None and (cost is None or len(cost) != 3 or any(not isfinite(v) or v <= 0 for v in cost)): + raise ValueError("quota admission requires three positive finite costs") + self.max, self.cost, self.probe = maximum, cost, probe + self.mono, self.utc, self.unseen_ttl_s = mono, utc, unseen_ttl_s + self.context = dict(context or {}) + self.logger = logging.getLogger(__name__) + self.limit, self.n, self.waiters = (0 if probe else 1), 0, 0 + self.mode, self.credit = ("cold", 0) if probe else ("passive", None) + self.next_tick = self.cool_until = 0.0 + self.last_stamp = self.last_raw = self.last_k = None + self.last_free = None + self.observed_zero = False + self.unseen: set[Ticket] = set() + self.polling = self.success = False + self.alarm = None + self.changed = asyncio.Event() + self.health = None + self.rate_limited_count = 0 + + def pulse(self): + old, self.changed = self.changed, asyncio.Event() + old.set() + + def tick_due(self): + self.alarm = None + self.pulse() + + def control(self, mode, limit, reason): + if self.mono() < self.cool_until: + limit = min(limit, self.limit) + health = "ok" if reason in {"fresh", "same_snapshot", "no_reader", "create_429"} else reason + if (mode, limit, health) != (self.mode, self.limit, self.health) or reason == "create_429": + event = { + **self.context, + "event": "adaptive_sandbox_admission", + "old_mode": self.mode, + "mode": mode, + "reason": reason, + "old_limit": self.limit, + "limit": limit, + "in_flight": self.n, + "waiters": self.waiters, + "free": self.last_free, + "cost": self.cost, + "credit": self.credit, + "unseen": len(self.unseen), + "snapshot_at": self.last_stamp, + "age_s": None if self.last_stamp is None else self.utc() - self.last_stamp, + "cooldown_s": max(0, self.cool_until - self.mono()), + "rate_limited_count": self.rate_limited_count, + } + self.logger.info(f"sandbox admission {self.mode} -> {mode} {json.dumps(event, sort_keys=True)}") + self.mode, self.limit, self.health = mode, limit, health + + def fresh(self, snapshot: QuotaSnapshot): + if self.last_stamp is not None and snapshot.at < self.last_stamp: + raise QuotaUnavailable("out_of_order") + if snapshot.at == self.last_stamp: + self.control("quota", self.limit, "same_snapshot") + return + raw = min(floor(f / d) for f, d in zip(snapshot.free, self.cost)) + k = min(raw, self.last_raw or 0) if snapshot.hbox else raw + if raw == 0 or k > 0: + self.observed_zero = raw == 0 + cut = snapshot.at - 2 + # 新合法水位才清除过老预留:平台可能已计账,但外部释放掩盖了余量下降。 + self.unseen = { + t for t in self.unseen if (t.ended is None or t.ended > cut) and t.started > cut - self.unseen_ttl_s + } + eligible = sorted((t for t in self.unseen if t.started <= cut), key=lambda t: t.started) + fall = max(0, self.last_k - raw) if self.last_raw is not None else 0 + self.unseen.difference_update(eligible[:fall]) + self.last_stamp, self.last_raw, self.last_k = snapshot.at, raw, k + self.last_free = snapshot.free + usable = max(1, k * 9 // 10) if k else 0 + spare = usable - len(self.unseen) + self.credit = max(0, spare) + self.control("quota", max(0, min(self.max, self.n + spare, self.limit + 8)), "fresh") + + def passive(self, ceiling, reason): + first = self.mode != "passive" + base = 1 if first else self.limit + int(self.success and self.mono() >= self.cool_until) + self.credit = None + self.control("passive", min(self.max, ceiling, max(1, base)), reason) + + async def refresh(self): + if self.probe is None: + self.passive(self.max, "no_reader") + return + try: + self.fresh(await self.probe()) + except QuotaUnavailable as exc: + # 坏快照不能认领活票,也不能解除已确认的零容量。 + self.unseen = {t for t in self.unseen if t.ended is None or t.ended > self.utc() - 92} + self.last_raw = None + recent = self.last_stamp is not None and self.utc() - self.last_stamp <= 90 + if self.observed_zero or recent: + self.credit = (self.credit or 0) if recent else 0 + self.control("hold", self.limit if self.credit else min(self.limit, self.n), exc.reason) + else: + self.passive(4, exc.reason) + + @asynccontextmanager + async def acquire(self): + self.waiters += 1 + try: + while True: + if not self.polling and self.mono() >= self.next_tick: + self.polling, self.next_tick = True, self.mono() + 20 + try: + await self.refresh() + self.success = False + finally: + self.polling = False + self.pulse() + continue + credit_ok = self.credit is None or ( + self.credit > 0 and self.last_stamp is not None and self.utc() - self.last_stamp <= 90 + ) + if not self.polling and self.mono() >= self.cool_until and self.n < self.limit and credit_ok: + ticket = Ticket(started=self.utc()) + if self.probe is not None: + self.unseen.add(ticket) + if self.credit is not None: + self.credit -= 1 + self.n += 1 # 检查与扣票之间不 await,全部样本共享这一笔本地额度。 + break + if not self.polling and self.alarm is None: + wake_at = min(self.next_tick, self.cool_until) if self.mono() < self.cool_until else self.next_tick + self.alarm = asyncio.get_running_loop().call_later(max(0, wake_at - self.mono()), self.tick_due) + await self.changed.wait() + finally: + self.waiters -= 1 + if not self.waiters and self.alarm is not None: + self.alarm.cancel() + self.alarm = None + try: + yield + finally: + ticket.ended = self.utc() + self.n -= 1 + self.pulse() + + def on_rate_limited(self): + first = self.mono() >= self.cool_until + self.cool_until, self.success = self.mono() + 40, False + self.rate_limited_count += 1 + if first: + self.control(self.mode, max(1, self.limit // 2) if self.limit else 0, "create_429") + self.pulse() + + def on_success(self): + if self.mono() >= self.cool_until: + self.success = True diff --git a/xtuner/v1/rl/agent_loop/trial_agent_loop/error_handling.py b/xtuner/v1/rl/agent_loop/trial_agent_loop/error_handling.py new file mode 100644 index 0000000000..505a41227b --- /dev/null +++ b/xtuner/v1/rl/agent_loop/trial_agent_loop/error_handling.py @@ -0,0 +1,175 @@ +"""Decisions and diagnostics for failed sample production, independent of tracing.""" + +from __future__ import annotations + +import logging +import time +from collections import Counter, deque +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any + +from pydantic import BaseModel, ConfigDict, Field + + +if TYPE_CHECKING: + from xtuner.v1.data_proto.rl_data import RolloutState + from xtuner.v1.rl.agent_loop.trial_agent_loop.trial.base import TrialContext + + +logger = logging.getLogger(__name__) +PRODUCTION_GROUP_FIELD = "trial_production_group" +PRODUCER_MODEL_STEP_FIELD = "producer_model_step" + + +def record_production_exception( + exc: Exception, + *, + phase: str, + ctx: TrialContext, + isolation: dict[str, Any], + command_ids: dict[str, str | None] | None = None, + request_ids: list[str] | None = None, + exported: list | None = None, +) -> None: + # Only emit known identifiers for reproduction. Prompts, task data, URLs and + # credentials can contain private materials and are not part of this record. + request_ids = list(request_ids or ()) + versions: set[int] = set() + for part in exported if isinstance(exported, list) else (): + if not isinstance(part, dict): + continue + if isinstance(part.get("response_model_steps"), list): + versions.update(step for step in part["response_model_steps"] if type(step) is int) + if isinstance(part.get("request_ids"), list): + request_ids.extend(rid for rid in part["request_ids"] if isinstance(rid, str)) + fields = { + "sid": ctx.session_id, + "phase": phase, + "task": ctx.task.key, + "model": ctx.model.name, + "producer_model_step": ctx.producer_model_step, + "response_model_steps": sorted(versions), + "command_ids": command_ids or {}, + "request_ids": list(dict.fromkeys(request_ids)), + "reproduction": {"sampling_seed": ctx.model.sampling.get("sampling_seed"), "output_dir": str(ctx.output_dir)}, + "isolation": isolation, + } + logger.error( + "Rollout production exception %s", + fields, + extra={"production_exception": fields}, + exc_info=(type(exc), exc, exc.__traceback__), + ) + + +class NoProgressBudget(BaseModel): + model_config = ConfigDict(extra="forbid", frozen=True) + + max_consecutive_discards: int = Field(default=128, gt=0) + max_active_seconds: float = Field(default=12 * 3600, gt=0, allow_inf_nan=False) + + +@dataclass(frozen=True) +class ProductionFailure: + sid: int | None + phase: str + code: str + + +@dataclass(frozen=True) +class ProductionGroup: + attempts: int + sid: int | None + failures: list[ProductionFailure] + + @classmethod + def from_samples(cls, samples: list[RolloutState]) -> ProductionGroup: + # TITO siblings share a SID. Capture failures before group admission + # removes rejected attempts, including across a Ray result boundary. + attempts: dict[int | None, RolloutState] = {} + for sample in samples: + attempts.setdefault(sample.session_id, sample) + failures = [ + ProductionFailure(sid, failure["phase"], failure["code"]) + for sid, sample in attempts.items() + if (failure := sample.extra_fields.get("agent_failure")) + ] + return cls(len(attempts), samples[0].session_id if samples else None, failures) + + +class ProductionProgress: + """Per-task ledger shared by the producer's consecutive scheduling windows.""" + + def __init__(self, budget: NoProgressBudget) -> None: + self.budget = budget + self.attempts = 0 + self.failures_by_phase: Counter[str] = Counter() + self.consecutive_discards = 0 + self.recent_failures: deque[ProductionFailure] = deque(maxlen=5) + self.last_batch_at: float | None = None + self._active_groups = 0 + self._active_since = 0.0 + self._active_seconds = 0.0 + + def start_group(self) -> None: + if not self._active_groups: + self._active_since = time.monotonic() + self._active_groups += 1 + + def finish_group(self) -> None: + self._active_groups -= 1 + if not self._active_groups: + self._active_seconds += time.monotonic() - self._active_since + + def take_group(self, samples: list[RolloutState]) -> ProductionGroup: + summary = None + for sample in samples: + summary = sample.extra_fields.pop(PRODUCTION_GROUP_FIELD, None) or summary + return summary if summary is not None else ProductionGroup.from_samples(samples) + + def record_group(self, group: ProductionGroup, *, rejected: str | None = None) -> None: + self.attempts += group.attempts + self.failures_by_phase.update(failure.phase for failure in group.failures) + if rejected is None: + self.consecutive_discards = 0 + else: + self.consecutive_discards += 1 + if not group.failures and group.attempts: + self.failures_by_phase["producer"] += group.attempts + self.recent_failures.extend(group.failures or [ProductionFailure(group.sid, "producer", rejected)]) + + def can_refill(self, *, task_name: str, pending: int) -> bool: + elapsed = self._active_seconds + if self._active_groups: + elapsed += time.monotonic() - self._active_since + exhausted = self.consecutive_discards >= self.budget.max_consecutive_discards or ( + self.consecutive_discards > 0 and elapsed >= self.budget.max_active_seconds + ) + if not exhausted: + return True + # Let the original groups settle and use any trainable results they + # deliver before deciding whether the producer must stop. + if pending: + return False + message = ( + f"ROLLOUT_NO_PROGRESS task={task_name} active_seconds={elapsed:.2f} " + f"consecutive_discards={self.consecutive_discards} last_batch_at={self.last_batch_at} " + f"failed_attempt_rates={self._failure_rates()} recent_failures={list(self.recent_failures)}" + ) + logger.error(message) + raise RuntimeError(message) + + def record_batch(self, task_name: str, *, batch_logger: logging.Logger) -> None: + self.last_batch_at = time.time() + batch_logger.info( + f"Rollout production task={task_name} attempts={self.attempts} " + f"failed_attempt_rates={self._failure_rates()} consecutive_discards={self.consecutive_discards} " + f"last_batch_at={self.last_batch_at}" + ) + self.consecutive_discards = 0 + self.recent_failures.clear() + self._active_seconds = 0.0 + self._active_since = time.monotonic() + + def _failure_rates(self) -> dict[str, float]: + return {phase: count / self.attempts for phase, count in self.failures_by_phase.items()} diff --git a/xtuner/v1/rl/agent_loop/trial_agent_loop/observation.py b/xtuner/v1/rl/agent_loop/trial_agent_loop/observation.py new file mode 100644 index 0000000000..b866e76868 --- /dev/null +++ b/xtuner/v1/rl/agent_loop/trial_agent_loop/observation.py @@ -0,0 +1,118 @@ +"""V3 adapter: preserve execution facts before trace admission can replace a result.""" + +from __future__ import annotations + +import functools +from dataclasses import asdict +from pathlib import Path + +from mini_agent import Failure + +from xtuner.v1.rl.observability import ( + current_observation, + exception_fields, +) + + +def decode_worker_observation(metadata: dict) -> list[dict] | None: + """Validate optional timing metadata without changing the core worker report.""" + phases = metadata.get("phases") + if ( + metadata.get("schema_version") != 1 + or not isinstance(phases, list) + or any( + not isinstance(item, dict) + or not isinstance(item.get("phase"), str) + or type(item.get("duration_s")) not in (int, float) + for item in phases + ) + ): + return None + return phases + + +def record_worker_observation(metadata: dict | None, *, job_id: str, sandbox_id: str) -> None: + """Project optional worker timings separately from the validated business report.""" + observation = current_observation() + if observation is None or observation.directory is None: + return + if metadata is None: + observation.emit("worker_observation_missing", job_id=job_id, reason="not_in_result") + return + phases = decode_worker_observation(metadata) + if phases is None: + observation.emit("worker_observation_missing", job_id=job_id, reason="invalid_metadata") + return + for item in phases: + observation.emit( + "phase_finished", + **{k: item[k] for k in ("phase", "duration_s", "status", "error", "inclusive") if k in item}, + attributes={"source": "worker_report", "job_id": job_id, "sandbox_id": sandbox_id}, + ) + + +def record_artifact(output_dir: Path, job, name: str, content: bytes) -> None: + """Retain each downloaded file without changing the job's business result.""" + observation = current_observation() + if observation is None or observation.directory is None: + return + directory = output_dir / f"job-{job.id}.artifacts" + index = len(job.artifact_paths) + len(job.artifact_errors) + path = directory / f"{index}-{Path(name).name}" + try: + directory.mkdir(exist_ok=True) + path.write_bytes(content) + job.artifact_paths[name] = str(path) + except OSError as exc: + job.artifact_errors[name] = f"{type(exc).__name__}: {exc}" + + +def record_job_finished(output_dir: Path, job, error) -> None: + observation = current_observation() + if observation is None or observation.directory is None: + return + paths = { + name + "_path": str(path) if path.is_file() else None + for name, path in { + "stdout": output_dir / f"job-{job.id}.stdout", + "stderr": output_dir / f"job-{job.id}.stderr", + "diagnostic": output_dir / f"job-{job.id}.json", + }.items() + } + observation.emit( + "job_finished", + job_id=job.id, + kind=job.kind, + sandbox_id=job.resource.id, + native_command_id=job.command_id, + return_code=job.return_code, + error=error, + artifact_paths=job.artifact_paths, + artifact_errors=job.artifact_errors, + **paths, + ) + + +def observe_job(fn): + @functools.wraps(fn) + async def run(self, job, *args, **kwargs): + observation = current_observation() + if observation is None or observation.directory is None: + return await fn(self, job, *args, **kwargs) + identity = {"job_id": job.id, "kind": job.kind, "sandbox_id": job.resource.id} + observation.emit("job_started", **identity) + result, error = None, None + try: + with observation.phase("job/" + job.kind, **identity) as span: + result = await fn(self, job, *args, **kwargs) + if isinstance(result, Failure): + span.fail(result) + error = asdict(result) + return result + except BaseException as exc: + error = exception_fields(exc) + raise + finally: + record_job_finished(self.ctx.output_dir, job, error) + + return run diff --git a/xtuner/v1/rl/agent_loop/trial_agent_loop/sandbox/__init__.py b/xtuner/v1/rl/agent_loop/trial_agent_loop/sandbox/__init__.py new file mode 100644 index 0000000000..f4480bd6db --- /dev/null +++ b/xtuner/v1/rl/agent_loop/trial_agent_loop/sandbox/__init__.py @@ -0,0 +1 @@ +"""Explicit modules for the native Agent execution path.""" diff --git a/xtuner/v1/rl/agent_loop/trial_agent_loop/sandbox/client.py b/xtuner/v1/rl/agent_loop/trial_agent_loop/sandbox/client.py new file mode 100644 index 0000000000..0fe32b76b3 --- /dev/null +++ b/xtuner/v1/rl/agent_loop/trial_agent_loop/sandbox/client.py @@ -0,0 +1,833 @@ +"""Narrow OpenSandbox transport; no SDK or legacy runtime at import time.""" + +from __future__ import annotations + +import asyncio +import base64 +import json +import time +from dataclasses import dataclass +from datetime import datetime, timezone +from math import ceil, isfinite +from pathlib import Path +from typing import Callable, Mapping, Sequence, TypeAlias +from urllib.parse import quote, urljoin, urlsplit, urlunsplit + +import httpx +from mini_agent import Failure, JsonObject, JsonValue + +from xtuner.v1.rl.agent_loop.trial_agent_loop.admission import QuotaSnapshot, QuotaUnavailable +from xtuner.v1.rl.agent_loop.trial_agent_loop.sandbox.types import ( + GatewayCluster, + NetworkPolicy, + ResourceHandle, + SandboxConfig, +) +from xtuner.v1.rl.agent_loop.trial_agent_loop.trial.base import ResourceSpec +from xtuner.v1.rl.observability import current_observation, observe_phase +from xtuner.v1.rl.observability.sandbox_http import HTTP_EVENT_HOOKS, record_command_status + + +UploadFileField: TypeAlias = tuple[str, tuple[str, bytes | str, str]] + + +async def read_project_quota(sandbox_cfg: SandboxConfig, quota_tenant: str | None = None) -> QuotaSnapshot: + """One bounded read, separate from owned sandbox lifecycle clients.""" + started = time.time() + try: + key = Path(sandbox_cfg.credential_file).read_text().strip() + if not key: + raise QuotaUnavailable("credential_empty") + endpoint = sandbox_cfg.endpoint.rstrip("/") + parsed = urlsplit(endpoint) + if parsed.scheme not in {"http", "https"} or not parsed.hostname or parsed.query or parsed.fragment: + raise QuotaUnavailable("invalid_endpoint") + if sandbox_cfg.backend != "opensandbox": + raise QuotaUnavailable("unsupported_backend") + if sandbox_cfg.platform == "hbox": + if not quota_tenant: + raise QuotaUnavailable("tenant_missing") + url = endpoint + f"/v1/tenants/{quote(quota_tenant, safe='')}/quotas/{quote(sandbox_cfg.project, safe='')}" + headers = {"Authorization": "Basic " + base64.b64encode(key.encode()).decode()} + params = None + else: + url = endpoint + "/v1/resource-quotas" + headers = {"OPEN-SANDBOX-API-KEY": key} + params = {"project": sandbox_cfg.project} + async with asyncio.timeout(3): + async with httpx.AsyncClient(trust_env=False, follow_redirects=False, timeout=None) as client: + response = await client.get(url, params=params, headers=headers) + response.raise_for_status() + body = response.json() + if sandbox_cfg.platform == "hbox": + ledger = body["admissionAvailable"]["manual"] + raw = [ledger[k] for k in ("cpuCores", "memoryGi", "pods")] + stamp = body.get("updatedAt") + else: + ledger = body["container"] + values = [ + ledger[side][k] for side in ("quota", "usage") for k in ("cpuRequest", "memoryRequest", "sandboxes") + ] + if any(type(v) not in (int, float) or not isfinite(v) for v in values): + raise QuotaUnavailable("invalid_resources") + raw = [values[i] - values[i + 3] for i in range(3)] + stamp = ledger["updatedAt"] + if any(type(v) not in (int, float) or not isfinite(v) for v in raw) or raw[2] != int(raw[2]): + raise QuotaUnavailable("invalid_resources") + if stamp is None and sandbox_cfg.platform == "hbox": + at = started + else: + dt = datetime.fromisoformat(stamp) + if dt.tzinfo is None or dt.utcoffset().total_seconds() != 0: + raise QuotaUnavailable("invalid_timestamp") + at = dt.timestamp() + if not 0 <= datetime.now(timezone.utc).timestamp() - at <= 90: + raise QuotaUnavailable("stale_timestamp") + return QuotaSnapshot(at, tuple(max(0, v) for v in raw), hbox=sandbox_cfg.platform == "hbox") + except QuotaUnavailable: + raise + except httpx.HTTPStatusError as exc: + raise QuotaUnavailable(f"http_{exc.response.status_code}") from None + except (TimeoutError, httpx.TimeoutException): + raise QuotaUnavailable("timeout") from None + except Exception as exc: + # 只记录异常分类,认证值、报文与路径均不进入准入日志;取消不属于 Exception。 + raise QuotaUnavailable(type(exc).__name__) from None + + +def _response_object(response: httpx.Response, phase: str) -> JsonObject | Failure: + """Decode only external JSON here; callers still own interface-specific fields.""" + try: + body = response.json() + if not isinstance(body, dict): + raise ValueError("expected JSON object") + return body + except (ValueError, UnicodeDecodeError) as exc: + return Failure("SANDBOX_RESPONSE_INVALID", phase, str(exc)) + + +def _format_k8s_resources(res: ResourceSpec) -> JsonObject: + """将统一数值 ResourceSpec 转换为 OpenSandbox / env-gateway 所需的 K8s 风格字段。""" + out: JsonObject = {} + if res.cpus is not None: + out["cpu"] = str(res.cpus) + if res.memory_mb is not None: + out["memory"] = f"{res.memory_mb}Mi" + if res.storage_mb is not None: + out["ephemeral-storage"] = f"{res.storage_mb}Mi" + return out + + +@dataclass(frozen=True) +class ExecOutput: + return_code: int + stdout: str + stderr: str + + +def decode_create_response(resp: httpx.Response, op_id: str) -> tuple[str, str] | Failure: + """Preserve rejected, rate-limited and unknown create outcomes for the ledger.""" + if resp.status_code >= 500: + return Failure("CREATE_FAILED", "create", f"{op_id}: HTTP {resp.status_code}") + if resp.status_code == 429: + # Preserve the provider's reason for diagnosis without changing the + # known rejection/cooldown contract or replaying the create request. + return Failure("RESOURCE_RATE_LIMITED", "create", f"429: {resp.text[:2048]}") + if not resp.is_success: + return Failure("CREATE_REJECTED", "create", str(resp.status_code)) + try: + body: JsonObject = resp.json() + sid: JsonValue = body["id"] + if not isinstance(sid, str) or not sid: + raise TypeError("sandbox id must be a nonempty str") + return sid, "" + except (ValueError, KeyError, TypeError) as exc: + return Failure("CREATE_FAILED", "create", f"{op_id}: invalid create response: {type(exc).__name__}: {exc}") + + +def decode_execd_event(line: str) -> JsonObject | None: + """Decode one SSE data event; completion still belongs to the stream owner.""" + if not line or line.startswith((":", "event:", "id:", "retry:")): + return None + event = json.loads(line[5:].strip() if line.startswith("data:") else line) + if not isinstance(event, dict): + raise TypeError("execd event must be an object") + return event + + +def decode_command_status(status: JsonObject, sandbox_id: str, command_id: str) -> dict[str, bool | int | None]: + """Decode bool running and an optional real rc; missing/negative rc stays visible.""" + running, rc = status["running"], status.get("exit_code") + if type(running) is not bool or (rc is not None and type(rc) is not int): + record_command_status(sandbox_id, command_id, "invalid_status", status) + raise ValueError("invalid command status") + if not running and rc is None: + record_command_status(sandbox_id, command_id, "not_running_without_exit_code", status) + elif not running and rc < 0: + # Preserve provider timing for unexplained worker exits such + # as -1; the original value still reaches the job owner. + record_command_status(sandbox_id, command_id, "negative_exit_code", status) + return {"running": running, "return_code": rc} + + +class OpenSandboxClient: + def __init__(self, cfg: SandboxConfig, session_id: str) -> None: + self.cfg: SandboxConfig = cfg + self.base_url: str = cfg.endpoint.rstrip("/") + self.project: str = cfg.project + self.session_id: str = session_id + api_key: str = Path(cfg.credential_file).read_text().strip() + self.http: httpx.AsyncClient = httpx.AsyncClient( + headers={"OPEN-SANDBOX-API-KEY": api_key}, timeout=20.0, trust_env=False, event_hooks=HTTP_EVENT_HOOKS + ) + + def proxy_headers(self, handle: ResourceHandle) -> dict[str, str]: + return {"X-EXECD-ACCESS-TOKEN": handle.token} + + async def get_info(self, sandbox_id: str, *, timeout: float) -> JsonObject | Failure: + response = await self._req("GET", f"/v1/sandboxes/{sandbox_id}", timeout=timeout) + if isinstance(response, Failure): + return response + if not response.is_success: + return Failure("SANDBOX_IO", "http", f"GET sandbox: HTTP {response.status_code}") + return _response_object(response, "monitor") + + async def _req( + self, + method: str, + path: str, + *, + timeout: float, + json_body: JsonObject | None = None, + headers: Mapping[str, str] | None = None, + params: Mapping[str, str] | None = None, + files: Sequence[UploadFileField] | None = None, + ) -> httpx.Response | Failure: + try: + async with asyncio.timeout(timeout): + return await self.http.request( + method, + self.base_url + path, + json=json_body, + headers=headers, + params=params, + files=files, + # The caller's total RPC budget owns cancellation; HTTPX's + # client default must not impose an earlier read deadline. + timeout=None, + ) + except (httpx.HTTPError, TimeoutError) as exc: + return Failure("SANDBOX_IO", "http", f"{method} {path}: {type(exc).__name__}") + + @observe_phase("sandbox/create", failure=Failure) + async def create( + self, + *, + image: str, + ports: tuple[int, ...], + resources: ResourceSpec, + ttl: float, + token: str, + op_id: str, + timeout: float, + network_policy: NetworkPolicy | None = None, + on_status: Callable[[int], None] | None = None, + ) -> tuple[str, str] | Failure: + exposed: list[int] = sorted({18080, 44772, *ports}) + resp = await self._req( + "POST", + "/v1/sandboxes", + timeout=timeout, + json_body={ + **({"networkPolicy": network_policy.to_payload()} if network_policy is not None else {}), + "image": {"uri": image}, + "entrypoint": ["sleep", "inf"], + "timeout": int(ttl), + "resourceRequests": _format_k8s_resources(resources), + "ports": [{"containerPort": p, "name": f"p{p}", "protocol": "tcp"} for p in exposed], + "env": {"EXECD_ACCESS_TOKEN": token}, + "extensions": { + "project": self.project, + "sandboxGroup": self.session_id, + "runtimeClassName": "sysbox-runc", + "disableProjectDataMount": "true", + }, + "metadata": {"purpose": "agent-rl-" + self.session_id, "operation_id": op_id}, + }, + ) + if isinstance(resp, Failure): + return Failure("CREATE_FAILED", "create", f"{op_id}: {resp.code}/{resp.phase}: {resp.detail}") + if on_status is not None: + on_status(resp.status_code) + return decode_create_response(resp, op_id) + + @observe_phase("sandbox/ready", failure=Failure) + async def wait_ready(self, handle: ResourceHandle, *, timeout: float) -> Failure | None: + try: + async with asyncio.timeout(timeout): + while True: + info = await self.get_info(handle.id, timeout=5.0) + if isinstance(info, Failure) and info.code == "SANDBOX_RESPONSE_INVALID": + return info + if not isinstance(info, Failure): + state = info.get("state") + if not isinstance(state, str): + return Failure("SANDBOX_RESPONSE_INVALID", "create", "state must be str") + if state == "failed": + return Failure("SANDBOX_NOT_READY", "create", handle.id) + if state == "running": + ping = await self._req( + "GET", + f"/v1/sandboxes/{handle.id}/proxy/44772/ping", + headers=self.proxy_headers(handle), + timeout=5.0, + ) + if not isinstance(ping, Failure) and ping.is_success: + return None + await asyncio.sleep(1.0) + except TimeoutError: + return Failure("SANDBOX_NOT_READY", "create", handle.id) + + def effective_expiry(self, ttl: float) -> int | None: + """Return the positive expiry in seconds actually sent to this platform.""" + seconds = int(ttl) + return seconds if seconds > 0 else None + + async def delete(self, sandbox_id: str, *, timeout: float) -> Failure | None: + scope = asyncio.timeout(timeout) + try: + async with scope: + await self._req("DELETE", f"/v1/sandboxes/{sandbox_id}", timeout=timeout) + while True: + obs = await self._req("GET", f"/v1/sandboxes/{sandbox_id}", timeout=timeout) + if not isinstance(obs, Failure) and obs.status_code == 404: + return None + await asyncio.sleep(0.5) + except TimeoutError: + if not scope.expired(): + raise + return Failure("DELETE_FAILED", "delete", sandbox_id) + + async def aclose(self) -> None: + await self.http.aclose() + + async def exec(self, handle: ResourceHandle, command: str, *, cwd: str, timeout: float) -> ExecOutput | Failure: + stdout: list[str] = [] + stderr: list[str] = [] + completed = False + return_code = 0 + try: + async with asyncio.timeout(timeout): + async with self.http.stream( + "POST", + f"{self.base_url}/v1/sandboxes/{handle.id}/proxy/44772/command", + headers=self.proxy_headers(handle), + json={"command": command, "cwd": cwd, "timeout": max(1, int(timeout * 1000))}, + timeout=None, + ) as response: + response.raise_for_status() + # execd emits one JSON object per data line. The terminal + # event is mandatory; a dropped stream never implies rc=0. + async for line in response.aiter_lines(): + event = decode_execd_event(line) + if event is None: + continue + kind = event["type"] + if kind == "stdout": + stdout.append(event["text"]) + elif kind == "stderr": + stderr.append(event["text"]) + elif kind == "error": + # execd's error event is terminal by itself and uses wire + # aliases, not the SDK object's normalized names. + return_code = int(event["error"]["evalue"]) + completed = True + elif kind == "execution_complete": + completed = True + except (httpx.HTTPError, TimeoutError, ValueError, TypeError, KeyError) as exc: + return Failure("COMMAND_UNKNOWN", "command", type(exc).__name__) + if not completed: + return Failure("COMMAND_UNKNOWN", "command", "missing execd completion event") + return ExecOutput(return_code, "".join(stdout), "".join(stderr)) + + async def resolve_endpoint(self, handle: ResourceHandle, port: int, *, timeout: float) -> str | Failure: + resp = await self._req("GET", f"/v1/sandboxes/{handle.id}/endpoints/{port}", timeout=timeout) + if isinstance(resp, Failure) or not resp.is_success: + return Failure("SERVICE_NOT_READY", "service", handle.name) + try: + raw_ep: JsonValue = resp.json()["endpoint"] + if not isinstance(raw_ep, str) or not raw_ep: + return Failure("SERVICE_NOT_READY", "service", "empty endpoint") + except (ValueError, KeyError, TypeError) as exc: + return Failure("SERVICE_NOT_READY", "service", str(exc)) + if raw_ep.startswith("/"): + return urljoin(self.base_url + "/", raw_ep) + scheme = urlsplit(self.base_url).scheme + # HBox's bare Pod IP ports serve plain HTTP; TLS belongs to its control + # and proxy URLs. An explicit scheme or proxy path keeps its own protocol. + if self.cfg.platform == "hbox" and "/" not in raw_ep: + scheme = "http" + return raw_ep if "://" in raw_ep else f"{scheme}://{raw_ep}" + + async def upload(self, handle: ResourceHandle, path: str, content: bytes, *, timeout: float) -> Failure | None: + resp = await self._req( + "POST", + f"/v1/sandboxes/{handle.id}/proxy/44772/files/upload", + timeout=timeout, + headers=self.proxy_headers(handle), + files=[ + ("metadata", ("metadata", json.dumps({"path": path, "mode": 600}), "application/json")), + ("file", (path, content, "application/octet-stream")), + ], + ) + if isinstance(resp, Failure): + return resp + return None if resp.is_success else Failure("UPLOAD_FAILED", "upload", str(resp.status_code)) + + async def download(self, handle: ResourceHandle, path: str, *, timeout: float) -> bytes | None | Failure: + resp = await self._req( + "GET", + f"/v1/sandboxes/{handle.id}/proxy/44772/files/download", + timeout=timeout, + headers=self.proxy_headers(handle), + params={"path": path}, + ) + if isinstance(resp, Failure): + return resp + if resp.status_code == 404: + return None + return resp.content if resp.is_success else Failure("DOWNLOAD_FAILED", "download", str(resp.status_code)) + + +class HBoxClient(OpenSandboxClient): + """HBox's OpenSandbox API: explicit project, nested state and server SAT. + + Execd command/file operations remain shared with OpenSandbox. The SAT + authenticates the HBox proxy; the client-generated token authenticates execd. + """ + + def __init__(self, cfg: SandboxConfig, session_id: str) -> None: + super().__init__(cfg, session_id) + self._access_tokens: dict[str, str] = {} + + async def _req( + self, + method: str, + path: str, + *, + timeout: float, + json_body: JsonObject | None = None, + headers: Mapping[str, str] | None = None, + params: Mapping[str, str] | None = None, + files: Sequence[UploadFileField] | None = None, + ) -> httpx.Response | Failure: + # HBox control APIs select a namespace by project. The SAT proxy derives + # it from its token; a project query there triggers a different ACL/403. + if "/proxy/" not in path: + params = {**(params or {}), "project": self.project} + return await super()._req( + method, path, timeout=timeout, json_body=json_body, headers=headers, params=params, files=files + ) + + def proxy_headers(self, handle: ResourceHandle) -> dict[str, str]: + return {**super().proxy_headers(handle), "X-Sandbox-Access-Token": self._access_tokens[handle.id]} + + @observe_phase("sandbox/create", failure=Failure) + async def create( + self, + *, + image: str, + ports: tuple[int, ...], + resources: ResourceSpec, + ttl: float, + token: str, + op_id: str, + timeout: float, + network_policy: NetworkPolicy | None = None, + on_status: Callable[[int], None] | None = None, + ) -> tuple[str, str] | Failure: + response = await self._req( + "POST", + "/v1/sandboxes", + timeout=timeout, + json_body={ + **({"networkPolicy": network_policy.to_payload()} if network_policy is not None else {}), + "image": {"uri": image}, + "entrypoint": ["sleep", "inf"], + "resources": _format_k8s_resources(resources), + "lifecycleMinutes": ceil(ttl / 60), + "ratio": 1, + "ports": [{"containerPort": port, "name": f"p{port}"} for port in sorted({18080, 44772, *ports})], + "env": {"EXECD_ACCESS_TOKEN": token}, + "metadata": {"purpose": "agent-rl-" + self.session_id, "operation_id": op_id}, + }, + ) + if isinstance(response, Failure): + return Failure("CREATE_FAILED", "create", f"{op_id}: {response.code}/{response.phase}: {response.detail}") + if on_status is not None: + on_status(response.status_code) + created = decode_create_response(response, op_id) + if not isinstance(created, Failure): + sat = response.json().get("accessToken") + if isinstance(sat, str) and sat: + self._access_tokens[created[0]] = sat + # Return a known ID even if SAT is malformed so Runtime can delete it. + return created + + def effective_expiry(self, ttl: float) -> int | None: + """HBox accepts whole minutes rounded up, including subsecond TTLs.""" + seconds = ceil(ttl / 60) * 60 + return seconds if seconds > 0 else None + + async def get_info(self, sandbox_id: str, *, timeout: float) -> JsonObject | Failure: + info = await super().get_info(sandbox_id, timeout=timeout) + if isinstance(info, Failure): + return info + status = info.get("status") + if not isinstance(status, dict) or not isinstance(status.get("state"), str): + return Failure("SANDBOX_RESPONSE_INVALID", "monitor", "status.state must be str") + if sandbox_id not in self._access_tokens: + return Failure("SANDBOX_RESPONSE_INVALID", "monitor", "create response missing accessToken") + return {**info, "state": status["state"].lower()} + + +class EnvGatewayClient: + """统一沙箱网关 env-gateway (pbox / hbox / dbox) 适配实现(保留 HBox URL query token)。""" + + def __init__(self, cfg: SandboxConfig) -> None: + self.cfg: SandboxConfig = cfg + self.base_url: str = cfg.endpoint.rstrip("/") + self.cluster_name: GatewayCluster = cfg.cluster_name + self.user: str = cfg.user + self.project: str = cfg.project + self.aksk: str = Path(cfg.credential_file).read_text().strip() + self.http: httpx.AsyncClient = httpx.AsyncClient(timeout=30.0, trust_env=False, event_hooks=HTTP_EVENT_HOOKS) + + @staticmethod + def _env_route(env_url: str, sub_path: str) -> str: + """在 `?token=...` 之前安全拼接 `/exec` 等子路径,兼容 PBox 前缀与 HBox query token。""" + parts = urlsplit(env_url) + joined_path = parts.path.rstrip("/") + "/" + sub_path.lstrip("/") + return urlunsplit((parts.scheme, parts.netloc, joined_path, parts.query, parts.fragment)) + + async def _req( + self, + method: str, + url: str, + *, + timeout: float, + json_body: JsonObject | None = None, + use_stream_timeout: bool = False, + ) -> httpx.Response | Failure: + req_timeout: float | None = None if use_stream_timeout else 30.0 + try: + async with asyncio.timeout(timeout): + return await self.http.request(method, url, json=json_body, timeout=req_timeout) + except (httpx.HTTPError, TimeoutError) as exc: + return Failure("SANDBOX_IO", "http", f"{method} {url}: {type(exc).__name__}") + + @observe_phase("sandbox/create", failure=Failure) + async def create( + self, + *, + image: str, + ports: tuple[int, ...], + resources: ResourceSpec, + ttl: float, + token: str, + op_id: str, + timeout: float, + ) -> tuple[str, str] | Failure: + resp = await self._req( + "POST", + f"{self.base_url}/envs", + timeout=timeout, + json_body={ + "env": image, + "user": self.user, + "cluster_name": self.cluster_name, + "ttl_seconds": int(ttl), + "extra_params": { + "project": self.project, + "aksk": self.aksk, + "resources": _format_k8s_resources(resources), + }, + }, + ) + if isinstance(resp, Failure): + return Failure("CREATE_FAILED", "create", f"{op_id}: {resp.code}/{resp.phase}: {resp.detail}") + if resp.status_code >= 500: + return Failure("CREATE_FAILED", "create", f"{op_id}: HTTP {resp.status_code}") + if resp.status_code == 429: + return Failure("RESOURCE_RATE_LIMITED", "create", "429") + if not resp.is_success: + return Failure("CREATE_REJECTED", "create", str(resp.status_code)) + try: + env_info: JsonObject = resp.json()["env"] + env_id: JsonValue = env_info["env_id"] + if not isinstance(env_id, str) or not env_id: + raise TypeError("env_id must be a nonempty str") + # A usable ID still belongs to Runtime when connection parameters + # are invalid. wait_ready reports that failure after receipt storage. + env_url: JsonValue = env_info.get("url") + return env_id, env_url if isinstance(env_url, str) else "" + except (ValueError, KeyError, TypeError) as exc: + return Failure("CREATE_FAILED", "create", f"{op_id}: invalid create response: {type(exc).__name__}: {exc}") + + @observe_phase("sandbox/ready", failure=Failure) + async def wait_ready(self, handle: ResourceHandle, *, timeout: float) -> Failure | None: + try: + parts = urlsplit(handle.url) + if parts.scheme not in {"http", "https"} or not parts.netloc: + raise ValueError("url must be an absolute HTTP URL") + except ValueError as exc: + return Failure("CREATE_FAILED", "create", f"{handle.id}: invalid gateway url: {exc}") + try: + async with asyncio.timeout(timeout): + while True: + resp = await self._req("GET", f"{self.base_url}/envs/{handle.id}", timeout=5.0) + if not isinstance(resp, Failure) and resp.is_success: + data = _response_object(resp, "create") + if isinstance(data, Failure): + return data + status: JsonValue = data.get("status") + if not isinstance(status, str): + return Failure("SANDBOX_RESPONSE_INVALID", "create", "status must be str") + if status in ("error", "deleted"): + return Failure("SANDBOX_NOT_READY", "create", handle.id) + if status == "ready": + raw_url: JsonValue = data.get("url") + target_url: str = raw_url if isinstance(raw_url, str) and raw_url else handle.url + health = await self._req( + "GET", + self._env_route(target_url, "/health"), + timeout=5.0, + ) + if not isinstance(health, Failure) and health.is_success: + body = _response_object(health, "create") + if isinstance(body, Failure): + return body + if type(body.get("ok")) is not bool: + return Failure("SANDBOX_RESPONSE_INVALID", "create", "ok must be bool") + if body["ok"]: + return None + await asyncio.sleep(1.0) + except TimeoutError: + return Failure("SANDBOX_NOT_READY", "create", handle.id) + + async def resolve_endpoint(self, handle: ResourceHandle, port: int, *, timeout: float) -> str | Failure: + # env.url exposes exec/files control APIs, with no declared mapping for + # arbitrary application ports. Never publish it as a business endpoint. + raise ValueError("env_gateway does not expose service ports; use opensandbox for multi-container services") + + def effective_expiry(self, ttl: float) -> int | None: + """Return the positive whole-second expiry accepted by Gateway.""" + seconds = int(ttl) + return seconds if seconds > 0 else None + + async def delete(self, sandbox_id: str, *, timeout: float) -> Failure | None: + scope = asyncio.timeout(timeout) + try: + async with scope: + while True: + resp = await self._req( + "DELETE", + f"{self.base_url}/envs/{sandbox_id}", + timeout=10.0, + ) + if not isinstance(resp, Failure): + if resp.status_code == 404: + return None + if resp.is_success: + body = _response_object(resp, "delete") + if isinstance(body, Failure): + return body + if type(body.get("ok")) is not bool: + return Failure("SANDBOX_RESPONSE_INVALID", "delete", "ok must be bool") + if body["ok"]: + return None + await asyncio.sleep(0.5) + except TimeoutError: + if not scope.expired(): + raise + return Failure("DELETE_FAILED", "delete", sandbox_id) + + async def exec(self, handle: ResourceHandle, command: str, *, cwd: str, timeout: float) -> ExecOutput | Failure: + timeout_sec: int = max(1, int(timeout)) + resp = await self._req( + "POST", + self._env_route(handle.url, "/exec"), + timeout=timeout, + json_body={"command": command, "cwd": cwd, "timeout_sec": timeout_sec, "detach": False}, + use_stream_timeout=True, + ) + if isinstance(resp, Failure) or not resp.is_success: + return Failure("COMMAND_UNKNOWN", "command", handle.id) + try: + body = _response_object(resp, "command") + if isinstance(body, Failure): + return body + rc: JsonValue = body["return_code"] + if type(rc) is not int: + raise TypeError("return_code must be int") + return ExecOutput(rc, str(body.get("stdout", "")), str(body.get("stderr", ""))) + except (ValueError, KeyError, TypeError) as exc: + return Failure("COMMAND_UNKNOWN", "command", type(exc).__name__) + + async def upload(self, handle: ResourceHandle, path: str, content: bytes, *, timeout: float) -> Failure | None: + resp = await self._req( + "POST", + self._env_route(handle.url, "/upload"), + timeout=timeout, + json_body={"target_path": path, "content_b64": base64.b64encode(content).decode()}, + ) + if isinstance(resp, Failure) or not resp.is_success: + return Failure("UPLOAD_FAILED", "upload", path) + body = _response_object(resp, "upload") + if isinstance(body, Failure): + return body + if type(body.get("ok")) is not bool: + return Failure("SANDBOX_RESPONSE_INVALID", "upload", "ok must be bool") + return None if body["ok"] else Failure("UPLOAD_FAILED", "upload", path) + + async def download(self, handle: ResourceHandle, path: str, *, timeout: float) -> bytes | None | Failure: + resp = await self._req( + "POST", + self._env_route(handle.url, "/download"), + timeout=timeout, + json_body={"source_path": path}, + ) + if isinstance(resp, Failure): + return resp + if resp.status_code == 404: + return None + if not resp.is_success: + return Failure("DOWNLOAD_FAILED", "download", str(resp.status_code)) + try: + body = _response_object(resp, "download") + if isinstance(body, Failure): + return body + if not bool(body.get("ok")): + return Failure("DOWNLOAD_FAILED", "download", "gateway response is not ok") + b64_str: JsonValue = body["content_b64"] + if not isinstance(b64_str, str): + raise TypeError("content_b64 must be str") + return base64.b64decode(b64_str) + except (ValueError, KeyError, TypeError) as exc: + return Failure("DOWNLOAD_FAILED", "download", type(exc).__name__) + + async def aclose(self) -> None: + await self.http.aclose() + + +def make_sandbox_client(cfg: SandboxConfig, session_id: str) -> OpenSandboxClient | EnvGatewayClient: + if cfg.backend == "env_gateway": + return EnvGatewayClient(cfg) + if cfg.platform == "hbox": + return HBoxClient(cfg, session_id) + return OpenSandboxClient(cfg, session_id) + + +class OpenSandboxCommands: + """Explicit optional command-ID capability, bound to one sandbox.""" + + def __init__(self, client: OpenSandboxClient, handle: ResourceHandle, request_seconds: float = 5) -> None: + self.client = client + self.request_seconds = request_seconds + self.handle = handle + self.path = f"/v1/sandboxes/{handle.id}/proxy/44772" + self.headers = client.proxy_headers(handle) + + async def start_command(self, command: str, cwd: str, timeout_sec: float) -> str | Failure: + try: + async with asyncio.timeout(self.request_seconds): + async with self.client.http.stream( + "POST", + self.client.base_url + self.path + "/command", + headers=self.headers, + json={ + "command": command, + "cwd": cwd, + "background": True, + "timeout": max(1, int(timeout_sec * 1000)), + }, + timeout=None, + ) as response: + response.raise_for_status() + async for line in response.aiter_lines(): + event = decode_execd_event(line) + if event is None: + continue + if event["type"] == "init" and isinstance(event.get("text"), str) and event["text"]: + return event["text"] + except (httpx.HTTPError, TimeoutError, ValueError, KeyError, TypeError) as exc: + return Failure("JOB_LAUNCH", "launch", type(exc).__name__) + return Failure("JOB_LAUNCH", "launch", "missing native command ID") + + async def get_command_status(self, command_id: str) -> dict[str, bool | int | None] | Failure: + response = await self.client._req( + "GET", self.path + "/command/status/" + quote(command_id, safe=""), headers=self.headers, timeout=5 + ) + if isinstance(response, Failure): + return response + try: + if not response.is_success: + if response.status_code in (409, 503): + # An inactive route may be transient, or the container may + # already be dead. Only the control plane can distinguish + # these; never infer an exit code from a failed proxy read. + state = await self.client.get_info(self.handle.id, timeout=5) + if isinstance(state, Failure) and state.code == "SANDBOX_RESPONSE_INVALID": + return state + if not isinstance(state, Failure): + if not isinstance(state.get("state"), str): + return Failure("SANDBOX_RESPONSE_INVALID", "monitor", "state must be str") + if state.get("state") == "failed": + details = state.get("status") or {} + if not isinstance(details, dict): + return Failure("SANDBOX_RESPONSE_INVALID", "monitor", "status must be object") + reason = details.get("reason") or details.get("message", "") + observation = current_observation() + if observation: + observation.emit( + "sandbox_failed", + sandbox_id=self.handle.id, + resource_name=self.handle.name, + native_command_id=command_id, + state="failed", + reason=reason, + ) + return Failure("SANDBOX_TERMINATED", "monitor", f"{self.handle.id}: {reason}") + return Failure("COMMAND_UNKNOWN", "monitor", str(response.status_code)) + status = _response_object(response, "monitor") + if isinstance(status, Failure): + return status + return decode_command_status(status, self.handle.id, command_id) + except (ValueError, KeyError, TypeError) as exc: + return Failure("COMMAND_UNKNOWN", "monitor", str(exc)) + + async def get_command_output(self, command_id: str) -> dict[str, str] | Failure: + response = await self.client._req( + "GET", + self.path + "/command/" + quote(command_id, safe="") + "/logs", + headers=self.headers, + # This is a terminal log read, rather than a short status poll. + timeout=self.request_seconds, + ) + if isinstance(response, Failure): + return response + if not response.is_success: + return Failure("COMMAND_UNKNOWN", "output", str(response.status_code)) + return {"stdout": response.text, "stderr": ""} + + async def interrupt_command(self, command_id: str) -> Failure | None: + response = await self.client._req( + "DELETE", + self.path + "/command", + params={"id": command_id}, + headers=self.headers, + timeout=min(5.0, self.request_seconds), + ) + if isinstance(response, Failure): + return response + return None if response.is_success else Failure("STOP_UNCONFIRMED", "stop", str(response.status_code)) diff --git a/xtuner/v1/rl/agent_loop/trial_agent_loop/sandbox/jobs.py b/xtuner/v1/rl/agent_loop/trial_agent_loop/sandbox/jobs.py new file mode 100644 index 0000000000..ef884fb991 --- /dev/null +++ b/xtuner/v1/rl/agent_loop/trial_agent_loop/sandbox/jobs.py @@ -0,0 +1,359 @@ +"""Single-command ownership; cross-resource policy belongs to SandboxRuntime.""" + +from __future__ import annotations + +import asyncio +import json +import logging +import shlex +from contextlib import suppress +from dataclasses import dataclass, field +from pathlib import Path +from time import monotonic +from typing import Literal, Mapping, Sequence, TypeAlias + +import httpx +from mini_agent import Failure + +from xtuner.v1.rl.agent_loop.trial_agent_loop.observation import record_artifact +from xtuner.v1.rl.agent_loop.trial_agent_loop.sandbox.client import ( + EnvGatewayClient, + OpenSandboxClient, + OpenSandboxCommands, +) +from xtuner.v1.rl.agent_loop.trial_agent_loop.sandbox.process_monitor import observe_process +from xtuner.v1.rl.agent_loop.trial_agent_loop.sandbox.types import ResourceHandle +from xtuner.v1.rl.agent_loop.trial_agent_loop.trial.base import Budgets +from xtuner.v1.rl.observability import current_observation, observe_phase +from xtuner.v1.rl.utils.async_utils import cleanup_owned_task, find_error_original_task + + +JobKind: TypeAlias = Literal["setup", "service", "agent", "grader"] +logger = logging.getLogger(__name__) + + +def shell_command(env: Mapping[str, str], argv: Sequence[str]) -> str: + """Preserve the image environment and apply explicit overrides without platform credentials.""" + exports = " ".join(f"{key}={shlex.quote(value)}" for key, value in env.items()) + return "env -u EXECD_ACCESS_TOKEN " + (exports + " " if exports else "") + shlex.join(argv) + + +@dataclass +class Job: + id: str + resource: ResourceHandle + kind: JobKind + directory: str + client: OpenSandboxClient | EnvGatewayClient + budgets: Budgets + output_dir: Path + command_id: str | None = None + terminal: bool = False + return_code: int | None = None + artifact_paths: dict[str, str] = field(default_factory=dict) + artifact_errors: dict[str, str] = field(default_factory=dict) + session_id: str | None = None + + async def start(self, argv: Sequence[str], *, cwd: str, env: Mapping[str, str], timeout: float) -> Failure | None: + prepared = await self.client.exec( + self.resource, + "install -d -m 700 " + shlex.join(("/private", "/private/jobs", self.directory)), + cwd="/tmp", + timeout=self.budgets.request, + ) + if isinstance(prepared, Failure): + return prepared + if prepared.return_code: + return Failure("JOB_LAUNCH", "launch", prepared.stderr) + return await self._start(shell_command(env, argv), cwd, timeout) + + async def _start(self, command: str, cwd: str, timeout: float) -> Failure | None: + raise NotImplementedError + + async def wait(self, timeout: float) -> int | Failure: + raise NotImplementedError + + async def collect(self, outputs: Sequence[str]) -> tuple[int, dict[str, bytes]] | Failure: + assert self.return_code is not None + files = {} + for name in outputs: + path = name if name.startswith("/") else f"{self.directory}/results/{name}" + content = await self.client.download(self.resource, path, timeout=self.budgets.request) + if isinstance(content, Failure): + return content + if content is None: + return Failure("RESULT_MISSING", "job", name) + files[name] = content + record_artifact(self.output_dir, self, name, content) + if name in self.artifact_errors: + logger.warning( + "Job artifact copy failed sid=%s job=%s artifact=%s: %s", + self.session_id, + self.id, + name, + self.artifact_errors[name], + ) + return self.return_code, files + + def _write_diagnostic(self, suffix: str, content: str) -> None: + path = self.output_dir / f"job-{self.id}.{suffix}" + # The job journal reports files at the final paths. Publish them only + # after a complete write, even if the disk fills partway through. + temporary = path.with_suffix(path.suffix + ".tmp") + try: + temporary.write_text(content) + temporary.replace(path) + except OSError as exc: + logger.warning( + "Job diagnostic write failed sid=%s job=%s diagnostic=%s rc=%s: %s", + self.session_id, + self.id, + suffix, + self.return_code, + exc, + ) + with suppress(OSError): + temporary.unlink(missing_ok=True) + + async def stop(self, timeout: float) -> Failure | None: + raise NotImplementedError + + async def check_health(self) -> Failure | None: + return None + + async def stop_on_exit(self, timeout: float) -> Failure | None: + return None + + async def close(self) -> BaseException | None: + """Converge the original launch after resource deletion; never relaunch.""" + + async def diagnostic(self) -> str: + result = await self.client.download(self.resource, self.directory + "/stderr", timeout=self.budgets.request) + return result.decode(errors="replace") if isinstance(result, bytes) else repr(result) + + +@dataclass +class NativeJob(Job): + _launch: asyncio.Task[str | Failure] | None = field(default=None, init=False, repr=False) + _output: dict[str, str] | None = field(default=None, init=False, repr=False) + launch_error_seen: bool = field(default=False, init=False) + + def __post_init__(self) -> None: + assert isinstance(self.client, OpenSandboxClient) + self._commands = OpenSandboxCommands(self.client, self.resource, self.budgets.request) + + async def _start(self, command: str, cwd: str, timeout: float) -> Failure | None: + # Save the original launch before awaiting its ID. An unknown receipt + # never permits a second POST or a switch to detached execution. + self._launch = asyncio.create_task(self._commands.start_command(command, cwd, timeout)) + result = await self.launch_result() + if isinstance(result, Failure): + return result + self.command_id = result + observation = current_observation() + if observation: + observation.emit("job_launched", job_id=self.id, native_command_id=result) + return None + + async def launch_result(self) -> str | Failure: + """Wait for the original launch and record delivery of ordinary errors.""" + assert self._launch is not None + try: + return await asyncio.shield(self._launch) + except Exception: + self.launch_error_seen = True + raise + + async def wait(self, timeout: float) -> int | Failure: + assert self.command_id is not None + # Recover reads of this original ID only. A terminal status needs an + # actual rc for execution evidence; capture it before any log download. + unknown_since: float | None = None + while True: + status = await self._commands.get_command_status(self.command_id) + if isinstance(status, Failure): + if status.code == "SANDBOX_TERMINATED": + self.terminal = True + return status + unknown_since = unknown_since or monotonic() + if monotonic() - unknown_since >= self.budgets.read_recovery: + return status + else: + unknown_since = None + if status["running"] is False: + self.terminal = True + rc = status["return_code"] + if type(rc) is not int: + return Failure("EXIT_CODE_MISSING", "job", self.command_id) + # Keep this fact even if a later log or artifact read fails. + self.return_code = rc + output = await self._commands.get_command_output(self.command_id) + if isinstance(output, Failure): + return output + self._output = output + for stream, content in output.items(): + self._write_diagnostic(stream, content) + return rc + await asyncio.sleep(0.2) + + async def check_health(self) -> Failure | None: + if self.terminal or self.command_id is None: + return None + status = await self._commands.get_command_status(self.command_id) + if isinstance(status, Failure) and status.code == "SANDBOX_TERMINATED": + self.terminal = True + return status + return None + + @observe_phase("tools/stop_native", failure=Failure) + async def stop(self, timeout: float) -> Failure | None: + """Interrupt once, then certify this command stopped within its stop budget. + + Unlike wait(), stopping may be confirmed without a readable exit code. + These loops intentionally share the client's read/decoding boundary, + rather than hiding their different completion rules behind poll flags. + """ + if self.terminal or self._launch is None: + return None + try: + async with asyncio.timeout(timeout): + if self.command_id is None: + launched = await self.launch_result() + if isinstance(launched, Failure): + return launched + self.command_id = launched + command_id = self.command_id + await self._commands.interrupt_command(command_id) + # Interrupt acknowledgement is not proof of termination. + while True: + status = await self._commands.get_command_status(command_id) + if isinstance(status, Failure) and status.code == "SANDBOX_TERMINATED": + self.terminal = True + return None + if not isinstance(status, Failure) and status["running"] is False: + self.terminal = True + rc = status["return_code"] + if type(rc) is int: + self.return_code = rc + return None + await asyncio.sleep(0.2) + except TimeoutError: + return Failure("STOP_UNCONFIRMED", "stop", self.id) + + async def stop_on_exit(self, timeout: float) -> Failure | None: + if self.terminal or self._launch is None: + return None + return await self.stop(timeout) + + async def close(self) -> BaseException | None: + if self._launch is not None: + launch_error = await cleanup_owned_task(self._launch) + return find_error_original_task(launch_error, seen_by_caller=self.launch_error_seen) + return None + + async def diagnostic(self) -> str: + return repr(self._output) + + +class DetachedJob(Job): + async def _start(self, command: str, cwd: str, timeout: float) -> Failure | None: + script = ( + "#!/bin/bash\n" + f"printf '%s' $$ > {shlex.quote(self.directory + '/pid.tmp')}\n" + f"mv {shlex.quote(self.directory + '/pid.tmp')} {shlex.quote(self.directory + '/pid')}\n" + f"(cd {shlex.quote(cwd)} || exit 125; {command}) " + f"> {shlex.quote(self.directory + '/stdout')} 2> {shlex.quote(self.directory + '/stderr')}\n" + f"printf '%s' $? > {shlex.quote(self.directory + '/rc.tmp')}\n" + f"mv {shlex.quote(self.directory + '/rc.tmp')} {shlex.quote(self.directory + '/rc')}\n" + ) + path = self.directory + "/job.sh" + uploaded = await self.client.upload(self.resource, path, script.encode(), timeout=self.budgets.request) + if isinstance(uploaded, Failure): + return uploaded + launched = await self.client.exec( + self.resource, + f"setsid nohup bash {shlex.quote(path)} >/dev/null 2>&1 int | Failure | None: + value = await self.client.download(self.resource, self.directory + "/pid", timeout=self.budgets.request) + if not isinstance(value, bytes): + return value + try: + pid = int(value) + if pid <= 0: + raise ValueError("PID must be positive") + return pid + except ValueError: + return Failure("JOB_LOST", "monitor", "invalid PID") + + async def wait(self, timeout: float) -> int | Failure: + """Recover the original PID/rc files; observe_process owns bounded read recovery. + + Missing rc, unreadable rc and a dead sandbox remain different facts. + No receipt failure starts a replacement command or changes backend. + """ + async with asyncio.timeout(self.budgets.read_recovery): + while True: + pid = await self._read_pid() + if type(pid) is int: + break + if isinstance(pid, Failure) and pid.code == "JOB_LOST": + return pid + await asyncio.sleep(0.2) + reason, rc, diagnostics = await observe_process( + self, + pid=pid, + timeout=timeout, + recovery_timeout=self.budgets.read_recovery, + poll_interval=0.5, + retry_interval=0.5, + rc_wait_timeout=5, + rc_poll_interval=0.2, + read_rc=self.read_rc, + ) + if rc is not None: + self.return_code = rc + self.terminal = True + self._write_diagnostic("json", json.dumps(diagnostics)) + if rc is None: + return Failure("JOB_TIMEOUT" if reason == "timeout" else "JOB_LOST", "monitor", reason) + return rc + + async def is_pid_running(self, pid: int) -> bool: + result = await self.client.exec( + self.resource, f"kill -0 {pid} 2>/dev/null", cwd="/tmp", timeout=min(self.budgets.request, 5) + ) + if isinstance(result, Failure): + raise httpx.RemoteProtocolError(result.detail) + return result.return_code == 0 + + async def read_rc(self) -> int | None: + result = await self.client.download(self.resource, self.directory + "/rc", timeout=self.budgets.request) + if isinstance(result, Failure): + raise httpx.RemoteProtocolError(result.detail) + if result is None: + return None + try: + return int(result) + except ValueError as exc: + raise httpx.RemoteProtocolError("invalid exit code") from exc + + async def stop(self, timeout: float) -> Failure | None: + pid = await self._read_pid() + if type(pid) is not int: + return Failure("STOP_UNCONFIRMED", "stop", self.id + ": " + repr(pid)) + command = ( + f"kill -TERM -- -{pid} 2>/dev/null || true; " + f"for i in {{1..20}}; do kill -0 -- -{pid} 2>/dev/null || exit 0; sleep 0.1; done; " + f"kill -KILL -- -{pid} 2>/dev/null || true; ! kill -0 -- -{pid} 2>/dev/null" + ) + result = await self.client.exec(self.resource, command, cwd="/tmp", timeout=timeout) + if isinstance(result, Failure) or result.return_code != 0: + return Failure("STOP_UNCONFIRMED", "stop", self.id) + return None diff --git a/xtuner/v1/rl/agent_loop/trial_agent_loop/sandbox/process_monitor.py b/xtuner/v1/rl/agent_loop/trial_agent_loop/sandbox/process_monitor.py new file mode 100644 index 0000000000..f75dbf0bd1 --- /dev/null +++ b/xtuner/v1/rl/agent_loop/trial_agent_loop/sandbox/process_monitor.py @@ -0,0 +1,132 @@ +"""Bounded read-only process/exit-code observation; unknown is never missing.""" + +import asyncio +import time + +import httpx + + +TERMINAL = {"deleted", "terminated", "failed", "stopped", "expired"} + + +async def observe_process( + client, + *, + pid, + timeout, + recovery_timeout, + poll_interval, + retry_interval, + rc_wait_timeout, + rc_poll_interval, + read_rc, + max_failures=3, +): + deadline = time.monotonic() + timeout + failures = {} # Independent PID and rc outages: a good PID cannot heal rc. + consecutive = {"pid": 0, "rc": 0} + errors = {"pid": 0, "rc": 0} + observations, rc_checks = [], [] + polls = 0 + missing_since = None + + def end(): + return ( + min([deadline] + [t + recovery_timeout for t in failures.values()]) if recovery_timeout > 0 else deadline + ) + + def result(reason, rc=None): + return ( + reason, + rc, + dict( + pid=pid, + polls=polls, + pid_check_errors_total=errors["pid"], + rc_check_errors_total=errors["rc"], + monitor_observations=observations, + rc_checks=rc_checks, + probe_kind=next(iter(failures), None), + deadline_reached=time.monotonic() >= deadline, + recovery_deadline_reached=bool(failures) and recovery_timeout > 0 and time.monotonic() >= end(), + ), + ) + + async def bounded(call, limit): + remaining = min(limit, end() - time.monotonic()) + if remaining <= 0: + raise TimeoutError + return await asyncio.wait_for(call(), remaining) + + def failed(kind, exc): + failures.setdefault(kind, time.monotonic()) + errors[kind] += 1 + consecutive[kind] += 1 + row = dict(poll=polls, probe_kind=kind, error_type=type(exc).__name__) + observations.append(row) + del observations[:-32] + return row + + def recovered(kind): + failures.pop(kind, None) + consecutive[kind] = 0 + + while time.monotonic() < end(): + polls += 1 + running = None + try: + running = await bounded(lambda: client.is_pid_running(pid), 30) + if type(running) is not bool: + raise httpx.RemoteProtocolError("Non-boolean process observation") + recovered("pid") + except (httpx.HTTPError, asyncio.TimeoutError, TimeoutError) as exc: + row = failed("pid", exc) + query = getattr(client, "get_lifecycle_state", None) + if query: + try: + row["sandbox_state"] = await bounded(query, 5) + if row["sandbox_state"] in TERMINAL: + return result("sandbox_unavailable") + except (httpx.HTTPError, RuntimeError, asyncio.TimeoutError, TimeoutError): + pass + + if running is not True or "rc" in failures: + started = time.monotonic() + check = {} + try: + rc = await bounded(read_rc, 5) + if rc is not None and type(rc) is not int: + raise httpx.RemoteProtocolError("Invalid exit code") + recovered("rc") + check["missing"] = rc is None + if rc is not None: + return result("entry_completed" if rc == 0 else "entry_failed", rc) + if running is False: + missing_since = missing_since or time.monotonic() + else: + missing_since = None + except (httpx.HTTPError, asyncio.TimeoutError, TimeoutError) as exc: + failed("rc", exc) + missing_since = None + check["error_type"] = type(exc).__name__ + if isinstance(exc, httpx.HTTPStatusError): + check["http_status"] = exc.response.status_code + finally: + check["elapsed_seconds"] = time.monotonic() - started + rc_checks.append(check) + del rc_checks[:-3] + else: + missing_since = None + + if failures and ( + time.monotonic() >= end() or (recovery_timeout <= 0 and max(consecutive.values()) >= max_failures) + ): + return result("pid_monitor_error") + if missing_since is not None and time.monotonic() >= missing_since + rc_wait_timeout: + return result("rc_missing") + delay = retry_interval if failures else poll_interval if running else rc_poll_interval + wake = end() + if missing_since is not None: + wake = min(wake, missing_since + rc_wait_timeout) + await asyncio.sleep(min(max(0.01, delay), max(0, wake - time.monotonic()))) + return result("pid_monitor_error" if failures else "rc_missing" if missing_since is not None else "timeout") diff --git a/xtuner/v1/rl/agent_loop/trial_agent_loop/sandbox/runtime.py b/xtuner/v1/rl/agent_loop/trial_agent_loop/sandbox/runtime.py new file mode 100644 index 0000000000..fc5662b807 --- /dev/null +++ b/xtuner/v1/rl/agent_loop/trial_agent_loop/sandbox/runtime.py @@ -0,0 +1,1484 @@ +"""One Attempt owns every pending sandbox creation and deletion.""" + +from __future__ import annotations + +import asyncio +import hashlib +import json +import logging +import secrets +import shlex +import tarfile +from builtins import BaseExceptionGroup +from dataclasses import asdict, dataclass, field, replace +from pathlib import Path, PurePosixPath +from time import time +from types import TracebackType +from typing import Any, Literal, Mapping, Sequence, TypeAlias +from uuid import uuid4 + +import mini_agent as ma +from mini_agent import Failure + +from xtuner.v1.rl.agent_loop.trial_agent_loop.error_handling import record_production_exception +from xtuner.v1.rl.agent_loop.trial_agent_loop.observation import ( + observe_job, + record_job_finished, + record_worker_observation, +) +from xtuner.v1.rl.agent_loop.trial_agent_loop.sandbox.client import ( + EnvGatewayClient, + OpenSandboxClient, + make_sandbox_client, +) +from xtuner.v1.rl.agent_loop.trial_agent_loop.sandbox.jobs import DetachedJob, Job, JobKind, NativeJob, shell_command +from xtuner.v1.rl.agent_loop.trial_agent_loop.sandbox.types import ( + AgentResult, + CmdArg, + CommandSpec, + GradeEvidence, + NetworkPolicy, + NetworkPolicyInput, + PreparedWorkspace, + ResourceHandle, + SandboxConfig, + WorkerCrashError, +) +from xtuner.v1.rl.agent_loop.trial_agent_loop.trial.base import Budgets, ResourceSpec, TrialContext, resolve_resources +from xtuner.v1.rl.observability import current_observation, observe_phase, otel +from xtuner.v1.rl.utils.async_utils import cleanup_owned_task, find_error_original_task, finish_owned + + +logger = logging.getLogger(__name__) +DeleteOutcome: TypeAlias = Failure | Literal["NO_ACK", "NO_TIME"] | None +ReleaseStatus: TypeAlias = Literal["REJECTED", "UNKNOWN", "DELETED", "TTL", "UNCONTAINED"] +ErrorRecords: TypeAlias = list[tuple[str, BaseException]] + + +@dataclass(frozen=True) +class _Known: + id: str + effective_expiry: int | None + + +@dataclass(frozen=True) +class ReleaseReceipt: + sandbox_id: str + source: Literal["explicit", "close"] + confirmed_at: float + confirmation: Literal["get_404", "gateway_delete_ack"] + + +@dataclass +class _CreateEntry: + name: str + op_id: str + token: str = field(repr=False) + resources: ResourceSpec + image: str + ports: tuple[int, ...] + network_policy: NetworkPolicy | None + receipt: _Known | Literal["UNKNOWN", "REJECTED"] = "UNKNOWN" + task: asyncio.Task[ResourceHandle | Failure] = field(init=False, repr=False) + error_observed: bool = False + policy_http_status: int | None = None + release_task: asyncio.Task[Failure | None] | None = None + confirmed_release: ReleaseReceipt | None = None + ready_cancelled_for_release: bool = False + handoff: asyncio.Event = field(default_factory=asyncio.Event, repr=False) + + +def find_error_execution(outcome: BaseException | None) -> tuple[BaseException | None, asyncio.CancelledError | None]: + if isinstance(outcome, asyncio.CancelledError): + return None, outcome + return outcome, None + + +def resolve_result_sandbox_exit( + execution_error: BaseException | None, + execution_cancel: asyncio.CancelledError | None, + cleanup_outcome: None | BaseException, + wait_cancel: asyncio.CancelledError | None, +) -> None: + if cleanup_outcome is None and (wait_cancel is None or execution_cancel is not None): + return # __aexit__ returns False; Python propagates the original body error. + errors = [ + error + for error in (execution_error, execution_cancel, wait_cancel) + if error is not None and error is not cleanup_outcome + ] + if cleanup_outcome is not None: + errors.append(cleanup_outcome) + raise errors[0] if len(errors) == 1 else BaseExceptionGroup("sandbox exit", errors) + + +def sandbox_release_status(entry: _CreateEntry, delete_outcomes_by_id: dict[str, DeleteOutcome]) -> ReleaseStatus: + if not isinstance(entry.receipt, _Known): + return entry.receipt + if delete_outcomes_by_id.get(entry.receipt.id, "NO_ACK") is None: + return "DELETED" + return "TTL" if entry.receipt.effective_expiry else "UNCONTAINED" + + +class SandboxRuntime: + def __init__( + self, + *, + ctx: TrialContext, + sandbox_cfg: SandboxConfig, + default_resources: ResourceSpec, + harness: ma.HarnessSpec, + max_turns: int | None, + tool_user: str | None, + tool_env: dict[str, str], + fail_fast_on_worker_crash: bool = False, + require_clean_exit: bool = False, + tool_env_command: Sequence[str] = ("env", "-0"), + ) -> None: + self.ctx: TrialContext = ctx + ctx.output_dir.mkdir(parents=True, exist_ok=True) + self.budgets: Budgets = ctx.budgets + # Attempt 总超时由父端控制;本进程只使用阶段时长,退出清理另用 cleanup。 + self.sandbox_cfg: SandboxConfig = sandbox_cfg + self.default_resources: ResourceSpec = default_resources + self.harness: ma.HarnessSpec = harness + self.max_turns: int | None = max_turns + self.tool_user: str | None = tool_user + self.tool_env: dict[str, str] = dict(tool_env) + self.tool_env_command = tuple(tool_env_command) + self.fail_fast_on_worker_crash = fail_fast_on_worker_crash + self.require_clean_exit = require_clean_exit + self.cleanup_failure: Failure | None = None + self.observed_request_ids: list[str] | None = None + self.client: OpenSandboxClient | EnvGatewayClient = make_sandbox_client(sandbox_cfg, ctx.session_id) + if sandbox_cfg.command_mode == "native" and not isinstance(self.client, OpenSandboxClient): + raise ValueError("This backend does not provide native command IDs") + self._job_type = NativeJob if sandbox_cfg.command_mode == "native" else DetachedJob + self._creates: dict[str, _CreateEntry] = {} + self._delete_tasks_by_id: dict[str, asyncio.Task[Failure | None]] = {} + self._jobs: list[Job] = [] + self._close_task: asyncio.Task[None] | None = None + + async def __aenter__(self) -> SandboxRuntime: + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + tb: TracebackType | None, + ) -> Literal[False]: + await self._close(exc) + return False + + @property + def command_ids(self) -> dict[str, str | None]: + return {job.id: job.command_id for job in self._jobs} + + @observe_phase("sandbox/acquire", failure=Failure) + async def acquire( + self, + name: str, + *, + image: str, + ports: Sequence[int] = (), + resources: ResourceSpec | None = None, + network_policy: NetworkPolicyInput | None = None, + ) -> ResourceHandle | Failure: + if self._close_task is not None: + raise asyncio.CancelledError() + if network_policy is not None and self.sandbox_cfg.backend != "opensandbox": + raise ValueError("create-time network policy requires OpenSandbox") + resolved = NetworkPolicy.resolve(network_policy, self.ctx.model.url) if network_policy is not None else None + effective_res = resolve_resources(resources, self.default_resources) + ports = tuple(sorted(set(ports))) + if name not in self._creates: + entry = _CreateEntry( + name=name, + op_id=uuid4().hex, + token=secrets.token_hex(16), + resources=effective_res, + image=image, + ports=ports, + network_policy=resolved, + ) + # Task's deferred start also bypasses an eager task factory: POST + # cannot run before this complete entry is published, with no await. + entry.task = asyncio.Task( + self._acquire_one(name, entry, image, tuple(ports)), loop=asyncio.get_running_loop() + ) + self._creates[name] = entry + entry = self._creates[name] + if entry.release_task is not None or entry.confirmed_release is not None: + raise ValueError(f"sandbox already released: {name}") + if (entry.image, entry.ports, entry.resources, entry.network_policy) != ( + image, + ports, + effective_res, + resolved, + ): + raise ValueError(f"conflicting sandbox specification: {name}") + task = entry.task + try: + return await asyncio.shield(task) + except Exception: + entry.error_observed = True + raise + + async def _acquire_one( + self, + name: str, + entry: _CreateEntry, + image: str, + ports: tuple[int, ...], + ) -> ResourceHandle | Failure: + observation = current_observation() + if observation: + observation.emit("resource_create_started", operation_id=entry.op_id, resource_name=name, image=image) + policy_args = {} + if entry.network_policy is not None: + policy_args = { + "network_policy": entry.network_policy, + "on_status": lambda status: setattr(entry, "policy_http_status", status), + } + created = await self.client.create( + image=image, + ports=ports, + resources=entry.resources, + ttl=self.budgets.sandbox_ttl, + token=entry.token, + op_id=entry.op_id, + timeout=self.budgets.create_rpc, + **policy_args, + ) + # 先保存平台互斥回执,再允许释放任务和观察事件读取资源去向。 + if isinstance(created, Failure): + entry.receipt = "REJECTED" if created.code in {"CREATE_REJECTED", "RESOURCE_RATE_LIMITED"} else "UNKNOWN" + else: + entry.receipt = _Known(created[0], self.client.effective_expiry(self.budgets.sandbox_ttl)) + entry.handoff.set() + if observation: + observation.emit( + "resource_create_finished", + operation_id=entry.op_id, + resource_name=name, + image=image, + status=("failed" if entry.receipt == "REJECTED" else "unknown") + if isinstance(created, Failure) + else "known", + sandbox_id=None if isinstance(created, Failure) else created[0], + error=asdict(created) if isinstance(created, Failure) else None, + ) + if entry.network_policy is not None: + folder = self.ctx.output_dir / "network" / entry.op_id + folder.mkdir(parents=True, exist_ok=True) + (folder / "network_policy.json").write_text( + json.dumps( + { + "resource_name": name, + "operation_id": entry.op_id, + "sandbox_id": entry.receipt.id if isinstance(entry.receipt, _Known) else None, + "policy": entry.network_policy.to_payload(), + "http_status": entry.policy_http_status, + "time": time(), + } + ) + ) + if isinstance(created, Failure): + return created + sid, url = created + if self._close_task is not None: + return Failure("CANCELLED", "create", name) + handle = ResourceHandle(name=name, id=sid, url=url, token=entry.token) + ready_budget = self.budgets.ready if self.budgets.ready is not None else self.budgets.attempt + err = await self.client.wait_ready(handle, timeout=ready_budget) + return err if isinstance(err, Failure) else handle + + async def release(self, name: str) -> Failure | None: + entry = self._creates.get(name) + if entry is None or entry.confirmed_release is not None or entry.receipt == "REJECTED": + return None + if entry.release_task is None: + if self._close_task is not None: + return Failure("RESOURCE_RELEASE_UNCONFIRMED", "release", f"runtime closing: {name}") + entry.release_task = asyncio.Task(self._release_one(entry), loop=asyncio.get_running_loop()) + outcome, wait_cancel = await finish_owned(entry.release_task) + errors = [error for error in (wait_cancel, outcome) if isinstance(error, BaseException)] + if errors: + raise errors[0] if len(errors) == 1 else BaseExceptionGroup("sandbox release", errors) + return outcome + + async def _release_one(self, entry: _CreateEntry) -> Failure | None: + loop = asyncio.get_running_loop() + deadline = loop.time() + self.budgets.cleanup + if entry.receipt == "UNKNOWN" and not entry.task.done(): + scope = asyncio.timeout(max(0, min(self.budgets.create_rpc, deadline - loop.time()))) + try: + async with scope: + await entry.handoff.wait() + except TimeoutError: + if not scope.expired(): + raise + if entry.receipt == "REJECTED": + return None + if not isinstance(entry.receipt, _Known): + return Failure("RESOURCE_RELEASE_UNCONFIRMED", "release", f"create outcome unknown: {entry.name}") + + # 已拿到远端 ID,只取消 readiness;原 POST 的回执和自发取消仍须保留。 + stopping_ready = not entry.task.done() and entry.task.cancelling() == 0 + collect = asyncio.Task(cleanup_owned_task(entry.task), loop=loop) + task_error, collect_cancel = await finish_owned(collect) + entry.ready_cancelled_for_release = stopping_ready and entry.task.cancelled() and task_error is None + original_error = find_error_original_task(task_error, seen_by_caller=entry.error_observed) + errors = [error for error in (original_error, collect_cancel) if error is not None] + outcome: Failure | BaseException | None = Failure("DELETE_FAILED", "cleanup", "release deadline expired") + sandbox_id = entry.receipt.id + if sandbox_id in self._delete_tasks_by_id or deadline > loop.time(): + if sandbox_id not in self._delete_tasks_by_id: + self._delete_tasks_by_id[sandbox_id] = asyncio.Task( + self.client.delete(sandbox_id, timeout=deadline - loop.time()), loop=loop + ) + outcome, delete_cancel = await finish_owned(self._delete_tasks_by_id[sandbox_id]) + if delete_cancel is not None: + errors.append(delete_cancel) + if outcome is None: + try: + self._confirm_release(entry.name, entry, "explicit") + except BaseException as confirm_error: + errors.append(confirm_error) + elif isinstance(outcome, BaseException): + errors.append(outcome) + if errors: + raise errors[0] if len(errors) == 1 else BaseExceptionGroup("sandbox release", errors) + if isinstance(outcome, Failure): + return Failure("RESOURCE_RELEASE_UNCONFIRMED", "release", f"{entry.name}: {outcome.detail}") + return None + + def _confirm_release(self, name: str, entry: _CreateEntry, source: Literal["explicit", "close"]) -> None: + if entry.confirmed_release is not None: + return + assert isinstance(entry.receipt, _Known) + # 只有删除确认回执允许发布 resource_released;每个逻辑资源只发布一次。 + entry.confirmed_release = ReleaseReceipt( + sandbox_id=entry.receipt.id, + source=source, + confirmed_at=time(), + confirmation="get_404" if self.sandbox_cfg.backend == "opensandbox" else "gateway_delete_ack", + ) + observation = current_observation() + if observation: + observation.emit( + "resource_released", resource_name=name, operation_id=entry.op_id, **asdict(entry.confirmed_release) + ) + + async def _close(self, body_error: BaseException | None = None) -> None: + execution_error, execution_cancel = find_error_execution(body_error) + if self._close_task is None: + self._close_task = asyncio.Task(self.cleanup_sandbox_runtime(), loop=asyncio.get_running_loop()) + cleanup_outcome, wait_cancel = await finish_owned(self._close_task) + resolve_result_sandbox_exit(execution_error, execution_cancel, cleanup_outcome, wait_cancel) + + @observe_phase("sandbox/cleanup") + async def cleanup_sandbox_runtime(self) -> None: + """Collect each resource independently, close local owners, then decide isolation.""" + loop = asyncio.get_running_loop() + deadline = loop.time() + self.budgets.cleanup + entries = self._creates # _close_task has sealed acquire and new jobs. + delete_outcomes_by_id: dict[str, DeleteOutcome] = { + entry.receipt.id: None + for entry in entries.values() + if isinstance(entry.receipt, _Known) and entry.confirmed_release is not None + } + operation_errors: ErrorRecords = [] + unconfirmed_closes: ErrorRecords = [] + resource_batch = asyncio.gather( + *( + self.cleanup_sandbox_resource(entry, deadline, delete_outcomes_by_id, operation_errors) + for entry in entries.values() + ), + return_exceptions=True, + ) + timed_out = False + try: + _, pending = await asyncio.wait({resource_batch}, timeout=max(0, deadline - loop.time())) + timed_out = bool(pending) + except BaseException as wait_error: + operation_errors.append(("resource/wait", wait_error)) + finally: + # Expiration ends only the wait. Every item still collects its own + # original POST/DELETE; A's DELETE never waits for B's POST barrier. + for name, outcome in zip(entries, await resource_batch): + if isinstance(outcome, BaseException): + unconfirmed_closes.append((f"resource/{name}", outcome)) + for name, entry in entries.items(): + if sandbox_release_status(entry, delete_outcomes_by_id) == "DELETED": + try: + self._confirm_release(name, entry, "close") + except BaseException as confirm_error: + operation_errors.append((f"release/report/{name}", confirm_error)) + job_closes = [(job.id, asyncio.create_task(job.close())) for job in self._jobs] + for job_id, close_task in job_closes: + try: + launch_error = await close_task + except BaseException as job_close_error: + unconfirmed_closes.append((f"job/{job_id}", job_close_error)) + else: + if launch_error is not None: + operation_errors.append((f"launch/{job_id}", launch_error)) + try: + async with asyncio.timeout(2): + await self.client.aclose() + except BaseException as client_close_error: + # No connection-pool close acknowledgement: this alone must propagate. + unconfirmed_closes.append(("client/aclose", client_close_error)) + cleanup_report_written = False + try: + cleanup_report_written = self._report_cleanup( + delete_outcomes_by_id, operation_errors + unconfirmed_closes, timed_out + ) + except BaseException as report_error: + operation_errors.append(("report", report_error)) + errors = self.find_error_sandbox_cleanup(delete_outcomes_by_id, operation_errors, unconfirmed_closes) + self.cleanup_failure = self.resolve_result_sandbox_runtime( + errors, delete_outcomes_by_id, unconfirmed_closes, timed_out, cleanup_report_written + ) + + async def cleanup_sandbox_resource( + self, + entry: _CreateEntry, + deadline: float, + delete_outcomes_by_id: dict[str, DeleteOutcome], + operation_errors: ErrorRecords, + ) -> None: + original_create = entry.task + loop = asyncio.get_running_loop() + if entry.release_task is not None: + await asyncio.wait({entry.release_task}, timeout=max(0, deadline - loop.time())) + release_error = await cleanup_owned_task(entry.release_task) + if release_error is not None: + operation_errors.append((f"release/{entry.name}", release_error)) + if entry.confirmed_release is not None: + assert isinstance(entry.receipt, _Known) + delete_outcomes_by_id[entry.receipt.id] = None + if entry.receipt == "UNKNOWN" and not original_create.done(): + seconds = max(0, min(self.budgets.create_rpc, deadline - loop.time())) + try: + await asyncio.wait({original_create}, timeout=seconds) + except BaseException as create_wait_error: + operation_errors.append((f"create/wait/{entry.name}", create_wait_error)) + task_error = await cleanup_owned_task(original_create) + if entry.ready_cancelled_for_release and isinstance(task_error, asyncio.CancelledError): + task_error = None # readiness 的取消由本次显式释放发出,且原任务已收回。 + create_error = find_error_original_task( + task_error, + seen_by_caller=entry.error_observed and entry.receipt != "UNKNOWN", + ) + if create_error is not None and not any(error is create_error for _, error in operation_errors): + operation_errors.append((f"create/{entry.name}", create_error)) + if not isinstance(entry.receipt, _Known) or entry.receipt.id in delete_outcomes_by_id: + return + sandbox_id = entry.receipt.id + delete_outcomes_by_id[sandbox_id] = "NO_ACK" # Claim once, before the first DELETE await. + seconds_left = deadline - loop.time() + if seconds_left <= 0: + delete_outcomes_by_id[sandbox_id] = "NO_TIME" + return + try: + previous = self._delete_tasks_by_id.get(sandbox_id) + if previous is not None: + outcome, wait_cancel = await finish_owned(previous) + if wait_cancel is not None: + operation_errors.append((f"delete/wait/{sandbox_id}", wait_cancel)) + if isinstance(outcome, BaseException): + operation_errors.append((f"delete/{sandbox_id}", outcome)) + elif outcome is None: + delete_outcomes_by_id[sandbox_id] = None + return + seconds_left = deadline - loop.time() + if seconds_left <= 0: + delete_outcomes_by_id[sandbox_id] = "NO_TIME" + return + self._delete_tasks_by_id[sandbox_id] = asyncio.Task( + self.client.delete(sandbox_id, timeout=seconds_left), loop=loop + ) + outcome, wait_cancel = await finish_owned(self._delete_tasks_by_id[sandbox_id]) + if wait_cancel is not None: + operation_errors.append((f"delete/wait/{sandbox_id}", wait_cancel)) + if isinstance(outcome, BaseException): + operation_errors.append((f"delete/{sandbox_id}", outcome)) + else: + delete_outcomes_by_id[sandbox_id] = outcome + except BaseException as delete_error: + operation_errors.append((f"delete/{sandbox_id}", delete_error)) + + def find_error_sandbox_cleanup( + self, + delete_outcomes_by_id: dict[str, DeleteOutcome], + operation_errors: ErrorRecords, + unconfirmed_closes: ErrorRecords, + ) -> ErrorRecords: + records = operation_errors + unconfirmed_closes + for entry in self._creates.values(): + if sandbox_release_status(entry, delete_outcomes_by_id) == "UNCONTAINED": + assert isinstance(entry.receipt, _Known) + records.append((entry.op_id, RuntimeError(f"{entry.receipt.id}: no delete receipt or expiry"))) + return records + + def resolve_result_sandbox_runtime( + self, + error_records: ErrorRecords, + delete_outcomes_by_id: dict[str, DeleteOutcome], + unconfirmed_closes: ErrorRecords, + timed_out: bool, + cleanup_report_written: bool, + ) -> Failure | None: + if not error_records: + statuses = [sandbox_release_status(entry, delete_outcomes_by_id) for entry in self._creates.values()] + if self.require_clean_exit and ( + timed_out + or not cleanup_report_written + or any(status not in ("REJECTED", "DELETED") for status in statuses) + ): + if unconfirmed_closes or any(status in ("UNKNOWN", "UNCONTAINED") for status in statuses): + raise RuntimeError("sandbox isolation unconfirmed") + # TTL 仅证明隔离,不是删除回执;严格退出不能交付原评分。 + return Failure( + "SANDBOX_CLEANUP_UNCONFIRMED", "cleanup", "sandbox deletion or cleanup report unconfirmed" + ) + return None + errors = [error for _, error in error_records] + cleanup_error = errors[0] if len(errors) == 1 else BaseExceptionGroup("sandbox cleanup", errors) + try: + for source, error in error_records: + ordinary = error.subgroup(Exception) if isinstance(error, BaseExceptionGroup) else error + if not isinstance(ordinary, Exception): + continue + record_production_exception( + ordinary, + phase="sandbox/cleanup", + ctx=self.ctx, + command_ids=self.command_ids, + request_ids=self.observed_request_ids, + isolation=self._cleanup_log_fields(delete_outcomes_by_id, unconfirmed_closes, source), + ) + except BaseException as logging_error: + raise BaseExceptionGroup("cleanup and logging", [cleanup_error, logging_error]) from None + all_creates_accounted_for = all( + sandbox_release_status(entry, delete_outcomes_by_id) in ("REJECTED", "DELETED", "TTL") + for entry in self._creates.values() + ) + if self.ctx.fail_fast or not isinstance(cleanup_error, Exception): + raise cleanup_error + if unconfirmed_closes or not all_creates_accounted_for: + raise cleanup_error + return Failure("TRIAL_CLEANUP_EXCEPTION", "cleanup", str(cleanup_error)) + + def _cleanup_log_fields( + self, + delete_outcomes_by_id: dict[str, DeleteOutcome], + unconfirmed_closes: ErrorRecords, + source: str, + ) -> dict[str, Any]: + # Preserve the existing ERROR schema, deriving it from the same receipts + # used by cleanup reports and the Runtime's policy decision. + statuses = { + entry.op_id: sandbox_release_status(entry, delete_outcomes_by_id) for entry in self._creates.values() + } + accounted = {op for op, status in statuses.items() if status in ("REJECTED", "DELETED", "TTL")} + return { + "source": source, + "local_work_settled": not unconfirmed_closes, + "unsettled_local": [owner for owner, _ in unconfirmed_closes], + "ledger_complete": True, + "registered_ops": sorted(statuses), + "accounted_ops": sorted(accounted), + "unaccounted_ops": sorted(statuses.keys() - accounted), + "rejected_ops": sorted(op for op, status in statuses.items() if status == "REJECTED"), + **{ + key: { + entry.op_id: entry.receipt.id + for entry in self._creates.values() + if isinstance(entry.receipt, _Known) and statuses[entry.op_id] == status + } + for key, status in (("deleted_ops", "DELETED"), ("ttl_ops", "TTL")) + }, + } + + def _report_cleanup( + self, + delete_outcomes_by_id: dict[str, DeleteOutcome], + error_records: ErrorRecords, + timed_out: bool, + ) -> bool: + """Only confirmed deletes enter deleted_ids; client close cannot certify them.""" + confirmed = {sid for sid, outcome in delete_outcomes_by_id.items() if outcome is None} + remaining_ids = sorted( + { + e.receipt.id + for e in self._creates.values() + if isinstance(e.receipt, _Known) and sandbox_release_status(e, delete_outcomes_by_id) != "DELETED" + } + ) + unresolved_creates = { + name: e.op_id + for name, e in self._creates.items() + if sandbox_release_status(e, delete_outcomes_by_id) == "UNKNOWN" + } + timed_out = timed_out or any( + outcome == "NO_TIME" or isinstance(outcome, Failure) and outcome.code == "DELETE_FAILED" + for outcome in delete_outcomes_by_id.values() + ) + errors = ["sandbox cleanup timed out"] if timed_out else [] + errors.extend( + f"delete({sid}): {outcome.code}: {outcome.detail}" + for sid, outcome in delete_outcomes_by_id.items() + if isinstance(outcome, Failure) and outcome.code != "DELETE_FAILED" + ) + errors.extend(f"{source}: {type(error).__name__}: {error}" for source, error in error_records) + path = self.ctx.output_dir / "cleanup.json" + payload = json.dumps( + { + "applied_resources": {name: e.resources.to_dict() for name, e in self._creates.items()}, + "remaining_ids": remaining_ids, + "unresolved_creates": unresolved_creates, + "errors": errors, + "delete_outcomes": { + sid: asdict(outcome) if isinstance(outcome, Failure) else outcome + for sid, outcome in delete_outcomes_by_id.items() + }, + "release_status": { + name: sandbox_release_status(entry, delete_outcomes_by_id) for name, entry in self._creates.items() + }, + "released_resources": { + name: asdict(entry.confirmed_release) + for name, entry in self._creates.items() + if entry.confirmed_release is not None + }, + } + ) + diagnostic_path = None + try: + path.write_text(payload) + except OSError as exc: + logger.warning( + "Sandbox cleanup diagnostic write failed sid=%s remaining=%s unresolved_creates=%s: %s", + self.ctx.session_id, + remaining_ids, + unresolved_creates, + exc, + ) + else: + diagnostic_path = str(path) + observation = current_observation() + if observation: + observation.emit( + "cleanup_finished", + deleted_ids=sorted(confirmed), + remaining_ids=remaining_ids, + unknown_creates=list(unresolved_creates.values()), + errors=errors, + diagnostic_path=diagnostic_path, + ) + if remaining_ids or unresolved_creates or errors: + logger.warning( + "Sandbox cleanup incomplete (relies on sandbox_ttl=%ss): session=%s remaining=%s unknown_creates=%s errors=%s", + self.budgets.sandbox_ttl, + self.ctx.session_id, + remaining_ids, + unresolved_creates, + errors, + ) + return diagnostic_path is not None + + @observe_phase("workspace/prepare", failure=Failure) + async def prepare( + self, + resource: ResourceHandle, + *, + workspace: str, + public_bundle: str | None = None, + setup: CommandSpec | None = None, + services: Mapping[str, str] = {}, + ) -> PreparedWorkspace | Failure: + if setup is None: + if public_bundle is not None: + raise ValueError("setup=None requires public_bundle=None") + ws_err = await self._ensure_workspace_exists(resource, workspace) + if isinstance(ws_err, Failure): + return ws_err + return PreparedWorkspace(resource, workspace) + + job = self._new_job(resource, "setup") + public_dir: str | None = None if public_bundle is None else f"{job.directory}/public" + staged = await self._stage_command( + job, + setup, + workspace=workspace, + public_dir=public_dir, + services=services, + ) + if isinstance(staged, Failure): + return staged + argv, cwd, env = staged + if public_bundle is not None: + assert public_dir is not None + unpacked = await self._unpack_bundle(resource, public_bundle, public_dir) + if isinstance(unpacked, Failure): + return unpacked + + rc_files = await self._run_job(job, argv, cwd=cwd, env=env, timeout=self.budgets.attempt, outputs=()) + if isinstance(rc_files, Failure): + return rc_files + rc, _ = rc_files + if rc != 0: + return Failure("SETUP_FAILED", "setup", f"{job.id} rc={rc}") + return PreparedWorkspace(resource, workspace) + + @observe_phase("verification/run", failure=Failure) + async def verify( + self, + resource: ResourceHandle, + *, + command: CommandSpec, + outputs: Sequence[str], + workspace: str | None = None, + services: Mapping[str, str] = {}, + inputs: Mapping[str, bytes] | None = None, + ) -> GradeEvidence | Failure: + blobs = inputs or {} + if blobs: + validate_file_bindings((), blobs.keys(), command) + digests = {dest: hashlib.sha256(blob).hexdigest() for dest, blob in blobs.items()} + job = self._new_job(resource, "grader") + if blobs: + (self.ctx.output_dir / "verification_inputs.json").write_text( + json.dumps( + { + "sandbox": resource.name, + "job_id": job.id, + "input_sha256": digests, + } + ) + ) + staged = await self._stage_command( + job, + command, + workspace=workspace, + public_dir=None, + services=services, + extra_files=blobs, + ) + if isinstance(staged, Failure): + return staged + argv, cwd, env = staged + job_out = await self._run_job(job, argv, cwd=cwd, env=env, timeout=self.budgets.verifier, outputs=outputs) + if isinstance(job_out, Failure): + return job_out + rc, files = job_out + return GradeEvidence(return_code=rc, files=files, input_sha256=digests) + + async def _ensure_workspace_exists(self, resource: ResourceHandle, workspace: str) -> Failure | None: + """无 setup 命令时确认任务镜像内已预置目标工作区目录。""" + chk = await self.client.exec( + resource, + f"test -d {shlex.quote(workspace)}", + cwd="/tmp", + timeout=self.budgets.command or 300.0, + ) + if isinstance(chk, Failure): + return chk + return None if chk.return_code == 0 else Failure("WORKSPACE_MISSING", "setup", workspace) + + def _new_job(self, resource: ResourceHandle, kind: JobKind) -> Job: + if self._close_task is not None: + raise asyncio.CancelledError() + jid: str = uuid4().hex + rec = self._job_type( + id=jid, + resource=resource, + kind=kind, + directory=f"/private/jobs/{jid}", + client=self.client, + budgets=self.budgets, + output_dir=self.ctx.output_dir, + session_id=self.ctx.session_id, + ) + self._jobs.append(rec) + observation = current_observation() + if observation: + observation.emit( + "job_created", + job_id=jid, + kind=kind, + sandbox_id=resource.id, + remote_directory=rec.directory, + output_dir=str(self.ctx.output_dir), + ) + return rec + + @staticmethod + def _resolve_arg( + arg: CmdArg, + *, + task_dir: str, + result_dir: str, + workspace: str | None, + public_dir: str | None, + services: Mapping[str, str], + ) -> str: + """将显式 RuntimeRef 解析为运行期实际路径或 URL;普通字符串原样返回,不做模板插值。""" + if isinstance(arg, str): + return arg + ref = arg["ref"] + if ref == "task_dir": + return task_dir + if ref == "result_dir": + return result_dir + if ref == "workspace": + if workspace is None: + raise ValueError("CommandSpec references xt.WORKSPACE but workspace is None") + return workspace + if ref == "public_dir": + if public_dir is None: + raise ValueError("CommandSpec references xt.PUBLIC_DIR but public_bundle is None") + return public_dir + if ref == "service": + svc_name: str | None = arg.get("name") + if not svc_name or svc_name not in services: + raise ValueError(f"CommandSpec references unknown service {svc_name!r}") + return services[svc_name] + raise ValueError(f"unsupported RuntimeRef: {arg!r}") + + async def _mkdir( + self, + resource: ResourceHandle, + dirs: Sequence[str], + *, + mode: str | None = None, + code: str, + phase: str, + ) -> Failure | None: + """一次远程命令批量创建目录;指定 mode(如 '700')时同步锁紧权限。""" + cmd_str: str = (f"install -d -m {mode} " if mode is not None else "mkdir -p ") + shlex.join(dirs) + out = await self.client.exec(resource, cmd_str, cwd="/tmp", timeout=self.budgets.request) + if isinstance(out, Failure): + return out + return None if out.return_code == 0 else Failure(code, phase, out.stderr) + + async def _stage_command( + self, + job: Job, + command: CommandSpec, + *, + workspace: str | None, + public_dir: str | None, + services: Mapping[str, str], + extra_files: Mapping[str, bytes] = {}, + ) -> tuple[list[str], str, dict[str, str]] | Failure: + resolved = self.resolve_command(job, command, workspace=workspace, public_dir=public_dir, services=services) + failure = await self.stage_command_materials(job, command, extra_files=extra_files) + return failure if isinstance(failure, Failure) else resolved + + def resolve_command( + self, + job: Job, + command: CommandSpec, + *, + workspace: str | None, + public_dir: str | None, + services: Mapping[str, str], + ) -> tuple[list[str], str, dict[str, str]] | Failure: + task_dir: str = f"{job.directory}/task" + result_dir: str = f"{job.directory}/results" + raw_argv: list[CmdArg] = command["argv"] + if not raw_argv: + raise ValueError("CommandSpec requires non-empty argv") + + # 先解析所有显式 RuntimeRef:若引用了不存在的服务或 public_bundle=None,在远程上传前即立刻抛 ValueError。 + raw_cwd: str = self._resolve_arg( + command["cwd"], + task_dir=task_dir, + result_dir=result_dir, + workspace=workspace, + public_dir=public_dir, + services=services, + ) + if not raw_cwd: + raise ValueError("CommandSpec requires non-empty cwd") + cwd: str = raw_cwd if PurePosixPath(raw_cwd).is_absolute() else str(PurePosixPath(task_dir) / raw_cwd) + + argv: list[str] = [ + self._resolve_arg( + arg, + task_dir=task_dir, + result_dir=result_dir, + workspace=workspace, + public_dir=public_dir, + services=services, + ) + for arg in raw_argv + ] + env: dict[str, str] = { + k: self._resolve_arg( + v, + task_dir=task_dir, + result_dir=result_dir, + workspace=workspace, + public_dir=public_dir, + services=services, + ) + for k, v in command["env"].items() + } + + return argv, cwd, env + + async def stage_command_materials( + self, + job: Job, + command: CommandSpec, + *, + extra_files: Mapping[str, bytes] = {}, + ) -> Failure | None: + """Stage once after all RuntimeRefs resolve; failed uploads are not replayed. + + Private grader callers still own the tool/model barrier before invoking + this method. It does not grant permission to upload private materials. + """ + task_dir = f"{job.directory}/task" + result_dir = f"{job.directory}/results" + all_dirs: list[str] = list( + dict.fromkeys( + ( + "/private", + "/private/jobs", + job.directory, + task_dir, + result_dir, + *( + str(PurePosixPath(f"{task_dir}/{rel_target}").parent) + for rel_target in [*command["files"], *extra_files] + ), + ) + ) + ) + mk_err = await self._mkdir(job.resource, all_dirs, mode="700", code="COMMAND_SETUP_FAILED", phase=job.kind) + if isinstance(mk_err, Failure): + return mk_err + + if command["bundle"] is not None: + unpacked = await self._unpack_bundle(job.resource, command["bundle"], task_dir) + if isinstance(unpacked, Failure): + return unpacked + + for rel_target, host_src in command["files"].items(): + up = await self.client.upload( + job.resource, + f"{task_dir}/{rel_target}", + Path(host_src).read_bytes(), + timeout=self.budgets.request, + ) + if isinstance(up, Failure): + return up + + for rel_target, blob in extra_files.items(): + up = await self.client.upload(job.resource, f"{task_dir}/{rel_target}", blob, timeout=self.budgets.request) + if isinstance(up, Failure): + return up + + return None + + @observe_phase("runtime/upload_unpack", failure=Failure) + async def _unpack_bundle(self, resource: ResourceHandle, host_tar: str, dest_dir: str) -> Failure | None: + remote_tar: str = f"/tmp/{uuid4().hex}.tar" + up = await self.client.upload(resource, remote_tar, Path(host_tar).read_bytes(), timeout=self.budgets.request) + if isinstance(up, Failure): + return up + unpack_cmd: str = ( + f"mkdir -p {shlex.quote(dest_dir)} && " + f"tar -xf {shlex.quote(remote_tar)} -C {shlex.quote(dest_dir)} && " + f"rm -f {shlex.quote(remote_tar)}" + ) + out = await self.client.exec( + resource, + unpack_cmd, + cwd="/tmp", + timeout=self.budgets.command or 300.0, + ) + if isinstance(out, Failure): + return out + return None if out.return_code == 0 else Failure("UNPACK_FAILED", "setup", out.stderr) + + @observe_phase("tools/stop", failure=Failure) + async def _stop_jobs(self, *, timeout: float, kinds: set[JobKind] | None = None) -> Failure | None: + try: + async with asyncio.timeout(timeout): + unconfirmed: list[str] = [] + for job in self._jobs: + if kinds is not None and job.kind not in kinds: + continue + stopped = await job.stop(timeout) + if isinstance(stopped, Failure): + unconfirmed.append(job.id) + return Failure("STOP_UNCONFIRMED", "stop", ",".join(unconfirmed)) if unconfirmed else None + except TimeoutError: + return Failure("STOP_UNCONFIRMED", "stop", "job stop timed out") + + async def _execute_job( + self, + job: Job, + argv: Sequence[str], + *, + cwd: str, + env: Mapping[str, str], + timeout: float, + outputs: Sequence[str], + ) -> tuple[int, dict[str, bytes]] | Failure: + try: + # This range owns launch, PID handoff, every poll and collection. + async with asyncio.timeout(timeout) as scope: + started = await job.start(argv, cwd=cwd, env=env, timeout=timeout) + if isinstance(started, Failure): + return started + rc = await self._wait_job(job, timeout) + if isinstance(rc, Failure): + return rc + return await job.collect(outputs) + except TimeoutError: + if not scope.expired(): + # Job 计时器未到期,内层超时不是本层的 JOB_TIMEOUT 回执。 + raise + # 本 Job 计时器确已到期,只能记录超时;原 Job 的停止仍由上层收回。 + return Failure("JOB_TIMEOUT", "job", job.id) + + async def start_service( + self, + resource: ResourceHandle, + *, + command: CommandSpec, + port: int, + ready: Sequence[str], + services: Mapping[str, str] = {}, + workspace: str | None = None, + ) -> str | Failure: + if not ready: + raise ValueError("service ready probe argv must not be empty") + job = self._new_job(resource, "service") + staged = await self._stage_command(job, command, workspace=workspace, public_dir=None, services=services) + if isinstance(staged, Failure): + return staged + argv, cwd, env = staged + started = await job.start(argv, cwd=cwd, env=env, timeout=self.budgets.attempt) + if isinstance(started, Failure): + return started + return await self._wait_service_ready(resource, port=port, ready=ready, cwd=cwd, env=env) + + @observe_phase("agent/run", failure=Failure) + async def run_agent( + self, + workspace: PreparedWorkspace, + instruction: str, + *, + outputs: Sequence[str] = (), + ) -> AgentResult | Failure: + """运行 mini_agent -> 确认进程停止 -> 排空并结算模型会话 -> 快照工作区产物。""" + validate_file_bindings(outputs) + job = self._new_job(workspace.resource, "agent") + try: + # 一个范围覆盖 worker 准备、运行与报告收集;各 RPC 仍可有更短的超时。 + async with asyncio.timeout(self.budgets.agent) as scope: + report = await self._run_worker(job, workspace, instruction) + except TimeoutError: + if not scope.expired(): + # 宿主 Agent 计时器未到期,应保留内层超时的原来源。 + raise + # 宿主预算确已到期,且原 Job 已走完停止,允许报告 AGENT_TIMEOUT。 + return Failure("AGENT_TIMEOUT", "agent", job.id) + if isinstance(report, Failure): + return report + + stopped = await self._stop_jobs(kinds={"agent"}, timeout=10.0) + if isinstance(stopped, Failure): + return stopped + + # 已确认工具停止,再取得模型会话结算回执,才能放行私有验证材料。 + await self.ctx.finish_session() + + snapshots = await self._snapshot_outputs(workspace, outputs) + if isinstance(snapshots, Failure): + return snapshots + return AgentResult(report=report, artifacts=snapshots) + + @observe_phase("service/ready", failure=Failure) + async def _wait_service_ready( + self, + resource: ResourceHandle, + *, + port: int, + ready: Sequence[str], + cwd: str, + env: Mapping[str, str], + ) -> str | Failure: + """Repeat readiness reads only; service launch remains owned and runs once.""" + """解析对外服务地址并轮询服务容器内的就绪探测命令。""" + try: + async with asyncio.timeout(self.budgets.attempt): + endpoint = await self.client.resolve_endpoint(resource, port, timeout=self.budgets.request) + if isinstance(endpoint, Failure): + return endpoint + + probe_cmd: str = shell_command(env, ready) + while True: + res = await self.client.exec( + resource, + probe_cmd, + cwd=cwd, + timeout=6.0, + ) + if not isinstance(res, Failure) and res.return_code == 0: + return endpoint + await asyncio.sleep(1.0) + except TimeoutError: + return Failure("SERVICE_NOT_READY", "service", resource.name) + + async def _configure_worker_access(self, job: Job, workspace: str, tool_user: str) -> Failure | None: + """按需创建受限工具用户、锁紧 0700 私有控制目录,并将公开工作区归属权授予工具用户。""" + tool_home: str = self.tool_env.get("HOME", f"/home/{tool_user}") + user_q: str = shlex.quote(tool_user) + init_cmd: str = ( + f"set -e; id {user_q} >/dev/null 2>&1 || useradd -m -U -d {shlex.quote(tool_home)} {user_q}; " + f"install -d -m 700 /private /private/jobs {shlex.quote(job.directory)}; " + f"chown -R {shlex.quote(f'{tool_user}:{tool_user}')} {shlex.quote(workspace)}" + ) + init_out = await self.client.exec(job.resource, init_cmd, cwd="/tmp", timeout=self.budgets.request) + if isinstance(init_out, Failure): + return init_out + return None if init_out.return_code == 0 else Failure("WORKER_SETUP_FAILED", "worker", init_out.stderr) + + async def _capture_tool_environment(self, workspace: PreparedWorkspace) -> dict[str, str] | Failure: + """Read the task image's environment before SDK installation or private HOME. + + The recipe selects its task environment explicitly. Use a direct client + read so full environment values never become stdout artifacts or logs; + shell_command removes the platform exec token before the capture. + """ + result = await self.client.exec( + workspace.resource, + shell_command({}, self.tool_env_command), + cwd=workspace.path, + timeout=self.budgets.request, + ) + if isinstance(result, Failure): + return result + if result.return_code: + return Failure("TOOL_ENVIRONMENT_FAILED", "prepare", result.stderr[-2000:]) + try: + environment = dict(entry.split("=", 1) for entry in result.stdout.split("\0") if entry) + except ValueError as exc: + return Failure("TOOL_ENVIRONMENT_INVALID", "prepare", str(exc)) + return {**environment, **self.tool_env, "PWD": workspace.path} + + async def _prepare_worker_files( + self, + job: Job, + workspace: PreparedWorkspace, + instruction: str, + tool_environment: dict[str, str], + ) -> tuple[str, str, str] | Failure: + """Deploy the offline runtime and private credentials/request once. + + The task environment is already captured. Private model keys remain + file-backed and are never part of the environment supplied to tools. + """ + res: ResourceHandle = workspace.resource + if self.harness.runtime_archive is not None: + installed = await self._unpack_bundle(res, self.harness.runtime_archive, self.harness.runtime_dir) + if isinstance(installed, Failure): + return installed + + if self.tool_user is not None: + access_err = await self._configure_worker_access(job, workspace.path, self.tool_user) + else: + access_err = await self._mkdir( + res, + ("/private", "/private/jobs", job.directory), + mode="700", + code="WORKER_SETUP_FAILED", + phase="worker", + ) + if isinstance(access_err, Failure): + return access_err + + model_cfg: ma.ModelSettings = self.ctx.model + if model_cfg.api_key_file is not None: + remote_key: str = f"{job.directory}/model-key" + up_key = await self.client.upload( + res, + remote_key, + Path(model_cfg.api_key_file).read_bytes(), + timeout=self.budgets.request, + ) + if isinstance(up_key, Failure): + return up_key + model_cfg = replace(model_cfg, api_key_file=remote_key) + + worker_req = ma.WorkerRequest( + workspace=workspace.path, + instruction=instruction, + harness=self.harness, + model=model_cfg, + limits=ma.HarnessLimits( + agent_seconds=self.budgets.agent, + request_seconds=( + self.budgets.model_request if self.budgets.model_request is not None else self.budgets.request + ), + command_seconds=self.budgets.command, + max_turns=self.max_turns, + ), + tool_user=self.tool_user, + tool_env=tool_environment, + trace_carrier=otel.current_carrier() if current_observation() else {}, + ) + req_path: str = f"{job.directory}/request.json" + res_path: str = f"{job.directory}/result.json" + fatal_path: str = f"{job.directory}/worker-fatal.txt" + up_req = await self.client.upload( + res, + req_path, + json.dumps(asdict(worker_req)).encode(), + timeout=self.budgets.request, + ) + if isinstance(up_req, Failure): + return up_req + + return req_path, res_path, fatal_path + + async def _run_worker( + self, + job: Job, + workspace: PreparedWorkspace, + instruction: str, + ) -> ma.AgentReport | Failure: + environment = await self._capture_tool_environment(workspace) + if isinstance(environment, Failure): + return environment + prepared = await self._prepare_worker_files(job, workspace, instruction, environment) + if isinstance(prepared, Failure): + return prepared + req_path, res_path, fatal_path = prepared + observation = current_observation() + worker_env = dict(self.harness.env) + if observation is not None and observation.directory is not None: + worker_env["MINI_AGENT_OBSERVABILITY"] = "1" + job_rc = None + try: + job_out = await self._run_job( + job, + ( + self.harness.python, + "-I", + "-m", + "mini_agent.worker", + "--request", + req_path, + "--result", + res_path, + "--fatal", + fatal_path, + ), + cwd=job.directory, + env=worker_env, + timeout=self.budgets.agent, + outputs=(), + ) + if isinstance(job_out, Failure): + return job_out + job_rc, _ = job_out + return await self._collect_worker_report( + job, job_rc, res_path=res_path, fatal_path=fatal_path, timeout=self.budgets.request + ) + except BaseException as exc: + if not isinstance(exc, asyncio.CancelledError) and not ( + isinstance(exc, BaseExceptionGroup) and exc.subgroup(asyncio.CancelledError) is not None + ): + raise + # 原 Job 已交回取消及停止错误,退出 Runtime 前仍收回 worker 的 fatal 回执。 + diagnostic, deferred = await finish_owned( + asyncio.create_task( + self._collect_worker_diagnostic(job, job_rc, fatal_path=fatal_path, timeout=self.budgets.request) + ) + ) + errors = [error for error in (exc, deferred, diagnostic) if isinstance(error, BaseException)] + if isinstance(diagnostic, Failure): + logger.warning( + "Worker diagnostic unavailable sid=%s job=%s: %s", self.ctx.session_id, job.id, diagnostic + ) + # fatal 只说明 worker 独立故障,不能覆盖宿主取消或原停止错误。 + raise errors[0] if len(errors) == 1 else BaseExceptionGroup("worker cancellation and diagnostics", errors) + + async def _collect_worker_report( + self, + job: Job, + job_rc: int, + *, + res_path: str, + fatal_path: str, + timeout: float, + ) -> ma.AgentReport | Failure: + """按 worker-fatal.txt -> 非零退出码 -> result.json 顺序收集报告;崩溃默认落盘诊断并转单样本 Failure。""" + diagnostic = await self._collect_worker_diagnostic(job, job_rc, fatal_path=fatal_path, timeout=timeout) + if isinstance(diagnostic, WorkerCrashError): + if self.ctx.fail_fast or self.fail_fast_on_worker_crash: + raise diagnostic + logger.error("sid=%s %s", self.ctx.session_id, diagnostic) + return Failure("WORKER_CRASH", "worker", str(diagnostic).partition("\n")[0]) + if isinstance(diagnostic, Failure): + return diagnostic + + payload = await self.client.download(job.resource, res_path, timeout=timeout) + if isinstance(payload, Failure): + return payload + if payload is None: + return Failure("RESULT_MISSING", "worker", job.id) + envelope = ma.decode_worker_envelope(payload) + record_worker_observation(envelope.observation, job_id=job.id, sandbox_id=job.resource.id) + if isinstance(envelope.result, ma.AgentReport): + self.observed_request_ids = envelope.result.observed_request_ids + return envelope.result + + async def _collect_worker_diagnostic( + self, job: Job, job_rc: int | None, *, fatal_path: str, timeout: float + ) -> WorkerCrashError | Failure | None: + # 只用取消前已收取的退出码判故障;主动停止后的非零 rc 仅作诊断展示。 + fatal_bytes = await self.client.download(job.resource, fatal_path, timeout=timeout) + if isinstance(fatal_bytes, bytes) or (job_rc is not None and job_rc != 0): + if isinstance(fatal_bytes, bytes): + diag_text: str = fatal_bytes.decode(errors="replace") + else: + diag_text = await job.diagnostic() + diag_file: Path = self.ctx.output_dir / f"worker-{job.id}.fatal.txt" + known_rc = job_rc if job_rc is not None else job.return_code + msg = f"WORKER_CRASH ({job.id}, exit={known_rc})" + try: + diag_file.write_text(f"exit={known_rc}\n{diag_text}") + except OSError as exc: + logger.warning("Worker diagnostic write failed sid=%s job=%s: %s", self.ctx.session_id, job.id, exc) + else: + msg += f"; see {diag_file}" + # 已读到 fatal 或真实非零退出码,保留原诊断;取消路径不在这里降级。 + return WorkerCrashError(f"{msg}\n{diag_text}") + return fatal_bytes if isinstance(fatal_bytes, Failure) else None + + @observe_phase("artifacts/snapshot", failure=Failure) + async def _snapshot_outputs( + self, workspace: PreparedWorkspace, outputs: Sequence[str] + ) -> dict[str, str] | Failure: + files, hashes = {}, {} + for src in outputs: + blob = await self.client.download( + workspace.resource, f"{workspace.path}/{src}", timeout=self.budgets.request + ) + if isinstance(blob, Failure): + return blob + if blob is None: + return Failure("ARTIFACT_MISSING", "snapshot", src) + dest = self.ctx.output_dir / "snapshot" / src + dest.parent.mkdir(exist_ok=True, parents=True) + dest.write_bytes(blob) + files[src], hashes[src] = str(dest), hashlib.sha256(blob).hexdigest() + if outputs: + (self.ctx.output_dir / "snapshot_sha256.json").write_text(json.dumps(hashes)) + return files + + @observe_job + async def _run_job( + self, + job: Job, + argv: Sequence[str], + *, + cwd: str, + env: Mapping[str, str], + timeout: float, + outputs: Sequence[str], + ) -> tuple[int, dict[str, bytes]] | Failure: + execution_error = None + try: + outcome = await self._execute_job(job, argv, cwd=cwd, env=env, timeout=timeout, outputs=outputs) + except BaseException as exc: + execution_error = exc + finally: + stopped, deferred = await finish_owned(asyncio.create_task(job.stop_on_exit(timeout=10))) + stop_error = stopped if isinstance(stopped, BaseException) else None + # 已收到执行、停止等待和原停止三份结果,独立停止错误不能覆盖取消。 + errors = [error for error in (execution_error, deferred, stop_error) if error is not None] + if errors: + raise errors[0] if len(errors) == 1 else BaseExceptionGroup("job execution and stop", errors) + if ( + isinstance(outcome, Failure) + and outcome.code == "JOB_TIMEOUT" + and isinstance(stopped, Failure) + and stopped.code == "STOP_UNCONFIRMED" + ): + logger.warning( + "Sandbox job sid=%s job=%s native_command_id=%s: %s followed by %s", + self.ctx.session_id, + job.id, + job.command_id, + outcome, + stopped, + ) + return stopped if isinstance(stopped, Failure) else outcome + + async def _wait_job(self, job: Job, timeout: float) -> int | Failure: + """Runtime owns cross-service health; Job owns its original command. + + A failed service can end this wait. Cancelling a waiter does not certify + that its command stopped; the lifecycle owner still performs cleanup. + """ + """Runtime owns service linkage; a Job only observes its own command.""" + waiting = asyncio.create_task(job.wait(timeout)) + try: + while True: + for service in self._jobs: + if service.kind != "service": + continue + health = await service.check_health() + if isinstance(health, Failure): + record_job_finished(self.ctx.output_dir, service, asdict(health)) + return health + done, _ = await asyncio.wait({waiting}, timeout=1.0) + if done: + return waiting.result() + finally: + if not waiting.done(): + waiting.cancel() + await asyncio.gather(waiting, return_exceptions=True) + + +def validate_file_bindings(sources, targets=(), command: CommandSpec | None = None): + targets = set(targets) + for name in [*sources, *targets]: + path = PurePosixPath(name) + if name in {"", "."} or path.is_absolute() or ".." in path.parts or str(path) != name: + raise ValueError(f"expected canonical relative file: {name!r}") + if not targets: + return + if command is None: + raise ValueError("a grader command is required for input destinations") + static_files = set(command["files"]) + static_dirs = set() + if command["bundle"] is not None: + with tarfile.open(command["bundle"]) as bundle: + for member in bundle: + paths = static_dirs if member.isdir() else static_files + paths.add(str(PurePosixPath(member.name))) + for dst in targets: + if ( + dst in static_files + or dst in static_dirs + or any(path.startswith(dst + "/") for path in static_dirs) + or any( + other != dst and (other.startswith(dst + "/") or dst.startswith(other + "/")) + for other in static_files | targets + ) + ): + raise ValueError(f"file binding collides at {dst}") diff --git a/xtuner/v1/rl/agent_loop/trial_agent_loop/sandbox/types.py b/xtuner/v1/rl/agent_loop/trial_agent_loop/sandbox/types.py new file mode 100644 index 0000000000..9c7f48c766 --- /dev/null +++ b/xtuner/v1/rl/agent_loop/trial_agent_loop/sandbox/types.py @@ -0,0 +1,197 @@ +"""Sandbox platform and command contracts; shared task resources live in attempt.""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Callable, Generic, Literal, Mapping, TypeAlias, TypeVar +from urllib.parse import urlsplit + +import mini_agent as ma +from mini_agent import Failure +from pydantic import BaseModel, ConfigDict +from typing_extensions import NotRequired, TypedDict + +from xtuner.v1.rl.agent_loop.trial_agent_loop.trial.base import SerializedResourceSpec + + +GatewayCluster: TypeAlias = Literal["pbox", "hbox", "dbox"] + + +class WorkerCrashError(RuntimeError): + """A confirmed worker crash for which the configured policy requires stopping.""" + + +@dataclass(frozen=True) +class ResourceHandle: + name: str + id: str + url: str = "" + token: str = field(default="", repr=False) + + +class SandboxConfig(BaseModel): + """纯沙箱平台连接配置(不包含任务 CPU/内存配额),供各任务 RunnerConfig 共享复用。""" + + model_config = ConfigDict(extra="forbid", frozen=True) + backend: Literal["opensandbox", "env_gateway"] = "opensandbox" + platform: Literal["dbox", "hbox"] = "dbox" # OpenSandbox API 的平台差异,不改变命令协议。 + command_mode: Literal["detached", "native"] = "detached" + endpoint: str + project: str + credential_file: str + cluster_name: GatewayCluster = "hbox" # env_gateway 专用:pbox / hbox / dbox + user: str = "autoolchain" # env_gateway 专用:用户标识 + + +OptsT = TypeVar("OptsT", bound=Mapping[str, object]) + + +class RuntimeRef(TypedDict): + """在 xt.cmd(...) 中显式声明运行期路径或服务地址,纯 JSON 可序列化,杜绝隐式魔法环境变量。""" + + ref: Literal["task_dir", "result_dir", "workspace", "public_dir", "service"] + name: NotRequired[str] # 仅 ref == "service" 时填写服务名 + + +CmdArg: TypeAlias = str | RuntimeRef + +TASK_DIR: RuntimeRef = {"ref": "task_dir"} +RESULT_DIR: RuntimeRef = {"ref": "result_dir"} +WORKSPACE: RuntimeRef = {"ref": "workspace"} +PUBLIC_DIR: RuntimeRef = {"ref": "public_dir"} + + +def service_url(name: str) -> RuntimeRef: + """在 xt.cmd(...) 的 argv、cwd 或 env 中显式引用指定依赖服务的运行期 URL。""" + if not name: + raise ValueError("service_url() requires a non-empty service name") + return {"ref": "service", "name": name} + + +class CommandSpec(TypedDict): + argv: list[CmdArg] + cwd: CmdArg + bundle: str | None + files: dict[str, str] + env: dict[str, CmdArg] + + +def cmd( + *argv: CmdArg, + cwd: CmdArg = ".", + bundle: str | None = None, + files: Mapping[str, str] | None = None, + env: Mapping[str, CmdArg] | None = None, +) -> CommandSpec: + """构造可 JSON 序列化的命令描述:保留镜像自身环境,运行期动态值通过 RuntimeRef 显式声明。""" + if not argv: + raise ValueError("cmd() requires at least one argv element") + return { + "argv": list(argv), + "cwd": cwd, + "bundle": bundle, + "files": dict(files or {}), + "env": dict(env or {}), + } + + +class ModelHostRef(TypedDict): + ref: Literal["model_host"] + + +class NetworkPolicyInput(TypedDict): + default_action: Literal["allow", "deny"] + egress: list[str | ModelHostRef] + + +@dataclass(frozen=True) +class NetworkPolicy: + default_action: Literal["allow", "deny"] + egress: tuple[str, ...] = () + + @classmethod + def resolve(cls, raw: NetworkPolicyInput, model_url: str) -> NetworkPolicy: + targets = [] + for item in raw["egress"]: + if item == {"ref": "model_host"}: + url = urlsplit(model_url) + if url.scheme not in {"http", "https"} or not url.hostname: + raise ValueError("expected model HTTP(S) hostname") + targets.append(url.hostname) + elif isinstance(item, str) and item: + targets.append(item) + else: + raise ValueError("unknown egress target") + if raw["default_action"] not in {"allow", "deny"}: + raise ValueError("invalid default_action") + return cls(raw["default_action"], tuple(targets)) + + def to_payload(self): + return { + "defaultAction": self.default_action, + "egress": [{"action": "allow", "target": t} for t in self.egress], + } + + +class SandboxResourceInput(TypedDict): + image: str + resources: NotRequired[SerializedResourceSpec | None] + network_policy: NotRequired[NetworkPolicyInput] + release: NotRequired[Literal["on_exit", "after_last_use"]] # 缺省留给 attempt 根清理 + + +class WorkspaceInput(TypedDict): + workspace: str + public_bundle: NotRequired[str | None] + setup: NotRequired[CommandSpec | None] + + +class ServiceInput(TypedDict): + name: str # 服务名用于 service_url(name) + sandbox: str # 引用 sandboxes 的逻辑名,两种名字可不同 + port: int + command: CommandSpec + ready: list[str] + + +class AgentStageInput(TypedDict): + sandbox: str + outputs: NotRequired[dict[str, str]] # 产物名 → 本箱工作区相对源路径 + + +class VerifyStageInput(TypedDict): + sandbox: str + command: CommandSpec + inputs: NotRequired[dict[str, str]] # grader job 相对目的路径 → 已声明的产物名 + outputs: list[str] # grader → 宿主,允许容器绝对结果路径 + + +class NamedSandboxTaskData(TypedDict, Generic[OptsT]): + sandboxes: dict[str, SandboxResourceInput] # 每个逻辑名在一个 SID 至多创建一个实例 + prepare: dict[str, WorkspaceInput] # 键也是沙盒引用;该箱首次使用时准备一次 + services: list[ServiceInput] # 声明顺序即启动顺序 + run_agent: AgentStageInput + verify: VerifyStageInput + grade_options: OptsT + + +@dataclass(frozen=True) +class GradeEvidence: + return_code: int + files: dict[str, bytes] + input_sha256: dict[str, str] = field(default_factory=dict) + + +@dataclass(frozen=True) +class AgentResult: + report: ma.AgentReport + artifacts: dict[str, str] # 工作区相对路径 -> 宿主机快照文件路径 + + +@dataclass(frozen=True) +class PreparedWorkspace: + resource: ResourceHandle + path: str + + +GradeDecoder: TypeAlias = Callable[[GradeEvidence, OptsT], float | Failure] diff --git a/xtuner/v1/rl/agent_loop/trial_agent_loop/trial/__init__.py b/xtuner/v1/rl/agent_loop/trial_agent_loop/trial/__init__.py new file mode 100644 index 0000000000..39884a2ee0 --- /dev/null +++ b/xtuner/v1/rl/agent_loop/trial_agent_loop/trial/__init__.py @@ -0,0 +1,6 @@ +"""Static Trial configuration, per-execution input and result contracts.""" + +from .base import Budgets, Failure, ResourceSpec, TaskInput, Trial, TrialConfig, TrialContext, TrialResult + + +__all__ = ["Budgets", "Failure", "ResourceSpec", "TaskInput", "Trial", "TrialConfig", "TrialContext", "TrialResult"] diff --git a/xtuner/v1/rl/agent_loop/trial_agent_loop/trial/base.py b/xtuner/v1/rl/agent_loop/trial_agent_loop/trial/base.py new file mode 100644 index 0000000000..708fa4d3cd --- /dev/null +++ b/xtuner/v1/rl/agent_loop/trial_agent_loop/trial/base.py @@ -0,0 +1,175 @@ +"""Declarative task identity and sandbox resources.""" + +from __future__ import annotations + +import asyncio +from abc import ABC, abstractmethod +from dataclasses import dataclass +from pathlib import Path +from typing import TYPE_CHECKING, Literal, TypeAlias + +import mini_agent as ma +from mini_agent import JsonObject +from pydantic import BaseModel, ConfigDict, Field +from typing_extensions import NotRequired, TypedDict + +from xtuner.v1.rl.agent_loop.trial_agent_loop.admission import AdaptiveConcurrencyGate +from xtuner.v1.rl.agent_loop.trial_agent_loop.error_handling import record_production_exception +from xtuner.v1.rl.observability import observe_phase + + +if TYPE_CHECKING: + from xtuner.v1.rl.rollout.controller import RolloutControllerProxy + + +Failure = ma.Failure +TaskKey: TypeAlias = tuple[str, str] +TrialTerminal: TypeAlias = ma.TerminalStatus | Literal["AgentTimeout"] + + +class SerializedResourceSpec(TypedDict, total=False): + cpus: int | None + memory_mb: int | None + storage_mb: int | None + + +class ResourceSpec(BaseModel): + """SandboxTrial 与 HarborTrialAdapter 共用的统一数值资源规格(由 Pydantic 原生校验正数)。""" + + model_config = ConfigDict(extra="forbid", frozen=True) + cpus: int | None = Field(default=None, gt=0) # 逻辑 CPU 核数(如 1 / 2 / 4) + memory_mb: int | None = Field(default=None, gt=0) # 内存 MB(如 2048 / 8192) + storage_mb: int | None = Field(default=None, gt=0) # 可选磁盘 MB + + def is_empty(self) -> bool: + return self.cpus is None and self.memory_mb is None and self.storage_mb is None + + def to_dict(self) -> SerializedResourceSpec: + return {"cpus": self.cpus, "memory_mb": self.memory_mb, "storage_mb": self.storage_mb} + + +def resolve_resources( + task: ResourceSpec | None, + default: ResourceSpec | None, +) -> ResourceSpec: + """两类 Runner 共用的两层逐字段合并:单样本资源(task)优先,缺失字段回退到任务集默认资源(default)。""" + return ResourceSpec( + cpus=task.cpus if task and task.cpus is not None else (default.cpus if default else None), + memory_mb=task.memory_mb if task and task.memory_mb is not None else (default.memory_mb if default else None), + storage_mb=task.storage_mb + if task and task.storage_mb is not None + else (default.storage_mb if default else None), + ) + + +class SerializedTaskInput(TypedDict): + key: list[str] | tuple[str, str] + instruction: str + data: JsonObject + resources: NotRequired[SerializedResourceSpec | None] + + +@dataclass(frozen=True) +class TaskInput: + key: TaskKey + instruction: str + data: JsonObject # 纯 JSON 数据,用于离线落盘 JSONL + resources: ResourceSpec | None = None # 样本级资源需求(如离线阶段从 task.toml [environment] 或数据行提取) + + def to_dict(self) -> SerializedTaskInput: + return { + "key": list(self.key), + "instruction": self.instruction, + "data": self.data, + "resources": None if self.resources is None else self.resources.to_dict(), + } + + @classmethod + def from_dict(cls, raw: SerializedTaskInput) -> TaskInput: + raw_res: SerializedResourceSpec | None = raw.get("resources") + res: ResourceSpec | None = None if raw_res is None else ResourceSpec(**raw_res) + return cls( + key=(raw["key"][0], raw["key"][1]), + instruction=raw["instruction"], + data=raw["data"], + resources=res, + ) + + +@dataclass(frozen=True) +class Budgets: + attempt: float = 9000.0 + agent: float = 7200.0 + request: float = 900.0 + command: float | None = 300.0 # Agent 单条工具命令超时(透传给支持该项的 Harness,如 mini_swe/claude_code) + verifier: float = 300.0 + cleanup: float = 120.0 + create_rpc: float = 20.0 + read_recovery: float = 300.0 + sandbox_ttl: float = 10800.0 + # A model HTTP call includes admission waiting across a weight update. + # None preserves the existing request budget; platform RPCs use request. + model_request: float | None = None + ready: float | None = None # None retains the attempt limit for existing recipes. + + +@dataclass(frozen=True) +class TrialContext: + """Serializable inputs for one execution; Runtime owns live resources.""" + + task: TaskInput + session_id: str + output_dir: Path + budgets: Budgets + model: ma.ModelSettings + rollout_ctl: RolloutControllerProxy + fail_fast: bool = False + producer_model_step: int | None = None + + @observe_phase("model/settle") + async def finish_session(self) -> None: + # 上下文只携带可序列化的 actor 句柄;不传捕获父端 self/HTTP client 的闭包。 + try: + async with asyncio.timeout(self.budgets.request): + await self.rollout_ctl.finish_agent_session.remote(self.session_id, self.budgets.request) + except Exception as exc: + record_production_exception( + exc, phase="model/settle", ctx=self, isolation={"model_session": "unconfirmed"} + ) + if not isinstance(exc, TimeoutError): + raise + raise RuntimeError(f"MODEL_UNSETTLED: session {self.session_id} settlement RPC timed out") from None + + +@dataclass(frozen=True) +class TrialResult: + score: float + terminal: TrialTerminal = "Submitted" + observed_request_ids: list[str] | None = None # None 表示使用服务端提交顺序(如 Harbor 直连)。 + + +class Trial(ABC): + """Bind one execution's inputs inside the local or CPU Ray event loop.""" + + def __init__(self, cfg: TrialConfig, ctx: TrialContext): + self.cfg = cfg + self.ctx = ctx + + @abstractmethod + async def run(self) -> TrialResult | Failure: ... + + +class TrialConfig(ABC, BaseModel): + """Reusable static policy; build(ctx) binds one execution without changing it.""" + + model_config = ConfigDict(extra="forbid", arbitrary_types_allowed=True) + default_resources: ResourceSpec | None = None # 任务集默认资源(单样本未指定字段时回退使用) + + def resolve_task_resources(self, task_resources: ResourceSpec | None) -> ResourceSpec: + return resolve_resources(task_resources, self.default_resources) + + def build_admission_gate(self, max_samples: int) -> AdaptiveConcurrencyGate | None: + return None + + @abstractmethod + def build(self, ctx: TrialContext) -> Trial: ... diff --git a/xtuner/v1/rl/agent_loop/trial_agent_loop/trial/execution.py b/xtuner/v1/rl/agent_loop/trial_agent_loop/trial/execution.py new file mode 100644 index 0000000000..c2d2bf6a99 --- /dev/null +++ b/xtuner/v1/rl/agent_loop/trial_agent_loop/trial/execution.py @@ -0,0 +1,238 @@ +"""One original CPU Trial; the parent owns its lifetime and model settlement.""" + +from __future__ import annotations + +import asyncio +import logging +from builtins import BaseExceptionGroup +from contextlib import nullcontext +from pathlib import Path +from typing import Literal, cast +from uuid import uuid4 + +import ray +from mini_agent import Failure +from ray.util.scheduling_strategies import PlacementGroupSchedulingStrategy + +from xtuner.v1.rl.agent_loop.trial_agent_loop.trial.base import TrialConfig, TrialContext, TrialResult +from xtuner.v1.rl.observability import Observation, current_observation, observe_phase, otel +from xtuner.v1.rl.trace import get_trace_env_vars +from xtuner.v1.rl.utils.async_utils import finish_owned + + +async def _await_terminal(ref, started_path: Path | None = None) -> TrialResult | Failure: + future = asyncio.ensure_future(ref) + try: + return await asyncio.shield(future) + except asyncio.CancelledError as interrupted: + cancel_trial(ref) + # Keep the parent's route lease until Runner.finally has completed. + outcome, deferred = await finish_owned(future) + cancellation = outcome.cause if isinstance(outcome, ray.exceptions.RayTaskError) else outcome + requested_cancel = ( + type(cancellation) is ray.exceptions.TaskCancelledError + and isinstance(ref, ray.ObjectRef) + # Python reports an explicit cancellation of this task after unwinding + # its finally. Other RayTaskError causes still belong to cleanup. + and cancellation.task_id == ref.task_id() + ) + receipt_error = None + if type(outcome) is ray.exceptions.TaskCancelledError and outcome.task_id is None and started_path is not None: + # Ray also uses C++ TASK_CANCELLED when a cancelled worker dies. + # Only a task that never crossed the shared start gate can treat + # that ambiguous receipt as safe queued cancellation. + try: + started_path.stat() + except FileNotFoundError: + requested_cancel = True + except OSError as exc: + receipt_error = exc + remote_error = None + if not requested_cancel and not isinstance(outcome, (TrialResult, Failure)): + remote_error = ( + outcome if isinstance(outcome, BaseException) else RuntimeError("Invalid remote Trial result") + ) + # A cancellation receipt for this exact task is expected. Remote cleanup + # errors and worker loss still prevent the parent from declaring timeout safe. + errors = [error for error in (interrupted, deferred, remote_error, receipt_error) if error is not None] + raise errors[0] if len(errors) == 1 else BaseExceptionGroup("remote trial cancellation and cleanup", errors) + + +@ray.remote(num_cpus=1, num_gpus=0, max_retries=0, retry_exceptions=False) +def run_trial( + trial_cfg: TrialConfig, ctx: TrialContext, observation: dict | None = None, started_path: str | None = None +) -> TrialResult | Failure: + """Construct stateful Runner/client objects inside this CPU worker's loop.""" + if started_path is not None: + path = Path(started_path) + path.parent.mkdir(parents=True, exist_ok=True) + # The attempt output is shared with the parent. Publish before building + # or running the Trial: absence then proves no business work started. + path.write_text(str(ray.get_runtime_context().get_task_id())) + + async def run() -> TrialResult | Failure: + loop = asyncio.get_running_loop() + wakeup: asyncio.TimerHandle | None = None + + def wake() -> None: + nonlocal wakeup + wakeup = loop.call_later(1, wake) + + # A synchronous Ray worker needs periodic select wakeups to service + # cooperative KeyboardInterrupt cancellation while its loop is idle. + wake() + try: + obs = Observation.from_dict(observation) if observation else None + with ( + obs.activate(role="trial", parent_carrier=observation.get("carrier")) if obs else nullcontext() + ) as active: + if active: + active.emit( + "trial_started", + ray_task_id=ray.get_runtime_context().get_task_id(), + ray_node_id=ray.get_runtime_context().get_node_id(), + ) + return await trial_cfg.build(ctx).run() + finally: + assert wakeup is not None + wakeup.cancel() + + return asyncio.run(run()) + + +def start_trial( + trial_cfg: TrialConfig, + ctx: TrialContext, + *, + dispatch_mode: Literal["local", "ray_task"] = "ray_task", + trial_cpus: float = 1, +) -> asyncio.Task[TrialResult | Failure]: + """Start once, retaining an owner that waits for the original task's finally. + + Runner/client construction stays inside the executing loop. Ray CPU credits + stay outside the model placement group; no live clients or callbacks cross + the process boundary. The Ray waiter owns its original ObjectRef even when + cancelled, so cancelling this Task cannot abandon the remote cleanup. + """ + if dispatch_mode == "local": + + async def run_local(): + return await trial_cfg.build(ctx).run() + + return asyncio.create_task(run_local()) + if dispatch_mode != "ray_task" or trial_cpus <= 0: + raise ValueError("ray_task dispatch requires positive trial_cpus") + + async def run_ray(): + observation = current_observation() + payload = observation.to_dict() if observation else None + options = {} + if payload is not None and otel.enabled(): + # Capture the active parent at submission. The sample reference carries durable identity. + carrier = otel.current_carrier() + if carrier: + payload["carrier"] = carrier + options["runtime_env"] = {"env_vars": get_trace_env_vars()} + started_path = (ctx.output_dir / f"trial-{uuid4().hex}.started").resolve() + ref = run_trial.options( + num_cpus=trial_cpus, + scheduling_strategy=PlacementGroupSchedulingStrategy( + placement_group=None, + placement_group_capture_child_tasks=False, + ), + **options, + ).remote(trial_cfg, ctx, payload, str(started_path)) + if observation: + observation.emit( + "trial_submitted", ray_task_id=ref.task_id().hex(), ray_job_id=ray.get_runtime_context().get_job_id() + ) + return await _await_terminal(ref, started_path) + + # Submission happens inside the owned Task: a cancellation before its first + # execution cannot submit remote work without entering its terminal waiter. + return asyncio.create_task(run_ray()) + + +def cancel_trial(original: asyncio.Future | ray.ObjectRef) -> None: + """Request cooperative cancellation of the original execution, never replay. + + A Ray ObjectRef waiter and remote task have different lifetimes. The owner + still waits for the terminal state after this request, including when the + request itself fails; no force kill substitutes for resource cleanup. + """ + if isinstance(original, ray.ObjectRef): + try: + ray.cancel(original, force=False, recursive=False) + except Exception: + logging.getLogger(__name__).exception("Trial cancel request failed; waiting for original task termination") + else: + original.cancel() + + +async def settle_trial(work: asyncio.Task, ctx: TrialContext, dispatch_mode: Literal["local", "ray_task"]): + """Retain both execution and model settlement through repeated cancellation. + + Local model settlement runs concurrently to unblock pending requests. Ray + must first finish the original remote Trial and its finally before the + parent performs fallback route retirement. Neither path drops true errors. + """ + if dispatch_mode == "local": + model_close = asyncio.create_task(ctx.finish_session()) + work_result = await finish_owned(work) + else: # start_trial has already validated ray_task dispatch. + work_result = await finish_owned(work) + model_close = asyncio.create_task(ctx.finish_session()) + + model_result = await finish_owned(model_close) + return work_result, model_result + + +def resolve_trial_result(work_result, model_result, outer_error, timeout_result) -> TrialResult | Failure: + """Keep deferred caller cancellation distinct from the original work outcome.""" + work_value, work_wait_cancel = work_result + # finish_session succeeds with None; its first result is otherwise an error. + model_error, model_wait_cancel = model_result + + work_error = work_value if isinstance(work_value, BaseException) else None + cancellation_expected = timeout_result is not None or outer_error is not None + if cancellation_expected and isinstance(work_error, asyncio.CancelledError): + # Timeout/caller interruption already records this requested work cancel. + # Deferred waiter cancellation and true cleanup errors remain distinct. + work_error = None + + errors = [ + error + for error in (outer_error, work_wait_cancel, model_error, model_wait_cancel, work_error) + if isinstance(error, BaseException) + ] + if errors: + raise errors[0] if len(errors) == 1 else BaseExceptionGroup("attempt cleanup failed", errors) + return timeout_result if timeout_result is not None else cast(TrialResult | Failure, work_value) + + +@observe_phase("dispatch/total", failure=Failure) +async def execute_trial( + trial_cfg: TrialConfig, + ctx: TrialContext, + *, + dispatch_mode: Literal["local", "ray_task"], + trial_cpus: float, +) -> TrialResult | Failure: + """Submit, wait once, settle original owners, then resolve the Attempt result.""" + loop = asyncio.get_running_loop() + deadline = loop.time() + ctx.budgets.attempt + work = start_trial(trial_cfg, ctx, dispatch_mode=dispatch_mode, trial_cpus=trial_cpus) + timeout_result = None + outer_error = None + try: + # Submission, Ray queueing and execution share the original deadline. + done, _ = await asyncio.wait({work}, timeout=max(0, deadline - loop.time())) + if work not in done: + timeout_result = Failure("ATTEMPT_TIMEOUT", "attempt", ctx.session_id) + except BaseException as exc: + outer_error = exc + finally: + if not work.done(): + cancel_trial(work) + work_result, model_result = await settle_trial(work, ctx, dispatch_mode) + return resolve_trial_result(work_result, model_result, outer_error, timeout_result) diff --git a/xtuner/v1/rl/agent_loop/trial_agent_loop/trial/sandbox_trial.py b/xtuner/v1/rl/agent_loop/trial_agent_loop/trial/sandbox_trial.py new file mode 100644 index 0000000000..9ca06dd9c5 --- /dev/null +++ b/xtuner/v1/rl/agent_loop/trial_agent_loop/trial/sandbox_trial.py @@ -0,0 +1,374 @@ +"""A linear sandbox Trial: services, workspace, Agent, then private grading.""" + +from __future__ import annotations + +import hashlib +import json +import logging +from functools import partial +from pathlib import Path +from typing import Annotated, Generic, Literal, Mapping + +import mini_agent as ma +from mini_agent import Failure +from pydantic import BaseModel, ConfigDict, Field + +from xtuner.v1.rl.agent_loop.trial_agent_loop.admission import AdaptiveConcurrencyGate +from xtuner.v1.rl.agent_loop.trial_agent_loop.error_handling import record_production_exception +from xtuner.v1.rl.agent_loop.trial_agent_loop.sandbox.client import read_project_quota +from xtuner.v1.rl.agent_loop.trial_agent_loop.sandbox.runtime import SandboxRuntime, validate_file_bindings +from xtuner.v1.rl.agent_loop.trial_agent_loop.sandbox.types import ( + AgentStageInput, + GradeDecoder, + NetworkPolicy, + OptsT, + SandboxConfig, + SandboxResourceInput, + ServiceInput, + VerifyStageInput, + WorkerCrashError, + WorkspaceInput, +) +from xtuner.v1.rl.agent_loop.trial_agent_loop.trial.base import ( + ResourceSpec, + TaskInput, + Trial, + TrialConfig, + TrialContext, + TrialResult, +) +from xtuner.v1.rl.observability import observe_phase +from xtuner.v1.rl.observability.sandbox_http import observe_sandbox_http + + +logger = logging.getLogger(__name__) + + +class SandboxTrialConfig(TrialConfig, Generic[OptsT]): + """通用沙箱执行器配置(留在 xtuner);mini_crg 中常规任务只需继承并预置 decode_grade 与 default_resources。""" + + sandbox: SandboxConfig + harness: ma.HarnessSpec + decode_grade: GradeDecoder[OptsT] | None = None # 走默认 run_task 时必填;子类覆写 run_task 时可省略 + max_turns: int | None = 300 + tool_user: str | None = None # None=免降权直接运行(默认);安全任务可显式设为 "agent-tools" + tool_env: dict[str, str] | None = None + # Capture in the image before any SDK/control variables are injected. + tool_env_command: tuple[str, ...] = ("env", "-0") + # Compatibility with experiment configs predating TrialAgentLoopConfig.fail_fast. + fail_fast_on_worker_crash: bool = False + require_clean_exit: bool = False + # 整个Attempt可能同时占用的资源峰值;None保留原固定并发。 + admission_peak: ( + tuple[ + Annotated[float, Field(gt=0, allow_inf_nan=False, strict=True)], + Annotated[float, Field(gt=0, allow_inf_nan=False, strict=True)], + Annotated[int, Field(gt=0, strict=True)], + ] + | Literal["passive"] + | None + ) = None + quota_tenant: str | None = Field(default=None, min_length=1) + + def build_admission_gate(self, max_samples: int) -> AdaptiveConcurrencyGate | None: + if self.admission_peak is None: + return None + can_probe = ( + self.sandbox.backend == "opensandbox" + and self.admission_peak != "passive" + and (self.sandbox.platform == "dbox" or self.quota_tenant is not None) + ) + return AdaptiveConcurrencyGate( + max_samples, + cost=self.admission_peak if can_probe else None, + probe=partial(read_project_quota, self.sandbox, self.quota_tenant) if can_probe else None, + context={ + "backend": self.sandbox.backend, + "platform": self.sandbox.platform, + "project": self.sandbox.project, + }, + ) + + def build(self, ctx: TrialContext) -> SandboxTrial[OptsT]: + return SandboxTrial(self, ctx) + + +class SandboxTrial(Trial, Generic[OptsT]): + """通用内置沙箱执行器:run 管生命周期壳子,run_task 实现默认线性流程(复杂任务在子类覆写 run_task)。""" + + cfg: SandboxTrialConfig[OptsT] + + def __init__(self, cfg: SandboxTrialConfig[OptsT], ctx: TrialContext) -> None: + super().__init__(cfg, ctx) + if type(self).run_task is SandboxTrial.run_task and cfg.decode_grade is None: + raise ValueError("Default SandboxTrial.run_task requires decode_grade") + self._decode_grade: GradeDecoder[OptsT] | None = cfg.decode_grade + if cfg.tool_env is not None: + self.tool_env: dict[str, str] = dict(cfg.tool_env) + elif cfg.tool_user is not None: + self.tool_env = { + "PATH": "/usr/local/bin:/usr/bin:/bin", + "HOME": f"/home/{cfg.tool_user}", + "LANG": "C.UTF-8", + } + else: + self.tool_env = {} + + @observe_phase("trial/run", failure=Failure) + @observe_sandbox_http + async def run(self) -> TrialResult | Failure: + ctx = self.ctx + attempt_resources: ResourceSpec = self.cfg.resolve_task_resources(ctx.task.resources) + sandbox_runtime = SandboxRuntime( + ctx=ctx, + sandbox_cfg=self.cfg.sandbox, + default_resources=attempt_resources, + harness=self.cfg.harness, + max_turns=self.cfg.max_turns, + tool_user=self.cfg.tool_user, + tool_env=self.tool_env, + tool_env_command=self.cfg.tool_env_command, + fail_fast_on_worker_crash=self.cfg.fail_fast_on_worker_crash, + require_clean_exit=self.cfg.require_clean_exit, + ) + async with sandbox_runtime: + try: + outcome = await self.run_task(ctx.task, sandbox_runtime) + except Exception as exc: + record_production_exception( + exc, + phase="trial/run", + ctx=ctx, + command_ids=sandbox_runtime.command_ids, + request_ids=sandbox_runtime.observed_request_ids, + isolation={"sandbox_cleanup": "pending", "parent_model_settlement": "required"}, + ) + if ctx.fail_fast or isinstance(exc, WorkerCrashError): + raise + outcome = Failure("TRIAL_EXECUTION_EXCEPTION", "trial", str(exc)) + if sandbox_runtime.cleanup_failure is not None: + logger.warning("Sandbox cleanup failed sid=%s original_outcome=%s", ctx.session_id, outcome) + return sandbox_runtime.cleanup_failure + return outcome + + async def _use(self, name, rt): + # 同名资源沿用首次创建和准备回执,因此不重发 POST 或 setup。 + if name not in self._opened: + box = self._spec.sandboxes[name] + handle = await rt.acquire( + name, + image=box["image"], + ports=tuple(s["port"] for s in self._spec.services if s["sandbox"] == name), + resources=ResourceSpec(**box["resources"]) if box.get("resources") is not None else None, + network_policy=box.get("network_policy"), + ) + if isinstance(handle, Failure): + return handle + ws = None + if name in self._spec.prepare: + prep = self._spec.prepare[name] + ws = await rt.prepare( + handle, + workspace=prep["workspace"], + setup=prep.get("setup"), + public_bundle=prep.get("public_bundle"), + services=self._services, + ) + if isinstance(ws, Failure): + return ws + self._opened[name] = (handle, ws) + return self._opened[name] + + async def run_task(self, task: TaskInput, sandbox_runtime: SandboxRuntime) -> TrialResult | Failure: + if self._decode_grade is None: + raise ValueError("Default SandboxTrial.run_task requires decode_grade") + rt = sandbox_runtime + spec = self._spec = TaskSpec.model_validate(task.data) + spec.validate_references(self.cfg.sandbox.backend, self.ctx.model.url) + spec.write_bindings(self.ctx.output_dir, mode="online", required=self.cfg.require_clean_exit) + self._opened, self._services = {}, {} + services = self._services + + for svc in spec.services: + bound = await self._use(svc["sandbox"], rt) + if isinstance(bound, Failure): + return bound + handle, ws = bound + url = await rt.start_service( + handle, + command=svc["command"], + port=svc["port"], + ready=svc["ready"], + services=services, + **({"workspace": ws.path} if ws is not None else {}), + ) + if isinstance(url, Failure): + return url + services[svc["name"]] = url + + agent_stage, verify_stage = spec.run_agent, spec.verify + agent_name, verify_name = agent_stage["sandbox"], verify_stage["sandbox"] + bound = await self._use(agent_name, rt) + if isinstance(bound, Failure): + return bound + _, ws = bound + outputs = agent_stage.get("outputs", {}) + paths = tuple(dict.fromkeys(outputs.values())) + agent = await rt.run_agent(ws, task.instruction, **({"outputs": paths} if paths else {})) + if isinstance(agent, Failure): + return agent + inputs = bind_agent_inputs(self.ctx.output_dir, outputs, agent.artifacts, verify_stage.get("inputs", {})) + if isinstance(inputs, Failure): + return inputs + # 已核验候选原始 bytes;独立 solver 再取得删除回执后,才允许创建 grader。 + if ( + agent_name != verify_name + and all(s["sandbox"] != agent_name for s in spec.services) + and spec.sandboxes[agent_name].get("release") == "after_last_use" + ): + failure = await rt.release(agent_name) + if failure is not None: + return failure + + bound = await self._use(verify_name, rt) + if isinstance(bound, Failure): + return bound + handle, ws = bound + evidence = await rt.verify( + handle, + command=verify_stage["command"], + outputs=verify_stage["outputs"], + workspace=ws.path if ws else None, + services=services, + **({"inputs": inputs} if inputs else {}), + ) + if isinstance(evidence, Failure): + return evidence + # 已取得验分回执;所需释放全部确认后才允许 decoder 出分。 + for name in reversed(self._opened): + if spec.sandboxes[name].get("release") == "after_last_use": + failure = await rt.release(name) + if failure is not None: + return failure + score = self._decode_grade(evidence, spec.grade_options) + if isinstance(score, Failure): + return score + return TrialResult( + score=score, terminal=agent.report.terminal, observed_request_ids=agent.report.observed_request_ids + ) + + +class TaskSpec(BaseModel, Generic[OptsT]): + """One named task declaration; validation never creates or prepares a sandbox.""" + + model_config = ConfigDict(extra="forbid", strict=True, frozen=True, hide_input_in_errors=True) + sandboxes: dict[str, SandboxResourceInput] + prepare: dict[str, WorkspaceInput] + services: list[ServiceInput] + run_agent: AgentStageInput + verify: VerifyStageInput + grade_options: OptsT + + def validate_references(self, backend: str, model_url: str) -> None: + boxes, prep = self.sandboxes, self.prepare + agent_box, grade_box = self.run_agent["sandbox"], self.verify["sandbox"] + uses = [svc["sandbox"] for svc in self.services] + [agent_box, grade_box] + if any(not name for name in boxes) or not set(uses).issubset(boxes) or not set(prep).issubset(boxes): + raise ValueError("unknown sandbox reference") + if agent_box not in prep or any( + not x["workspace"] or (x.get("setup") is None and x.get("public_bundle") is not None) + for x in prep.values() + ): + raise ValueError("invalid or missing workspace preparation") + ports, service_names = {name: set() for name in boxes}, set() + for svc in self.services: + name, box, port = svc["name"], svc["sandbox"], svc["port"] + if not name or name in service_names or not 0 < port <= 65535 or not svc["ready"]: + raise ValueError(f"invalid service: {name}") + if port in ports[box]: + raise ValueError(f"multiple listeners on {box}:{port}") + service_names.add(name) + ports[box].add(port) + for name, box in boxes.items(): + if not box["image"]: + raise ValueError(f"missing image: {name}") + if box.get("resources") is not None: + ResourceSpec(**box["resources"]) + if "network_policy" in box: + if backend != "opensandbox": + raise ValueError("create-time network policy requires OpenSandbox") + NetworkPolicy.resolve(box["network_policy"], model_url) + + # Check command references in the same fixed order as execution. A workspace is prepared once. + ready, prepared = set(), set() + stages = [(s["sandbox"], s["command"], s["name"]) for s in self.services] + stages.extend([(agent_box, None, None), (grade_box, self.verify["command"], None)]) + for box, command, service in stages: + ws = prep.get(box) + checks = [] + if box not in prepared and ws is not None and ws.get("setup") is not None: + checks.append((ws["setup"], ws.get("public_bundle") is not None)) + prepared.add(box) + if command is not None: + checks.append((command, False)) + for cmd_spec, has_public in checks: + if not cmd_spec["argv"]: + raise ValueError(f"expected command argv in {box}") + for ref in [*cmd_spec["argv"], cmd_spec["cwd"], *cmd_spec["env"].values()]: + if isinstance(ref, str): + continue + kind = ref["ref"] + if ( + kind in {"task_dir", "result_dir"} + or (kind == "workspace" and ws is not None) + or (kind == "public_dir" and has_public) + or (kind == "service" and ref.get("name") in ready) + ): + continue + raise ValueError(f"unavailable command reference in {box}: {ref}") + if service is not None: + ready.add(service) + outputs, inputs = self.run_agent.get("outputs", {}), self.verify.get("inputs", {}) + if any(not name for name in outputs) or not set(inputs.values()).issubset(outputs): + raise ValueError("unknown Agent output name") + if any(not path for path in self.verify["outputs"]): + raise ValueError("empty verifier output path") + validate_file_bindings(outputs.values(), inputs.keys(), self.verify["command"]) + + def write_bindings(self, root: Path, *, mode: Literal["online", "snapshot"], required: bool) -> None: + stages = { + "run_agent": self.run_agent["sandbox"], + "verify": self.verify["sandbox"], + "services": {s["name"]: s["sandbox"] for s in self.services}, + } + try: + (root / "sandbox_bindings.json").write_text(json.dumps({"mode": mode, "stages": stages})) + except OSError: + if required: + raise + logger.warning("Failed to write sandbox bindings in %s", root, exc_info=True) + + +def bind_agent_inputs( + root: Path, outputs: dict[str, str], artifacts: Mapping[str, str], inputs: dict[str, str] +) -> dict[str, bytes] | Failure: + # 唯一生产者是本次 run_agent;支持改名、一源多目标和保留未消费的输出用于审计。 + if not inputs: + return {} + try: + original = json.loads((root / "snapshot_sha256.json").read_bytes()) + by_source = {} + for alias in inputs.values(): + src = outputs[alias] + if src in by_source: + continue + path = root / "snapshot" / src + if Path(artifacts[src]) != path: + return Failure("SNAPSHOT_INVALID", "snapshot", src) + blob = path.read_bytes() + if hashlib.sha256(blob).hexdigest() != original[src]: + return Failure("SNAPSHOT_MISMATCH", "snapshot", src) + by_source[src] = blob + return {dst: by_source[outputs[alias]] for dst, alias in inputs.items()} + except (OSError, ValueError, KeyError, TypeError) as exc: + return Failure("SNAPSHOT_INVALID", "snapshot", str(exc)) diff --git a/xtuner/v1/rl/utils/async_utils.py b/xtuner/v1/rl/utils/async_utils.py index fe98a9d74d..ceaadca718 100644 --- a/xtuner/v1/rl/utils/async_utils.py +++ b/xtuner/v1/rl/utils/async_utils.py @@ -291,3 +291,42 @@ def asyncio_run(coro: Coroutine, loop: Optional[AbstractEventLoop] = None) -> An except Exception as exc: if os.getenv("XTUNER_ASYNCIO_DIAGNOSTICS"): logger.warning(f"[AsyncioDiag] failed to stop asyncio diagnostics: {type(exc).__name__}: {exc}") + + +async def finish_owned(task: asyncio.Future[T]) -> tuple[T | BaseException, asyncio.CancelledError | None]: + """等待独占Future真实终态,重复取消不会打断原执行。 + + 返回的第一个值属于原执行(结果或异常),第二个值属于等待期间的调用方取消; + 调用方须在完成其他收尾后统一处理二者,不能把延后取消误当作原执行失败。""" + deferred_cancel: asyncio.CancelledError | None = None + while not task.done(): + try: + await asyncio.shield(task) + except asyncio.CancelledError as exc: + if not task.cancelled(): + deferred_cancel = deferred_cancel or exc + except BaseException: + break + try: + return task.result(), deferred_cancel + except BaseException as exc: + return exc, deferred_cancel + + +async def cleanup_owned_task(task: asyncio.Task) -> BaseException | None: + """Cancel and collect an owned task, preserving cancellations it already had.""" + cancel_sent = not task.done() and task.cancelling() == 0 and task.cancel() + try: + await task + except BaseException as task_error: + if cancel_sent and isinstance(task_error, asyncio.CancelledError): + return None + return task_error + return None + + +def find_error_original_task(task_error: BaseException | None, *, seen_by_caller: bool) -> BaseException | None: + """Keep control signals and errors not yet delivered to the execution owner.""" + if seen_by_caller and isinstance(task_error, Exception): + return None + return task_error