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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
174 changes: 174 additions & 0 deletions .dev_scripts/smoke_sandbox_cleanup.py
Original file line number Diff line number Diff line change
@@ -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()))
5 changes: 5 additions & 0 deletions tests/rl/fixtures/opensandbox/exit7.events
Original file line number Diff line number Diff line change
@@ -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"]}}
41 changes: 41 additions & 0 deletions tests/rl/fixtures/opensandbox/oom_native_status.json
Original file line number Diff line number Diff line change
@@ -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
}
24 changes: 24 additions & 0 deletions tests/rl/fixtures/opensandbox/service_oom_while_main_running.json
Original file line number Diff line number Diff line change
@@ -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"
}
}
]
92 changes: 92 additions & 0 deletions tests/rl/named_sandbox_http_fixture.py
Original file line number Diff line number Diff line change
@@ -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))
Loading
Loading