From b82fa1d9c73d803026e94c8ee5a020d3692b5d09 Mon Sep 17 00:00:00 2001 From: Ananth Subramaniam Date: Mon, 20 Jul 2026 10:02:16 -0700 Subject: [PATCH 1/2] feat(sandbox): add ConnectableProvider capability and serialize/connect facade Introduce an optional, runtime_checkable ConnectableProvider protocol (serialize_handle / connect), separate from the base SandboxProvider, so a provider whose sandbox is reachable by id can hand a descriptor to another process. Add AsyncSandbox.serialize and AsyncSandbox.connect, which delegate to the capability and raise for providers that do not support it. No in-tree provider implements the capability yet; a fake provider in the tests exercises the serialize/connect round-trip and the negative cases. Signed-off-by: Ananth Subramaniam --- nemo_gym/sandbox/__init__.py | 2 + nemo_gym/sandbox/api.py | 30 +++++ nemo_gym/sandbox/providers/__init__.py | 2 + nemo_gym/sandbox/providers/base.py | 24 +++- tests/unit_tests/test_sandbox_connect.py | 162 +++++++++++++++++++++++ 5 files changed, 219 insertions(+), 1 deletion(-) create mode 100644 tests/unit_tests/test_sandbox_connect.py diff --git a/nemo_gym/sandbox/__init__.py b/nemo_gym/sandbox/__init__.py index e85f5728db5..6d8840cdeb5 100644 --- a/nemo_gym/sandbox/__init__.py +++ b/nemo_gym/sandbox/__init__.py @@ -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, @@ -37,6 +38,7 @@ __all__ = [ "Sandbox", "AsyncSandbox", + "ConnectableProvider", "ExecResult", "SandboxCreateError", "SandboxCreateVerificationError", diff --git a/nemo_gym/sandbox/api.py b/nemo_gym/sandbox/api.py index 329baa8ad94..0c1cb707512 100644 --- a/nemo_gym/sandbox/api.py +++ b/nemo_gym/sandbox/api.py @@ -24,6 +24,7 @@ from typing import Any, TypeVar from nemo_gym.sandbox.providers import ( + ConnectableProvider, SandboxExecResult, SandboxHandle, SandboxProvider, @@ -131,6 +132,35 @@ 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()") + return await provider.serialize_handle(self._require_handle(), scope=scope) + + @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 diff --git a/nemo_gym/sandbox/providers/__init__.py b/nemo_gym/sandbox/providers/__init__.py index d1b2eed4967..bdc9205f9c7 100644 --- a/nemo_gym/sandbox/providers/__init__.py +++ b/nemo_gym/sandbox/providers/__init__.py @@ -15,6 +15,7 @@ """Sandbox provider registry.""" from nemo_gym.sandbox.providers.base import ( + ConnectableProvider, ExecResult, SandboxCreateError, SandboxCreateVerificationError, @@ -34,6 +35,7 @@ __all__ = [ + "ConnectableProvider", "ExecResult", "SandboxCreateError", "SandboxCreateVerificationError", diff --git a/nemo_gym/sandbox/providers/base.py b/nemo_gym/sandbox/providers/base.py index b8bca468bbe..52ef17995c6 100644 --- a/nemo_gym/sandbox/providers/base.py +++ b/nemo_gym/sandbox/providers/base.py @@ -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): @@ -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.""" + ... diff --git a/tests/unit_tests/test_sandbox_connect.py b/tests/unit_tests/test_sandbox_connect.py new file mode 100644 index 00000000000..b3a84eda415 --- /dev/null +++ b/tests/unit_tests/test_sandbox_connect.py @@ -0,0 +1,162 @@ +# 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) + 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 + + # 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" + + 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()) From b2f0d572fb74f16a588f6b26147290cf5c9e4b17 Mon Sep 17 00:00:00 2001 From: Ananth Subramaniam Date: Mon, 20 Jul 2026 10:27:11 -0700 Subject: [PATCH 2/2] fix(sandbox): carry workdir through serialize so reattach preserves it AsyncSandbox.connect rebuilds the spec from descriptor["workdir"] and exec defaults cwd to it. The remote provider's SandboxRef already includes workdir, but a provider whose descriptor omits it (e.g. OpenSandbox's {"sandbox_id"}) would lose the working directory on reattach. Have serialize() annotate the descriptor with the sandbox's workdir when the provider did not, so exec on a reattached sandbox defaults to the same directory for every provider. Signed-off-by: Ananth Subramaniam --- nemo_gym/sandbox/api.py | 8 +++++++- tests/unit_tests/test_sandbox_connect.py | 7 +++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/nemo_gym/sandbox/api.py b/nemo_gym/sandbox/api.py index 0c1cb707512..38faab4981d 100644 --- a/nemo_gym/sandbox/api.py +++ b/nemo_gym/sandbox/api.py @@ -143,7 +143,13 @@ async def serialize(self, *, scope: str | None = None) -> dict[str, Any]: if not isinstance(provider, ConnectableProvider): name = getattr(provider, "name", type(provider).__name__) raise RuntimeError(f"provider {name!r} does not support serialize()/connect()") - return await provider.serialize_handle(self._require_handle(), scope=scope) + 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": diff --git a/tests/unit_tests/test_sandbox_connect.py b/tests/unit_tests/test_sandbox_connect.py index b3a84eda415..33676e5cf18 100644 --- a/tests/unit_tests/test_sandbox_connect.py +++ b/tests/unit_tests/test_sandbox_connect.py @@ -61,6 +61,8 @@ async def exec(self, handle, command, *, cwd=None, env=None, timeout_s=None, use 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: @@ -135,6 +137,8 @@ async def _run() -> None: 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()) @@ -142,6 +146,9 @@ async def _run() -> None: 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())