Skip to content
Merged
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
2 changes: 2 additions & 0 deletions nemo_gym/sandbox/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from nemo_gym.sandbox.api import AsyncSandbox, Sandbox
from nemo_gym.sandbox.config import resolve_provider_config, resolve_provider_metadata
from nemo_gym.sandbox.providers import (
ConnectableProvider,
ExecResult,
SandboxCreateError,
SandboxCreateVerificationError,
Expand All @@ -37,6 +38,7 @@
__all__ = [
"Sandbox",
"AsyncSandbox",
"ConnectableProvider",
"ExecResult",
"SandboxCreateError",
"SandboxCreateVerificationError",
Expand Down
36 changes: 36 additions & 0 deletions nemo_gym/sandbox/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
from typing import Any, TypeVar

from nemo_gym.sandbox.providers import (
ConnectableProvider,
SandboxExecResult,
SandboxHandle,
SandboxProvider,
Expand Down Expand Up @@ -131,6 +132,41 @@ async def stop(self) -> None:
await self._provider.aclose()
self._closed = True

async def serialize(self, *, scope: str | None = None) -> dict[str, Any]:
"""Return a JSON descriptor another process can rebuild this box from.

Requires a provider that supports the connect capability (the remote
provider, or an external-control-plane provider such as OpenSandbox). For
the remote provider, ``scope`` mints a co-lease (``scope="operate"``).
"""
provider = self._provider
if not isinstance(provider, ConnectableProvider):
name = getattr(provider, "name", type(provider).__name__)
raise RuntimeError(f"provider {name!r} does not support serialize()/connect()")
descriptor = await provider.serialize_handle(self._require_handle(), scope=scope)
# Carry the working directory so a reattached sandbox lands in the same
# place, even for providers whose descriptor does not include it (the
# remote provider's SandboxRef already has it; e.g. OpenSandbox does not).
if isinstance(descriptor, dict) and descriptor.get("workdir") is None and self._spec is not None:
descriptor = {**descriptor, "workdir": self._spec.workdir}
return descriptor

@classmethod
async def connect(cls, descriptor: Mapping[str, Any] | Any, *, provider: SandboxProvider) -> "AsyncSandbox":
"""Rebuild a sandbox in this process from a descriptor produced by
:meth:`serialize`, using ``provider`` (which must support connect)."""
if not isinstance(provider, ConnectableProvider):
name = getattr(provider, "name", type(provider).__name__)
raise RuntimeError(f"provider {name!r} does not support serialize()/connect()")
if not isinstance(descriptor, Mapping) and hasattr(descriptor, "to_dict"):
descriptor = descriptor.to_dict()
handle = await provider.connect(descriptor)
workdir = descriptor.get("workdir") if isinstance(descriptor, Mapping) else None
sandbox = cls(provider, SandboxSpec(workdir=workdir))
sandbox._handle = handle
sandbox._stopped = False
return sandbox

async def __aenter__(self) -> "AsyncSandbox":
return self

Expand Down
2 changes: 2 additions & 0 deletions nemo_gym/sandbox/providers/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"""Sandbox provider registry."""

from nemo_gym.sandbox.providers.base import (
ConnectableProvider,
ExecResult,
SandboxCreateError,
SandboxCreateVerificationError,
Expand All @@ -34,6 +35,7 @@


__all__ = [
"ConnectableProvider",
"ExecResult",
"SandboxCreateError",
"SandboxCreateVerificationError",
Expand Down
24 changes: 23 additions & 1 deletion nemo_gym/sandbox/providers/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
from dataclasses import dataclass, field
from enum import Enum
from pathlib import Path
from typing import Any, Protocol
from typing import Any, Protocol, runtime_checkable


class SandboxStatus(str, Enum):
Expand Down Expand Up @@ -168,3 +168,25 @@ async def close(self, handle: SandboxHandle) -> None:
async def aclose(self) -> None:
"""Close provider-scoped resources such as SDK clients."""
...


@runtime_checkable
class ConnectableProvider(Protocol):
"""Optional capability: rebuild a handle in another process from a descriptor.

Providers whose sandboxes are reachable by id (external control plane, e.g.
OpenSandbox and Fargate, and the sandbox server's remote provider) implement
this. A provider that does not implement it can only be shared by fronting it
with a sandbox server. Membership is checked with ``isinstance`` because the
protocol is ``runtime_checkable``.
"""

async def serialize_handle(self, handle: SandboxHandle, *, scope: str | None = None) -> dict[str, Any]:
"""Return a JSON-serializable descriptor that ``connect`` can rebuild a
handle from. ``scope`` is honored by providers that mint leases (the
remote provider) and ignored by the rest."""
...

async def connect(self, descriptor: Mapping[str, Any]) -> SandboxHandle:
"""Rebuild a live handle in this process from a descriptor."""
...
169 changes: 169 additions & 0 deletions tests/unit_tests/test_sandbox_connect.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Tests for the ConnectableProvider capability and the serialize/connect facade.

Hermetic: a fake in-process provider stands in for a reattachable backend, so
these exercise the facade and protocol without any sandbox server.
"""

from __future__ import annotations

import asyncio
from pathlib import Path
from typing import Any
from uuid import uuid4

import pytest

from nemo_gym.sandbox import (
AsyncSandbox,
ConnectableProvider,
SandboxExecResult,
SandboxHandle,
SandboxSpec,
SandboxStatus,
)


_STORE: dict[str, dict[str, Any]] = {}


class FakeConnectableProvider:
"""In-memory provider that supports connect; boxes live in a global store
keyed by id, so a second instance can reconnect by id."""

name = "fake_connectable"

async def create(self, spec: SandboxSpec) -> SandboxHandle:
sid = f"fake-{uuid4().hex[:8]}"
_STORE[sid] = {"files": {}, "closed": False}
return SandboxHandle(sandbox_id=sid, provider_name=self.name, raw=sid)

async def exec(self, handle, command, *, cwd=None, env=None, timeout_s=None, user=None) -> SandboxExecResult:
box = _STORE.get(handle.sandbox_id)
if box is None or box["closed"]:
return SandboxExecResult(stdout=None, stderr="no such sandbox", return_code=1)
if command.startswith("cat "):
data = box["files"].get(command[4:].strip())
if data is None:
return SandboxExecResult(stdout=None, stderr="no such file", return_code=1)
return SandboxExecResult(stdout=data.decode(), stderr=None, return_code=0)
if command == "pwd":
return SandboxExecResult(stdout=cwd or "", stderr=None, return_code=0)
return SandboxExecResult(stdout=f"ran: {command}", stderr=None, return_code=0)

async def upload_file(self, handle, source_path, target_path) -> None:
_STORE[handle.sandbox_id]["files"][target_path] = Path(source_path).read_bytes()

async def download_file(self, handle, source_path, target_path) -> None:
Path(target_path).parent.mkdir(parents=True, exist_ok=True)
Path(target_path).write_bytes(_STORE[handle.sandbox_id]["files"][source_path])

async def status(self, handle) -> SandboxStatus:
box = _STORE.get(handle.sandbox_id)
if box is None:
return SandboxStatus.UNKNOWN
return SandboxStatus.STOPPED if box["closed"] else SandboxStatus.RUNNING

async def close(self, handle) -> None:
box = _STORE.get(handle.sandbox_id)
if box is not None:
box["closed"] = True

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

async def serialize_handle(self, handle, *, scope=None) -> dict[str, Any]:
return {"sandbox_id": handle.sandbox_id}

async def connect(self, descriptor) -> SandboxHandle:
sid = str(descriptor["sandbox_id"])
if sid not in _STORE:
raise RuntimeError(f"no such sandbox {sid!r}")
return SandboxHandle(sandbox_id=sid, provider_name=self.name, raw=sid)


class _OpsOnlyProvider:
"""A provider without the connect capability (negative case)."""

name = "ops_only"

async def create(self, spec):
return SandboxHandle(sandbox_id="x", provider_name=self.name, raw="x")

async def exec(self, *a, **k):
return SandboxExecResult(stdout="", stderr=None, return_code=0)

async def upload_file(self, *a, **k):
return None

async def download_file(self, *a, **k):
return None

async def status(self, handle):
return SandboxStatus.RUNNING

async def close(self, handle):
return None

async def aclose(self):
return None


def test_connectable_provider_isinstance() -> None:
assert isinstance(FakeConnectableProvider(), ConnectableProvider)
assert not isinstance(_OpsOnlyProvider(), ConnectableProvider)


def test_serialize_then_connect_round_trip(tmp_path: Path) -> None:
async def _run() -> None:
sandbox = await AsyncSandbox(FakeConnectableProvider(), SandboxSpec(workdir="/w")).start()
payload = tmp_path / "f.txt"
payload.write_text("hello-connect")
await sandbox.upload(payload, "/w/f.txt")

descriptor = await sandbox.serialize()
assert "sandbox_id" in descriptor
# The facade carries workdir even though the provider descriptor omits it.
assert descriptor["workdir"] == "/w"

# A separate provider instance rebuilds a working handle from the descriptor.
reattached = await AsyncSandbox.connect(descriptor, provider=FakeConnectableProvider())
result = await reattached.exec("cat /w/f.txt")
assert result.return_code == 0
assert result.stdout == "hello-connect"

# The reattached sandbox defaults exec to the original working directory.
assert (await reattached.exec("pwd")).stdout == "/w"

asyncio.run(_run())


def test_serialize_requires_connect_capability() -> None:
async def _run() -> None:
sandbox = await AsyncSandbox(_OpsOnlyProvider(), SandboxSpec()).start()
with pytest.raises(RuntimeError, match="serialize"):
await sandbox.serialize()

asyncio.run(_run())


def test_connect_requires_connect_capability() -> None:
async def _run() -> None:
with pytest.raises(RuntimeError, match="serialize"):
await AsyncSandbox.connect({"sandbox_id": "x"}, provider=_OpsOnlyProvider())

asyncio.run(_run())
Loading