Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

feat(cua-sandbox): migrate to the native fleet CRDs (#2840)

r33drichards6213b5811ad8
diff --git a/libs/python/cua-sandbox/.bumpversion.cfg b/libs/python/cua-sandbox/.bumpversion.cfg
index 8529d70544..c9e997e9f0 100644
--- a/libs/python/cua-sandbox/.bumpversion.cfg
+++ b/libs/python/cua-sandbox/.bumpversion.cfg
@@ -1,5 +1,5 @@
[bumpversion]
-current_version = 0.1.24
+current_version = 0.1.25
commit = True
tag = True
tag_name = sandbox-v{new_version}
diff --git a/libs/python/cua-sandbox/README.md b/libs/python/cua-sandbox/README.md
index 4ee34878a4..5df96557ce 100644
--- a/libs/python/cua-sandbox/README.md
+++ b/libs/python/cua-sandbox/README.md
@@ -92,17 +92,62 @@ Fleet is the OAuth cloud backend. Configure OAuth credentials once; Fleet uses `
Fleet does not support snapshots or custom disks, and currently supports only `us-east-1`. `await sb.tunnel.forward(3000)` returns the authenticated Fleet service URL for an exposed port; it does not open a local SSH tunnel.
-## Fleet pools
+## Fleet templates and pools
-Use a pool to keep reusable registry-image sandboxes warm. Reconciliation is idempotent: it creates a missing pool or updates the existing pool with the same name. Each claim is released when the context exits, including when the block raises.
+Use a pool to keep reusable registry-image sandboxes warm. The VM shape — image, resources, exposed services — lives in a *template*; a pool only says how many replicas to keep warm and which template to use. Reconcile the template first, then the pool that references it. Reconciliation is idempotent for both: it creates the missing resource or updates the existing one with the same name. Each claim is released when the context exits, including when the block raises.
```python
-from cua_sandbox import Image, Pool
+from cua_sandbox import (
+ CreatePoolRequest,
+ CreateTemplateRequest,
+ OsGymSandboxTemplateSpec,
+ OsGymSandboxWarmPoolSpec,
+ Pool,
+ SandboxService,
+ SandboxTemplateRef,
+ ServiceProtocol,
+ Template,
+ VmTemplate,
+)
+
+await Template.reconcile(
+ CreateTemplateRequest(
+ namespace="foo",
+ name="workspace",
+ spec=OsGymSandboxTemplateSpec(
+ vm_template=VmTemplate(
+ container_disk_image="registry.example/workspace:latest",
+ command=None,
+ runtime=None,
+ runtime_class_name=None,
+ node_selector=None,
+ tolerations=None,
+ image_pull_policy=None,
+ image_pull_secret="ecr-credentials",
+ cpu_cores=4,
+ memory="8Gi",
+ firmware=None,
+ probes=None,
+ services=[
+ SandboxService(name="server", target_port=8000, protocol=ServiceProtocol.TCP),
+ SandboxService(name="mcp", target_port=3000, protocol=ServiceProtocol.TCP),
+ ],
+ oidc=None,
+ ),
+ ),
+ )
+)
-pool = await Pool.reconcile({
- "name": "foo",
- "image": Image.from_registry("registry.example/workspace:latest"),
-})
+pool = await Pool.reconcile(
+ CreatePoolRequest(
+ namespace="foo",
+ spec=OsGymSandboxWarmPoolSpec(
+ replicas=1,
+ sandbox_template_ref=SandboxTemplateRef(name="workspace"),
+ autoscaling=None,
+ ),
+ )
+)
async with pool.claim() as sb:
result = await sb.shell.run("echo hello")
@@ -117,10 +162,10 @@ async with pool.claim() as sb:
For scripts that use the synchronous facade:
```python
-from cua_sandbox import Image
-from cua_sandbox.sync import Pool
+from cua_sandbox.sync import Pool, Template
-pool = Pool.reconcile({"name": "foo", "image": Image.from_registry("example:latest")})
+Template.reconcile(template_request) # same CreateTemplateRequest as above
+pool = Pool.reconcile(pool_request) # same CreatePoolRequest as above
with pool.claim() as sb:
result = sb.shell.run("echo hello")
```
diff --git a/libs/python/cua-sandbox/cua_sandbox/__init__.py b/libs/python/cua-sandbox/cua_sandbox/__init__.py
index ee6eadacf0..62481efda9 100644
--- a/libs/python/cua-sandbox/cua_sandbox/__init__.py
+++ b/libs/python/cua-sandbox/cua_sandbox/__init__.py
@@ -22,7 +22,7 @@ from cua_sandbox._auth import login, whoami
from cua_sandbox._config import configure
from cua_sandbox.image import Image
from cua_sandbox.localhost import Localhost, localhost
-from cua_sandbox.pool import Pool
+from cua_sandbox.pool import Pool, Template
from cua_sandbox.runtime.compat import (
RuntimeSupport,
check_local_support,
@@ -33,14 +33,19 @@ from cua_sandbox.transport.cloud import CloudTransport
from fleet_sdk import (
ClaimSpec,
CreatePoolRequest,
+ CreateTemplateRequest,
Firmware,
- PoolSpec,
- PoolTemplate,
+ OsGymSandboxTemplateSpec,
+ OsGymSandboxWarmPoolSpec,
RuntimeKind,
SandboxService,
SandboxTemplateRef,
ServiceProtocol,
)
+from fleet_sdk import Template as TemplateResource
+from fleet_sdk import (
+ VmTemplate,
+)
__all__ = [
"configure",
@@ -48,12 +53,16 @@ __all__ = [
"whoami",
"Image",
"Pool",
+ "Template",
+ "TemplateResource",
"CreatePoolRequest",
+ "CreateTemplateRequest",
"ClaimSpec",
"SandboxTemplateRef",
- "PoolSpec",
+ "OsGymSandboxWarmPoolSpec",
+ "OsGymSandboxTemplateSpec",
"RuntimeKind",
- "PoolTemplate",
+ "VmTemplate",
"SandboxService",
"ServiceProtocol",
"Firmware",
diff --git a/libs/python/cua-sandbox/cua_sandbox/pool.py b/libs/python/cua-sandbox/cua_sandbox/pool.py
index d84090bb41..08ad1cb070 100644
--- a/libs/python/cua-sandbox/cua_sandbox/pool.py
+++ b/libs/python/cua-sandbox/cua_sandbox/pool.py
@@ -1,4 +1,4 @@
-"""Fleet pool API for reusable cloud sandboxes."""
+"""Fleet template and pool APIs for reusable cloud sandboxes."""
from __future__ import annotations
@@ -14,18 +14,64 @@ from fleet_sdk import (
ClaimSpec,
CreateClaimRequest,
CreatePoolRequest,
+ CreateTemplateRequest,
)
logger = logging.getLogger(__name__)
+class Template:
+ """A reconciled Fleet sandbox template.
+
+ A template holds the VM shape — image, resources, firmware, exposed
+ services — that warm pools and claims reference by name through
+ ``spec.sandboxTemplateRef``. Reconcile a template before reconciling a
+ pool that points at it.
+
+ Template instances retain only Fleet resource metadata; each call opens
+ and closes its own Fleet client.
+ """
+
+ def __init__(self, resource: Any) -> None:
+ self._resource = resource
+
+ @property
+ def name(self) -> str:
+ """The template name."""
+ return cast(str, self._resource.metadata.name)
+
+ @property
+ def resource(self) -> Any:
+ """The underlying Fleet SDK template resource."""
+ return self._resource
+
+ @classmethod
+ async def reconcile(cls, request: CreateTemplateRequest) -> "Template":
+ """Create or update a Fleet sandbox template from a native request.
+
+ The request is passed unchanged to the generated Fleet client. Import
+ ``CreateTemplateRequest`` and its nested schema types from
+ ``cua_sandbox`` so callers do not depend on the generated binding
+ package directly.
+ """
+ if not isinstance(request, CreateTemplateRequest):
+ raise TypeError("Template.reconcile requires a CreateTemplateRequest")
+ client = _FleetClient()
+ try:
+ return cls(await client.reconcile_template(request))
+ finally:
+ await client.close()
+
+
class Pool:
"""A reconciled Fleet pool that can lease cloud sandboxes.
``reconcile`` creates a pool when it is absent and updates its desired
- configuration when it already exists. The supplied ``image`` must be an
- :meth:`Image.from_registry` image; Fleet does not support locally-built
- images, layers, snapshots, or custom disks.
+ configuration when it already exists. A pool carries no VM shape of its
+ own: it names a :class:`Template` through ``spec.sandboxTemplateRef``, so
+ reconcile that template first. Fleet templates require an
+ :meth:`Image.from_registry` image; locally-built images, layers,
+ snapshots, and custom disks are not supported.
Pool instances retain only Fleet resource metadata. Each call to
:meth:`claim` creates and closes its own Fleet client, so a Pool may be
diff --git a/libs/python/cua-sandbox/cua_sandbox/sandbox.py b/libs/python/cua-sandbox/cua_sandbox/sandbox.py
index 553342f55d..783a04162b 100644
--- a/libs/python/cua-sandbox/cua_sandbox/sandbox.py
+++ b/libs/python/cua-sandbox/cua_sandbox/sandbox.py
@@ -727,8 +727,8 @@ class Sandbox:
spec = pool.get("spec") or {}
status = pool.get("status") or {}
replicas = spec.get("replicas", 1)
- available = status.get("availableCount", 0)
- state = "suspended" if replicas == 0 else "running" if available else "provisioning"
+ ready = status.get("readyReplicas", 0)
+ state = "suspended" if replicas == 0 else "running" if ready else "provisioning"
return SandboxInfo(
name=metadata.get("name", ""),
status=state,
diff --git a/libs/python/cua-sandbox/cua_sandbox/sync/__init__.py b/libs/python/cua-sandbox/cua_sandbox/sync/__init__.py
index c7ec3462e4..fcb8be7eee 100644
--- a/libs/python/cua-sandbox/cua_sandbox/sync/__init__.py
+++ b/libs/python/cua-sandbox/cua_sandbox/sync/__init__.py
@@ -23,8 +23,9 @@ from typing import Any, Iterator, Optional
from cua_sandbox.image import Image
from cua_sandbox.localhost import Localhost as _AsyncLocalhost
from cua_sandbox.pool import Pool as _AsyncPool
+from cua_sandbox.pool import Template as _AsyncTemplate
from cua_sandbox.sandbox import Sandbox as _AsyncSandbox
-from fleet_sdk import ClaimSpec, CreatePoolRequest
+from fleet_sdk import ClaimSpec, CreatePoolRequest, CreateTemplateRequest
def _get_or_create_loop() -> asyncio.AbstractEventLoop:
@@ -74,6 +75,22 @@ class _SyncProxy:
return f"Sync({self._async_obj!r})"
+class Template:
+ """Blocking facade for :class:`cua_sandbox.Template`."""
+
+ def __init__(self, async_template: _AsyncTemplate) -> None:
+ self._async_template = async_template
+
+ @property
+ def name(self) -> str:
+ return self._async_template.name
+
+ @classmethod
+ def reconcile(cls, request: CreateTemplateRequest) -> "Template":
+ """Synchronously create or update a Fleet sandbox template."""
+ return cls(_run(_AsyncTemplate.reconcile(request)))
+
+
class Pool:
"""Blocking facade for :class:`cua_sandbox.Pool`.
diff --git a/libs/python/cua-sandbox/cua_sandbox/transport/fleet_cloud.py b/libs/python/cua-sandbox/cua_sandbox/transport/fleet_cloud.py
index 9965167be0..3ad9023d6c 100644
--- a/libs/python/cua-sandbox/cua_sandbox/transport/fleet_cloud.py
+++ b/libs/python/cua-sandbox/cua_sandbox/transport/fleet_cloud.py
@@ -20,15 +20,18 @@ from cua_sandbox.transport.fleet import FleetTransport
from fleet_sdk import (
CreateClaimRequest,
CreatePoolRequest,
+ CreateTemplateRequest,
CyclopsClient,
CyclopsConfiguration,
CyclopsCredentials,
HttpRequest,
- PoolSpec,
- PoolTemplate,
+ OsGymSandboxTemplateSpec,
+ OsGymSandboxWarmPoolSpec,
PreservedJson,
SandboxService,
+ SandboxTemplateRef,
ServiceProtocol,
+ VmTemplate,
)
if TYPE_CHECKING:
@@ -70,6 +73,18 @@ class _FleetClient:
async def reconcile_pool(self, request: CreatePoolRequest) -> Any:
return await self._client.reconcile_pool(request)
+ async def create_template(self, request: CreateTemplateRequest) -> Any:
+ return await self._client.create_template(request)
+
+ async def reconcile_template(self, request: CreateTemplateRequest) -> Any:
+ return await self._client.reconcile_template(request)
+
+ async def get_template(self, namespace: str, name: str) -> Any:
+ return await self._client.get_template(namespace, name)
+
+ async def delete_template(self, template: Any) -> None:
+ await self._client.delete_template(template)
+
async def create_claim(self, request: CreateClaimRequest) -> Any:
return await self._client.create_claim(request)
@@ -80,7 +95,7 @@ class _FleetClient:
for current_pool in pools:
if current_pool.metadata.name != pool.metadata.name:
continue
- if current_pool.status and (current_pool.status.available_count or 0) >= 1:
+ if current_pool.status and (current_pool.status.ready_replicas or 0) >= 1:
return current_pool
break
if asyncio.get_running_loop().time() >= deadline:
@@ -215,6 +230,7 @@ class FleetCloudTransport(FleetTransport):
self._services = dict(services) if services is not None else None
self._provisioned = False
self._owns_resources = image is not None
+ self._template: Any = None
self._pool: Any = None
self._claim: Any = None
self._sdk: Any = None
@@ -233,6 +249,7 @@ class FleetCloudTransport(FleetTransport):
self._pool = await self._sdk.get_pool(self._name)
else:
self._validate_image(self._image)
+ self._template = await self._sdk.create_template(self._template_request())
self._pool = await self._sdk.create_pool(self._pool_request())
self._pool = await self._sdk.wait_pool(self._pool)
if self._claim is None:
@@ -294,6 +311,9 @@ class FleetCloudTransport(FleetTransport):
if self._pool is not None:
await self._sdk.delete_pool(self._pool)
self._pool = None
+ if self._template is not None:
+ await self._sdk.delete_template(self._template)
+ self._template = None
self._provisioned = False
@classmethod
@@ -339,12 +359,16 @@ class FleetCloudTransport(FleetTransport):
sdk = _FleetClient()
try:
pool = await sdk.get_pool(name)
+ template_name = pool.spec.sandbox_template_ref.name
await sdk.delete_claim(await sdk.get_claim(pool))
await sdk.delete_pool(pool)
+ await sdk.delete_template(
+ await sdk.get_template(pool.metadata.namespace, template_name)
+ )
finally:
await sdk.close()
- def _pool_request(self) -> CreatePoolRequest:
+ def _template_request(self) -> CreateTemplateRequest:
assert self._image is not None
service_ports = self._services or {
"server": 8000,
@@ -354,18 +378,18 @@ class FleetCloudTransport(FleetTransport):
SandboxService(name=name, target_port=port, protocol=ServiceProtocol.TCP)
for name, port in service_ports.items()
]
- return CreatePoolRequest(
+ return CreateTemplateRequest(
namespace=self._name,
- spec=PoolSpec(
- replicas=self._replicas,
- services=services,
- template=PoolTemplate(
+ name=self._name,
+ spec=OsGymSandboxTemplateSpec(
+ vm_template=VmTemplate(
+ container_disk_image=self._image._registry,
+ command=None,
runtime=None,
runtime_class_name=None,
node_selector=None,
tolerations=None,
- command=None,
- container_disk_image=self._image._registry,
+ image_pull_policy=None,
image_pull_secret="ecr-credentials",
cpu_cores=self._cpu,
memory=None if self._memory_mb is None else f"{self._memory_mb}Mi",
@@ -373,15 +397,25 @@ class FleetCloudTransport(FleetTransport):
probes=PreservedJson.from_json(
json.dumps({"readinessProbe": {"tcpSocket": {"port": 8000}}})
),
+ services=services,
oidc=None,
),
+ ),
+ )
+
+ def _pool_request(self) -> CreatePoolRequest:
+ return CreatePoolRequest(
+ namespace=self._name,
+ spec=OsGymSandboxWarmPoolSpec(
+ replicas=self._replicas,
+ sandbox_template_ref=SandboxTemplateRef(name=self._name),
autoscaling=None,
),
)
@staticmethod
- def _service_names(pool: Any) -> list[str]:
- return [service.name for service in pool.spec.services or []] or ["server"]
+ def _service_names(template: Any) -> list[str]:
+ return [service.name for service in template.spec.vm_template.services or []] or ["server"]
@staticmethod
def _validate_image(image: Image) -> None:
diff --git a/libs/python/cua-sandbox/pyproject.toml b/libs/python/cua-sandbox/pyproject.toml
index b9b3b09d9e..6b71817a04 100644
--- a/libs/python/cua-sandbox/pyproject.toml
+++ b/libs/python/cua-sandbox/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "cua-sandbox"
-version = "0.1.24"
+version = "0.1.25"
description = "CUA Sandbox — ephemeral and persistent sandboxed computer environments"
readme = "README.md"
license = "MIT"
@@ -29,7 +29,7 @@ requires-python = ">=3.11,<3.14"
dependencies = [
"cua-core>=0.3.0,<0.4.0",
"cua-auto>=0.1.2",
- "cua-fleet==0.0.8",
+ "cua-fleet==0.0.9",
"websockets>=12.0",
"httpx>=0.27.0",
"oras>=0.2.40",
diff --git a/libs/python/cua-sandbox/tests/test_fleet_cloud_client.py b/libs/python/cua-sandbox/tests/test_fleet_cloud_client.py
index fced7e9be0..09800cac1e 100644
--- a/libs/python/cua-sandbox/tests/test_fleet_cloud_client.py
+++ b/libs/python/cua-sandbox/tests/test_fleet_cloud_client.py
@@ -1,7 +1,65 @@
+from types import SimpleNamespace
+
import pytest
from cua_sandbox.transport.fleet_cloud import _FleetClient
+async def test_wait_pool_returns_once_a_replica_is_ready():
+ client = _FleetClient.__new__(_FleetClient)
+ warming = SimpleNamespace(
+ metadata=SimpleNamespace(name="demo", namespace="demo"),
+ status=SimpleNamespace(replicas=1, ready_replicas=0, selector=None),
+ )
+ ready = SimpleNamespace(
+ metadata=SimpleNamespace(name="demo", namespace="demo"),
+ status=SimpleNamespace(replicas=1, ready_replicas=1, selector=None),
+ )
+ listings = iter([[warming], [ready]])
+
+ class SDK:
+ async def list_pools(self, namespace):
+ assert namespace == "demo"
+ return next(listings)
+
+ client._client = SDK()
+ assert await client.wait_pool(warming, poll_interval=0) is ready
+
+
+async def test_template_calls_delegate_to_generated_client():
+ client = _FleetClient.__new__(_FleetClient)
+ calls = []
+
+ class SDK:
+ async def reconcile_template(self, request):
+ calls.append(("reconcile", request))
+ return "template"
+
+ async def create_template(self, request):
+ calls.append(("create", request))
+ return "template"
+
+ async def get_template(self, namespace, name):
+ calls.append(("get", namespace, name))
+ return "template"
+
+ async def delete_template(self, template):
+ calls.append(("delete", template))
+
+ client._client = SDK()
+ assert await client.reconcile_template("request") == "template"
+ assert await client.create_template("request") == "template"
+ assert await client.get_template("demo", "workspace") == "template"
+ assert await client.delete_template("template") is None
+ assert calls == [
+ ("reconcile", "request"),
+ ("create", "request"),
+ ("get", "demo", "workspace"),
+ ("delete", "template"),
+ ]
+
+
@pytest.mark.asyncio
async def test_list_pools_enumerates_namespaces(monkeypatch):
client = _FleetClient.__new__(_FleetClient)
@@ -36,17 +94,3 @@ async def test_service_request_delegates_to_generated_client():
client._client = SDK()
assert await client.service_request("sandbox", "server", "/status", "request") == "response"
assert calls == [("sandbox", "server", "/status", "request")]
-
-
-async def test_pool_lookup_matches_sdk_resources():
- client = _FleetClient.__new__(_FleetClient)
- pool = type("Pool", (), {"metadata": type("Metadata", (), {"name": "demo"})()})()
-
- async def list_pools():
- return [pool]
-
- client.list_pools = list_pools
- assert await client.get_pool("demo") is pool
- with pytest.raises(LookupError):
- await client.get_pool("missing")
diff --git a/libs/python/cua-sandbox/tests/test_fleet_cloud_transport.py b/libs/python/cua-sandbox/tests/test_fleet_cloud_transport.py
index e21237fa75..af5865927d 100644
--- a/libs/python/cua-sandbox/tests/test_fleet_cloud_transport.py
+++ b/libs/python/cua-sandbox/tests/test_fleet_cloud_transport.py
@@ -5,23 +5,36 @@ from cua_sandbox.transport.fleet_cloud import FleetCloudTransport
from fleet_sdk import Sandbox
-def test_registry_image_becomes_typed_pool_request():
+def test_registry_image_becomes_typed_template_request():
request = FleetCloudTransport(
image=Image.from_registry("registry.example/workspace@sha256:abc").expose(3000),
name="demo",
cpu=4,
memory_mb=8192,
- )._pool_request()
- assert request.namespace == "demo"
- assert request.spec.template.container_disk_image == "registry.example/workspace@sha256:abc"
- assert request.spec.template.cpu_cores == 4
- assert request.spec.template.memory == "8192Mi"
- assert [(service.name, service.target_port) for service in request.spec.services] == [
+ )._template_request()
+ assert (request.namespace, request.name) == ("demo", "demo")
+ vm_template = request.spec.vm_template
+ assert vm_template.container_disk_image == "registry.example/workspace@sha256:abc"
+ assert vm_template.cpu_cores == 4
+ assert vm_template.memory == "8192Mi"
+ assert [(service.name, service.target_port) for service in vm_template.services] == [
("server", 8000),
("port-3000", 3000),
]
+def test_pool_request_only_references_the_template():
+ request = FleetCloudTransport(
+ image=Image.from_registry("registry.example/workspace@sha256:abc"),
+ name="demo",
+ replicas=3,
+ )._pool_request()
+ assert request.namespace == "demo"
+ assert request.spec.replicas == 3
+ assert request.spec.sandbox_template_ref.name == "demo"
+ assert request.spec.autoscaling is None
+
+
@pytest.mark.parametrize(
"image", [Image.linux(), Image.from_registry("example:latest").apt_install("curl")]
)
@@ -31,12 +44,20 @@ def test_rejects_unsupported_images(image):
@pytest.mark.asyncio
-async def test_connect_uses_generated_pool_template_claim_default(monkeypatch):
+async def test_connect_creates_template_before_pool_and_defaults_the_claim(monkeypatch):
pool = type("Pool", (), {"metadata": type("Metadata", (), {"name": "demo"})()})()
requests = []
+ order = []
class Client:
+ async def create_template(self, request):
+ order.append("template")
+ assert request.spec.vm_template.container_disk_image == "example:latest"
+ return "template"
+
async def create_pool(self, request):
+ order.append("pool")
+ assert request.spec.sandbox_template_ref.name == "demo"
return pool
async def wait_pool(self, created_pool):
@@ -57,6 +78,7 @@ async def test_connect_uses_generated_pool_template_claim_default(monkeypatch):
await FleetCloudTransport(image=Image.from_registry("example:latest"), name="demo").connect()
+ assert order == ["template", "pool"]
assert len(requests) == 1
assert requests[0].spec is None
@@ -82,6 +104,30 @@ async def test_cleanup_stops_after_claim_failure():
assert calls == [("claim", "claim")]
+async def test_cleanup_releases_claim_pool_then_template():
+ transport = FleetCloudTransport(image=Image.from_registry("example:latest"), name="demo")
+ calls = []
+
+ class Client:
+ async def delete_claim(self, claim):
+ calls.append(("claim", claim))
+
+ async def delete_pool(self, pool):
+ calls.append(("pool", pool))
+
+ async def delete_template(self, template):
+ calls.append(("template", template))
+
+ transport._sdk = Client()
+ transport._claim = "claim"
+ transport._pool = "pool"
+ transport._template = "template"
+ await transport._cleanup_resources()
+ assert calls == [("claim", "claim"), ("pool", "pool"), ("template", "template")]
+ assert transport._template is None
+
+
@pytest.mark.asyncio
async def test_forward_tunnel_uses_named_service_url():
transport = FleetCloudTransport(image=Image.from_registry("example:latest"), name="demo")
diff --git a/libs/python/cua-sandbox/tests/test_fleet_sdk_packaging.py b/libs/python/cua-sandbox/tests/test_fleet_sdk_packaging.py
index 6c9ad4e47b..7ae581a12a 100644
--- a/libs/python/cua-sandbox/tests/test_fleet_sdk_packaging.py
+++ b/libs/python/cua-sandbox/tests/test_fleet_sdk_packaging.py
@@ -17,9 +17,9 @@ class FleetSdkPackagingTests(unittest.TestCase):
with PYPROJECT_PATH.open("rb") as pyproject_file:
project = tomllib.load(pyproject_file)
- self.assertEqual(project["project"]["version"], "0.1.20")
+ self.assertEqual(project["project"]["version"], "0.1.25")
dependencies = project["project"]["dependencies"]
- self.assertIn("cua-fleet==0.0.8", dependencies)
+ self.assertIn("cua-fleet==0.0.9", dependencies)
self.assertFalse(any(dependency.startswith("cua-train") for dependency in dependencies))
self.assertNotIn("cua-fleet", project["tool"]["uv"]["sources"])
self.assertNotIn("cua-train", project["tool"]["uv"]["sources"])
@@ -50,7 +50,7 @@ class FleetSdkPackagingTests(unittest.TestCase):
self.assertNotIn("cua-train", sandbox_dependencies)
self.assertIn("cua-fleet", sandbox_requires_dist)
self.assertNotIn("cua-train", sandbox_requires_dist)
- self.assertEqual(packages["cua-fleet"]["version"], "0.0.8")
+ self.assertEqual(packages["cua-fleet"]["version"], "0.0.9")
self.assertEqual(packages["cua-fleet"]["source"], {"registry": "https://pypi.org/simple"})
self.assertNotIn("cua-train", fleet_dependencies)
self.assertNotIn("cua-train", packages)
diff --git a/libs/python/cua-sandbox/tests/test_pool.py b/libs/python/cua-sandbox/tests/test_pool.py
index 5adf0f273f..e2821cd53f 100644
--- a/libs/python/cua-sandbox/tests/test_pool.py
+++ b/libs/python/cua-sandbox/tests/test_pool.py
@@ -6,16 +6,20 @@ import pytest
from cua_sandbox import (
ClaimSpec,
CreatePoolRequest,
+ CreateTemplateRequest,
Firmware,
+ OsGymSandboxTemplateSpec,
+ OsGymSandboxWarmPoolSpec,
Pool,
- PoolSpec,
- PoolTemplate,
RuntimeKind,
SandboxService,
SandboxTemplateRef,
ServiceProtocol,
+ Template,
+ VmTemplate,
)
from cua_sandbox.sync import Pool as SyncPool
+from cua_sandbox.sync import Template as SyncTemplate
from cua_sandbox.transport.fleet_cloud import _FleetClient
from fleet_sdk import Sandbox as FleetSandbox
@@ -27,35 +31,52 @@ def test_public_pool_schema_exports_runtime_kind() -> None:
def pool_request(
*,
name: str = "foo",
- image: str = "example:latest",
+ template_name: str | None = None,
replicas: int = 1,
- services: dict[str, int] | None = None,
- template: PoolTemplate | None = None,
) -> CreatePoolRequest:
return CreatePoolRequest(
namespace=name,
- spec=PoolSpec(
+ spec=OsGymSandboxWarmPoolSpec(
replicas=replicas,
- services=[
- SandboxService(name=service_name, target_port=port, protocol=ServiceProtocol.TCP)
- for service_name, port in (services or {"server": 8000}).items()
- ],
- template=template
- or PoolTemplate(
+ sandbox_template_ref=SandboxTemplateRef(name=template_name or name),
+ autoscaling=None,
+ ),
+ )
+
+
+def template_request(
+ *,
+ name: str = "foo",
+ image: str = "example:latest",
+ services: dict[str, int] | None = None,
+ vm_template: VmTemplate | None = None,
+) -> CreateTemplateRequest:
+ return CreateTemplateRequest(
+ namespace=name,
+ name=name,
+ spec=OsGymSandboxTemplateSpec(
+ vm_template=vm_template
+ or VmTemplate(
+ container_disk_image=image,
+ command=None,
runtime=None,
runtime_class_name=None,
node_selector=None,
tolerations=None,
- command=None,
- container_disk_image=image,
+ image_pull_policy=None,
image_pull_secret="ecr-credentials",
cpu_cores=None,
memory=None,
firmware=None,
probes=None,
+ services=[
+ SandboxService(
+ name=service_name, target_port=port, protocol=ServiceProtocol.TCP
+ )
+ for service_name, port in (services or {"server": 8000}).items()
+ ],
oidc=None,
),
- autoscaling=None,
),
)
@@ -63,7 +84,19 @@ def pool_request(
def fleet_pool(name: str = "foo") -> SimpleNamespace:
return SimpleNamespace(
metadata=SimpleNamespace(name=name, namespace=name),
- spec=SimpleNamespace(services=[]),
+ spec=SimpleNamespace(
+ replicas=1,
+ sandbox_template_ref=SimpleNamespace(name=name),
+ autoscaling=None,
+ ),
+ status=SimpleNamespace(replicas=1, ready_replicas=1, selector=None),
+ )
+
+
+def fleet_template(name: str = "foo") -> SimpleNamespace:
+ return SimpleNamespace(
+ metadata=SimpleNamespace(name=name, namespace=name),
+ spec=SimpleNamespace(vm_template=SimpleNamespace(services=[])),
)
@@ -79,6 +112,7 @@ class FakeFleetClient:
self.reconcile_error = reconcile_error
self.release_error = release_error
self.reconciled: list[object] = []
+ self.reconciled_templates: list[object] = []
self.claims: list[object] = []
self.released: list[object] = []
self.service_requests: list[object] = []
@@ -90,6 +124,12 @@ class FakeFleetClient:
raise self.reconcile_error
return self.existing or fleet_pool(request.namespace)
+ async def reconcile_template(self, request: object) -> object:
+ self.reconciled_templates.append(request)
+ if self.reconcile_error:
+ raise self.reconcile_error
+ return self.existing or fleet_template(request.name)
+
async def create_claim(self, request: object) -> object:
self.claims.append(request)
return "claim-1"
@@ -152,15 +192,26 @@ async def test_fleet_client_reconcile_pool_delegates_to_generated_client() -> No
@pytest.mark.asyncio
-async def test_reconcile_creates_pool_from_registry_image(monkeypatch):
+async def test_fleet_client_reconcile_template_delegates_to_generated_client() -> None:
+ expected = fleet_template()
+
+ class GeneratedClient:
+ async def reconcile_template(self, request: object) -> object:
+ assert request == "desired"
+ return expected
+
+ client = object.__new__(_FleetClient)
+ client._client = GeneratedClient()
+
+ assert await client.reconcile_template("desired") is expected
+
+
+async def test_reconcile_creates_pool_referencing_a_template(monkeypatch):
client = FakeFleetClient()
monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: client)
- request = pool_request(
- image="registry.example/workspace:latest",
- services={"server": 8000, "port-3000": 3000},
- )
- pool = await Pool.reconcile(request)
+ pool = await Pool.reconcile(pool_request(template_name="workspace"))
assert pool.name == "foo"
assert pool.resource.metadata.name == "foo"
@@ -168,13 +219,61 @@ async def test_reconcile_creates_pool_from_registry_image(monkeypatch):
assert len(client.reconciled) == 1
request = client.reconciled[0]
assert request.namespace == "foo"
- assert request.spec.template.container_disk_image == "registry.example/workspace:latest"
- assert [(service.name, service.target_port) for service in request.spec.services] == [
+ assert request.spec.sandbox_template_ref.name == "workspace"
+ assert request.spec.replicas == 1
+
+
+async def test_template_reconcile_creates_template_from_registry_image(monkeypatch):
+ client = FakeFleetClient()
+ monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: client)
+
+ request = template_request(
+ image="registry.example/workspace:latest",
+ services={"server": 8000, "port-3000": 3000},
+ )
+ template = await Template.reconcile(request)
+
+ assert template.name == "foo"
+ assert template.resource.metadata.name == "foo"
+ assert client.closed is True
+ assert client.reconciled_templates == [request]
+ vm_template = client.reconciled_templates[0].spec.vm_template
+ assert vm_template.container_disk_image == "registry.example/workspace:latest"
+ assert [(service.name, service.target_port) for service in vm_template.services] == [
("server", 8000),
("port-3000", 3000),
]
+async def test_template_reconcile_closes_temporary_client_when_reconciliation_fails(monkeypatch):
+ client = FakeFleetClient(reconcile_error=RuntimeError("reconcile failed"))
+ monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: client)
+
+ with pytest.raises(RuntimeError, match="reconcile failed"):
+ await Template.reconcile(template_request())
+
+ assert client.closed is True
+
+
[email protected]("invalid_value", [None, {}, "not-a-request", pool_request()])
+async def test_template_reconcile_rejects_non_request(invalid_value):
+ with pytest.raises(TypeError, match="CreateTemplateRequest"):
+ await Template.reconcile(invalid_value)
+
+
+def test_sync_template_reconcile_matches_async_facade(monkeypatch):
+ client = FakeFleetClient()
+ monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: client)
+
+ template = SyncTemplate.reconcile(template_request())
+
+ assert template.name == "foo"
+ assert client.closed is True
+
+
@pytest.mark.asyncio
async def test_reconcile_closes_temporary_client_when_reconciliation_fails(monkeypatch):
client = FakeFleetClient(reconcile_error=RuntimeError("reconcile failed"))
@@ -196,7 +295,7 @@ async def test_reconcile_updates_existing_pool_idempotently(monkeypatch):
assert pool.resource is existing
assert len(client.reconciled) == 1
- assert client.reconciled[0].spec.template.container_disk_image == "example:latest"
+ assert client.reconciled[0].spec.sandbox_template_ref.name == "foo"
assert client.closed is True
@@ -279,20 +378,31 @@ def test_sync_pool_matches_blocking_context_manager(monkeypatch):
@pytest.mark.asyncio
-async def test_reconcile_preserves_replicas_and_named_services(monkeypatch):
+async def test_reconcile_preserves_replicas_and_template_reference(monkeypatch):
client = FakeFleetClient()
monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: client)
- request = pool_request(
- image="registry.example/workspace:latest",
- replicas=2,
- services={"server": 8000, "mcp": 3000},
- )
- await Pool.reconcile(request)
+ await Pool.reconcile(pool_request(replicas=2, template_name="workspace"))
request = client.reconciled[0]
assert request.spec.replicas == 2
- assert [(service.name, service.target_port) for service in request.spec.services] == [
+ assert request.spec.sandbox_template_ref.name == "workspace"
+
+
+async def test_template_reconcile_preserves_named_services(monkeypatch):
+ client = FakeFleetClient()
+ monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: client)
+
+ await Template.reconcile(
+ template_request(
+ image="registry.example/workspace:latest",
+ services={"server": 8000, "mcp": 3000},
+ )
+ )
+
+ vm_template = client.reconciled_templates[0].spec.vm_template
+ assert [(service.name, service.target_port) for service in vm_template.services] == [
("server", 8000),
("mcp", 3000),
]
@@ -302,29 +412,41 @@ async def test_reconcile_preserves_replicas_and_named_services(monkeypatch):
async def test_reconcile_forwards_native_create_pool_request_unchanged(monkeypatch):
client = FakeFleetClient()
monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: client)
- request = pool_request(
- image="registry.example/workspace:latest",
- replicas=2,
- services={"server": 8000, "mcp": 3000},
- template=PoolTemplate(
- runtime=None,
+ request = pool_request(replicas=2, template_name="workspace")
+
+ await Pool.reconcile(request)
+
+ assert client.reconciled == [request]
+
+
+async def test_template_reconcile_forwards_native_request_unchanged(monkeypatch):
+ client = FakeFleetClient()
+ monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: client)
+ request = template_request(
+ vm_template=VmTemplate(
+ container_disk_image="registry.example/workspace:latest",
+ command=None,
+ runtime=RuntimeKind.KUBEVIRT,
runtime_class_name=None,
node_selector=None,
tolerations=None,
- command=None,
- container_disk_image="registry.example/workspace:latest",
+ image_pull_policy=None,
image_pull_secret="workspace-pull",
cpu_cores=10,
memory="20Gi",
firmware=Firmware.EFI,
probes=None,
+ services=[
+ SandboxService(name="server", target_port=8000, protocol=ServiceProtocol.TCP)
+ ],
oidc=None,
),
)
- await Pool.reconcile(request)
+ await Template.reconcile(request)
- assert client.reconciled == [request]
+ assert client.reconciled_templates == [request]
@pytest.mark.asyncio
diff --git a/libs/python/cua-sandbox/uv.lock b/libs/python/cua-sandbox/uv.lock
index 3f693c47a2..7be6dde92b 100644
--- a/libs/python/cua-sandbox/uv.lock
+++ b/libs/python/cua-sandbox/uv.lock
@@ -539,7 +539,7 @@ dev = [{ name = "pytest", specifier = ">=8.3.5" }]
[[package]]
name = "cua-fleet"
-version = "0.0.8"
+version = "0.0.9"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "attrs" },
@@ -547,15 +547,15 @@ dependencies = [
{ name = "python-dateutil" },
]
wheels = [
- { url = "https://files.pythonhosted.org/packages/d1/9d/f1f800c746c3f4137d21864293db3d2cded36125dc4fd0547c9def35beff/cua_fleet-0.0.8-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:d62ba6b263e858ff7157e1dfb317b1526a7b6fe2dba76479621490393efb2f8e", size = 2126597, upload-time = "2026-08-02T17:12:56.242Z" },
- { url = "https://files.pythonhosted.org/packages/0c/ce/dedd4f4847bc1c7da18bd1f58d75c0c03da1fa50f30d0720a74dcf6705e3/cua_fleet-0.0.8-py3-none-macosx_11_0_arm64.whl", hash = "sha256:4a3fd42fe75520ae0070935d13ce22e28b5c121852d6e39d65eed3df35cb3dd0", size = 2040766, upload-time = "2026-08-02T17:12:57.96Z" },
- { url = "https://files.pythonhosted.org/packages/cb/97/09faebc28ce1b2d7e6882861e6f9f1a3788abe5bc286e23a55e8d9b1caac/cua_fleet-0.0.8-py3-none-manylinux_2_34_aarch64.whl", hash = "sha256:776a1287c474362d76a5240dfd868be3ad29d36a51114519d2b06c8061f51036", size = 2304088, upload-time = "2026-08-02T17:13:00.066Z" },
- { url = "https://files.pythonhosted.org/packages/fb/36/0cd2f82e1cdd56e7330094ff3aa57ae9ab670b56e4e4500eb91e3e3f8580/cua_fleet-0.0.8-py3-none-manylinux_2_34_x86_64.whl", hash = "sha256:dee669f487ad3dafa176d80d236c5b5a89df0af8d46f86e756c720a1f683af36", size = 2357881, upload-time = "2026-08-02T17:13:01.999Z" },
+ { url = "https://files.pythonhosted.org/packages/dc/b8/fd15a0649a94c576af69d5cda60a78a47cd37a7d5abab6bcfe43456ef0f1/cua_fleet-0.0.9-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:1041153f664fb84fb68e1bf453db611590a28518fe56f511b531dd4e6c931aa4", size = 2109242, upload-time = "2026-08-04T15:35:40.587Z" },
+ { url = "https://files.pythonhosted.org/packages/0f/c0/19c161a492e1e051c7f8c6462a6df18d73d2539c8246bec97ef61c6c1521/cua_fleet-0.0.9-py3-none-macosx_11_0_arm64.whl", hash = "sha256:10177ae5d468461fa38ffccf8c34fccf10ac0a31e025d91a529174d2621718cf", size = 2020725, upload-time = "2026-08-04T15:35:42.226Z" },
+ { url = "https://files.pythonhosted.org/packages/39/ef/fb57cdb3f348b3ce763742b0a2954b7488fd73ddf26e669c74b36d1fa33f/cua_fleet-0.0.9-py3-none-manylinux_2_34_aarch64.whl", hash = "sha256:84f82e365671f6d33daf7dfcabde26434d0ed4c2bcfdebcf11f28c6ec31f0459", size = 2288295, upload-time = "2026-08-04T15:35:43.437Z" },
+ { url = "https://files.pythonhosted.org/packages/c8/d2/3915a34260d65685460334941bf2c4d7803a673243e5ed8c7caab03f01c9/cua_fleet-0.0.9-py3-none-manylinux_2_34_x86_64.whl", hash = "sha256:0f3558227fd9e86870d6f32ab4f2e0ae70d0453246b40ece8795743d7102f717", size = 2337412, upload-time = "2026-08-04T15:35:44.529Z" },
]
[[package]]
name = "cua-sandbox"
-version = "0.1.21"
+version = "0.1.25"
source = { editable = "." }
dependencies = [
{ name = "cua-auto" },
@@ -592,7 +592,7 @@ dev = [
requires-dist = [
{ name = "cua-auto", specifier = ">=0.1.2" },
{ name = "cua-core", specifier = ">=0.3.0,<0.4.0" },
- { name = "cua-fleet", specifier = "==0.0.8" },
+ { name = "cua-fleet", specifier = "==0.0.9" },
{ name = "grpcio", specifier = "==1.78.0" },
{ name = "httpx", specifier = ">=0.27.0" },
{ name = "oras", specifier = ">=0.2.40" },