Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
feat(cua-sandbox): add pool-backed durable lifecycle
r33drichardsd0e871fe3b32
diff --git a/.github/release-attribution-config.json b/.github/release-attribution-config.jsonindex 0c4578ab89..48d41292ff 100644--- a/.github/release-attribution-config.json+++ b/.github/release-attribution-config.json@@ -29,6 +29,7 @@"[email protected]": "ai-ag2026","[email protected]": "madhavajay","[email protected]": "enchanted-koala",+ "[email protected]": "r33drichards","[email protected]": "rsyuzyov","[email protected]": "sarinali","[email protected]": "injaneity",diff --git a/.github/scripts/tests/test_periodic_cua_sandbox_live.py b/.github/scripts/tests/test_periodic_cua_sandbox_live.pyindex 0952fe7e06..277b01c703 100644--- a/.github/scripts/tests/test_periodic_cua_sandbox_live.py+++ b/.github/scripts/tests/test_periodic_cua_sandbox_live.py@@ -2,16 +2,15 @@import jsonimport os-from pathlib import Pathimport shutilimport subprocessimport sysimport tempfileimport unittest+from pathlib import Pathimport yaml-REPO_ROOT = Path(__file__).resolve().parents[3]WORKFLOW = REPO_ROOT / ".github/workflows/periodic-cua-sandbox-live.yml"SANDBOX_ROOT = REPO_ROOT / "libs/python/cua-sandbox"@@ -218,7 +217,7 @@ class TestPeriodicCuaSandboxLive(unittest.TestCase):)self.assertEqual(checkout["with"]["ref"],- "${{ github.event_name == 'push' && github.sha || 'main' }}",+ "${{ github.event_name == 'push' && github.sha || github.ref }}",)self.assertEqual(steps["Set up Python"]["uses"],diff --git a/.github/workflows/periodic-cua-sandbox-live.yml b/.github/workflows/periodic-cua-sandbox-live.ymlindex e1b7254054..66cb68f9cd 100644--- a/.github/workflows/periodic-cua-sandbox-live.yml+++ b/.github/workflows/periodic-cua-sandbox-live.yml@@ -84,7 +84,7 @@ jobs:- name: Checkout mainuses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4with:- ref: ${{ github.event_name == 'push' && github.sha || 'main' }}+ ref: ${{ github.event_name == 'push' && github.sha || github.ref }}- name: Record checked out source SHAid: source_shadiff --git a/docs/superpowers/plans/2026-08-11-fleet-sandbox-lifecycle.md b/docs/superpowers/plans/2026-08-11-fleet-sandbox-lifecycle.mdnew file mode 100644index 0000000000..388a2f6628--- /dev/null+++ b/docs/superpowers/plans/2026-08-11-fleet-sandbox-lifecycle.md@@ -0,0 +1,87 @@+# Fleet Sandbox Lifecycle Implementation Plan++> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.++**Goal:** Route Fleet-backed `Sandbox.create()` and `Sandbox.ephemeral()` through reusable pools, with durable claim serialization and explicit disconnect/close semantics.++**Architecture:** `Pool.apply()` idempotently reconciles a content-addressed template and warm pool for supported registry-image configuration. `Pool.get()` resolves an existing pool without mutation, and `Pool.claim()` creates or reattaches a named claim and returns a connected `Sandbox`. `Sandbox` stores claim identity, reconnects from serialized state, renews its controller-enforced lifetime, and releases only the claim on close; pools remain reusable infrastructure.++**Tech Stack:** Python, pytest/pytest-asyncio, generated `cua-fleet` UniFFI bindings.++## Global Constraints++- `pool=` is read-only and mutually exclusive with `image`.+- Without `pool=`, `image` is required and creation performs `Pool.apply(image, replicas=1).claim(...)`.+- `name=` identifies the claim; `Sandbox.name` remains the bound sandbox name.+- Expose `claim_name` and `pool_name` separately.+- `disconnect()` closes transport/client resources only.+- `close()` idempotently releases the claim only; it does not delete a pool or template.+- `ephemeral()` calls `close()` on every exit path.+- Unsupported Fleet options raise `NotImplementedError`.+- Named claim retries reattach only when the existing claim belongs to the requested pool.+- Preserve contributor credit from commits `6f7c60404` and `0bd1b621f` when adapting their claim lifecycle work.++### Task 1: Add Private Claim State++**Files:**+- Modify: `libs/python/cua-sandbox/cua_sandbox/pool.py`+- Modify: `libs/python/cua-sandbox/cua_sandbox/transport/fleet.py`+- Test: `libs/python/cua-sandbox/tests/test_pool.py`++- [ ] Write failing tests for versioned JSON claim identity, bound identity, pool verification, client ownership, renewal, and 404-tolerant release.+- [ ] Run `uv run --project libs/python/cua-sandbox pytest libs/python/cua-sandbox/tests/test_pool.py -q` and verify the new tests fail.+- [ ] Adapt the submitted Lease implementation into private `_ClaimHandle`; do not export a public Lease noun.+- [ ] Add `owns_sdk` transport behavior so reattached Sandbox transports close their Fleet client on disconnect.+- [ ] Re-run the focused tests and verify they pass.++### Task 2: Add Pool Apply/Get/Claim++**Files:**+- Modify: `libs/python/cua-sandbox/cua_sandbox/pool.py`+- Modify: `libs/python/cua-sandbox/cua_sandbox/transport/fleet_cloud.py`+- Test: `libs/python/cua-sandbox/tests/test_pool.py`++- [ ] Write failing tests for deterministic `Pool.apply`, read-only `Pool.get`, claim naming, retry reattachment, wrong-pool conflict, service readiness, and unsupported image options.+- [ ] Run the pool tests and verify the new tests fail.+- [ ] Move Fleet template/pool request construction from `FleetCloudTransport` into `Pool.apply()` using generated builders.+- [ ] Hash image registry, CPU, memory, services, and replicas into a stable DNS-safe pool name when no explicit pool name is supplied.+- [ ] Implement `Pool.claim()` as a durable async operation returning `Sandbox`, not an async context manager.+- [ ] Re-run `test_pool.py` and `test_fleet_builder_usage.py`.++### Task 3: Route Sandbox Factories Through Pools++**Files:**+- Modify: `libs/python/cua-sandbox/cua_sandbox/sandbox.py`+- Create: `libs/python/cua-sandbox/tests/test_sandbox_fleet_lifecycle.py`++- [ ] Write failing tests for the existing-pool and image-apply dispatch branches.+- [ ] Test mutual exclusion, missing image, unsupported Fleet options, and preservation of local/legacy behavior.+- [ ] Extend `Sandbox.create()` with `pool`, `replicas`, `service`, `claim_spec`, and initial lifetime arguments.+- [ ] Refactor `Sandbox.ephemeral()` to call `Sandbox.create()` and terminate with `close()`.+- [ ] Run lifecycle, runtime, and VM-cleanup tests.++### Task 4: Add Reattach/Renew/Close++**Files:**+- Modify: `libs/python/cua-sandbox/cua_sandbox/sandbox.py`+- Modify: `libs/python/cua-sandbox/tests/test_sandbox_fleet_lifecycle.py`++- [ ] Write failing tests for `to_dict`, awaitable/context-managed `from_dict`, `keep_alive`, `disconnect`, and idempotent `close`.+- [ ] Ensure reattach resolves the live claim and verifies its pool instead of trusting cached service data.+- [ ] Compute renewal deadlines with timezone-aware UTC arithmetic.+- [ ] Raise `NotImplementedError` for lifecycle methods on unsupported providers.+- [ ] Run focused lifecycle and transport tests.++### Task 5: Align Sync API, Exports, And Docs++**Files:**+- Modify: `libs/python/cua-sandbox/cua_sandbox/sync/__init__.py`+- Modify: `libs/python/cua-sandbox/cua_sandbox/__init__.py`+- Modify: `libs/python/cua-sandbox/README.md`+- Test: `libs/python/cua-sandbox/tests/test_pool.py`++- [ ] Update sync Pool wrappers for durable `apply/get/claim` behavior.+- [ ] Keep generated request/builders public, but keep `_ClaimHandle` private.+- [ ] Document existing-pool, image-applied, ephemeral, serialization, and renewal examples.+- [ ] Document every Fleet `NotImplementedError` boundary.+- [ ] Run the full `libs/python/cua-sandbox/tests` suite.diff --git a/libs/python/cua-cli/cua_cli/commands/sandbox.py b/libs/python/cua-cli/cua_cli/commands/sandbox.pyindex 29d83d0ee4..e0228314c1 100644--- a/libs/python/cua-cli/cua_cli/commands/sandbox.py+++ b/libs/python/cua-cli/cua_cli/commands/sandbox.py@@ -470,7 +470,8 @@ def cmd_launch(args: argparse.Namespace) -> int:create_kwargs.update(await _cloud_auth_kwargs())sb = await Sandbox.create(image, **create_kwargs)- name = sb.name+ claim_name = getattr(sb, "claim_name", None)+ name = claim_name if isinstance(claim_name, str) and claim_name else sb.nameawait sb.disconnect()except Exception as e:import tracebackdiff --git a/libs/python/cua-cli/tests/commands/test_sandbox.py b/libs/python/cua-cli/tests/commands/test_sandbox.pyindex 0d7a8e58d2..9da55f3a50 100644--- a/libs/python/cua-cli/tests/commands/test_sandbox.py+++ b/libs/python/cua-cli/tests/commands/test_sandbox.py@@ -295,7 +295,8 @@ class TestCmdLaunch:)image = object()created = MagicMock(name="created")- created.name = "fleet-sandbox"+ created.name = "bound-sandbox-resource"+ created.claim_name = "fleet-sandbox"created.disconnect = AsyncMock()mock_create = AsyncMock(return_value=created)mock_sdk = MagicMock()@@ -306,13 +307,14 @@ class TestCmdLaunch:with patch.object(sandbox, "get_access_token", new_callable=AsyncMock) as mock_token:- with patch.object(sandbox, "print_success"):+ with patch.object(sandbox, "print_success") as mock_success:result = sandbox.cmd_launch(args)assert result == 0mock_token.assert_not_awaited()mock_create.assert_awaited_once_with(image, name="fleet-sandbox")created.disconnect.assert_awaited_once_with()+ mock_success.assert_called_once_with("Sandbox 'fleet-sandbox' is ready")class TestCmdInfo:diff --git a/libs/python/cua-sandbox/README.md b/libs/python/cua-sandbox/README.mdindex a7dcaf6c92..455a6a74d8 100644--- a/libs/python/cua-sandbox/README.md+++ b/libs/python/cua-sandbox/README.md@@ -20,7 +20,9 @@ Created on enter, destroyed on exit.```pythonfrom cua_sandbox import Sandbox, Image-async with Sandbox.ephemeral(Image.linux()) as sb:+async with Sandbox.ephemeral(+ Image.from_registry("registry.example/desktop-workspace@sha256:...")+) as sb:await sb.shell.run("uname -a")await sb.screenshot()```@@ -32,9 +34,11 @@ Provision a new sandbox that stays alive after your script exits.```pythonfrom cua_sandbox import Sandbox, Image-sb = await Sandbox.create(Image.linux())+sb = await Sandbox.create(+ Image.from_registry("registry.example/desktop-workspace@sha256:...")+)await sb.shell.run("uname -a")-print(sb.name) # save this to reconnect later+print(sb.claim_name) # Fleet lifecycle identifier; save this to reconnect laterawait sb.disconnect()```@@ -92,101 +96,80 @@ 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 templates and pools+## Fleet pools and durable claims-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.+For production workloads, claim from an existing pool. Supplying `pool=` never changes its configuration; `name=` names the claim, while `sb.name` is the separately bound sandbox resource.```python-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,- ),- ),- )-)+from cua_sandbox import Sandbox-pool = await Pool.reconcile(- CreatePoolRequest(- namespace="foo",- spec=OsGymSandboxWarmPoolSpec(- replicas=1,- sandbox_template_ref=SandboxTemplateRef(name="workspace"),- autoscaling=None,- ),- )+sb = await Sandbox.create(+ pool="workspace",+ name="workflow-123",+ service="mcp",+ keep_alive_minutes=30,)-async with pool.claim() as sb:- result = await sb.shell.run("echo hello")+reference = sb.to_dict()+await sb.disconnect() # claim remains held- # Requests use the same authenticated Fleet claim.- response = await sb.services.request(- "mcp", method="POST", path="/mcp", json={"jsonrpc": "2.0", "method": "tools/list", "id": 1}- )- response.raise_for_status()+# A later process or Temporal activity re-resolves the live claim.+sb = await Sandbox.from_dict(reference)+await sb.keep_alive(minutes=30)+await sb.close() # idempotently releases the claim```-For scripts that use the synchronous facade:+If `pool=` is omitted, a registry image is required. `Sandbox.create(image)` applies a deterministic reusable pool and claims from it. `Sandbox.ephemeral(image)` instead creates an isolated temporary pool and deletes it after releasing the claim, preserving teardown-by-default semantics.```python-from cua_sandbox.sync import Pool, Template+from cua_sandbox import Image, Sandbox++image = Image.from_registry("registry.example/desktop-workspace@sha256:...")-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")+async with Sandbox.ephemeral(+ image,+ name="job-123",+ cpu=4,+ memory_mb=4096,+ server_port=5000,+) as sb:+ await sb.shell.run("uname -a")```+To deliberately retain deterministic warm capacity for later calls, opt in with `keep_pool=True`:+```python-import os+async with Sandbox.ephemeral(image, keep_pool=True) as sb:+ await sb.shell.run("uname -a")+```-import cua_sandbox as cua-from cua_sandbox import Image, Sandbox+The equivalent lower-level reusable-pool API is:-cua.configure(- client_id=os.environ["CUA_CLIENT_ID"],- client_secret=os.environ["CUA_CLIENT_SECRET"],+```python+from cua_sandbox import Image, Pool++pool = await Pool.apply(+ Image.from_registry("registry.example/desktop-workspace@sha256:..."),+ replicas=1,+ cpu=4,+ memory_mb=4096,+ services={"server": 8000, "mcp": 3000},)-async with Sandbox.ephemeral(- Image.from_registry("registry.example/linux-computer-server:latest"),- server_port=5000,-) as sb:- await sb.shell.run("uname -a")+sb = await pool.claim(name="job-123", service="mcp")+await sb.close()```+`Pool.claim()` is both awaitable and an async context manager, so existing scoped usage remains valid:++```python+async with pool.claim(name="job-123") as sb:+ await sb.shell.run("echo hello")+```++`Pool.reconcile(CreatePoolRequest(...))` and `Template.reconcile(CreateTemplateRequest(...))` remain available for advanced generated-schema configuration. The public generated builders should be used instead of constructing builder-enabled Fleet records directly.+The image must run the CUA computer-server `/cmd` API on the configured `server_port`.Windows computer-server images continue to use the default port `8000`.++Fleet currently supports registry images, CPU, memory, replica count, and named TCP services. Local image builds, layers, injected files or environment, snapshots, custom disks, unsupported regions, and provider-crossing serialization raise `NotImplementedError`.diff --git a/libs/python/cua-sandbox/cua_sandbox/pool.py b/libs/python/cua-sandbox/cua_sandbox/pool.pyindex 08ad1cb070..757f8c5b22 100644--- a/libs/python/cua-sandbox/cua_sandbox/pool.py+++ b/libs/python/cua-sandbox/cua_sandbox/pool.py@@ -2,58 +2,71 @@from __future__ import annotations+import hashlib+import jsonimport logging-from collections.abc import AsyncIterator-from contextlib import asynccontextmanager-from typing import Any, cast+from typing import Any, Callable, Coroutine, Generic, TypeVar, cast+from cua_sandbox.image import Imagefrom cua_sandbox.sandbox import Sandboxfrom cua_sandbox.transport.fleet import FleetTransport-from cua_sandbox.transport.fleet_cloud import _FleetClient+from cua_sandbox.transport.fleet_cloud import FleetCloudTransport, _FleetClientfrom fleet_sdk import (+ Claim,ClaimSpec,CreateClaimRequest,CreatePoolRequest,CreateTemplateRequest,+ ResourceMetadata,+ SandboxTemplateRefBuilder,+ SdkError,)+_T = TypeVar("_T")logger = logging.getLogger(__name__)-class Template:- """A reconciled Fleet sandbox template.+class _ClaimResult(Generic[_T]):+ """Awaitable claim acquisition that also supports scoped cleanup."""++ def __init__(self, factory: Callable[[], Coroutine[Any, Any, _T]]) -> None:+ self._factory = factory+ self._instance: Any = None- 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.+ def __await__(self) -> Any:+ return self._factory().__await__()- Template instances retain only Fleet resource metadata; each call opens- and closes its own Fleet client.- """+ async def __aenter__(self) -> _T:+ self._instance = await self._factory()+ return self._instance++ async def __aexit__(self, exc_type: Any, exc: Any, traceback: Any) -> None:+ if self._instance is None:+ return+ try:+ await self._instance.close()+ except BaseException:+ if exc_type is None:+ raise+ logger.exception("Failed to release Fleet claim after an earlier error")+++class Template:+ """A reconciled Fleet sandbox template."""def __init__(self, resource: Any) -> None:self._resource = resource@propertydef name(self) -> str:- """The template name."""return cast(str, self._resource.metadata.name)@propertydef resource(self) -> Any:- """The underlying Fleet SDK template resource."""return self._resource@classmethodasync 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()@@ -63,42 +76,139 @@ class Template:await client.close()-class Pool:- """A reconciled Fleet pool that can lease cloud sandboxes.+def _claim_stub(namespace: str, name: str) -> Claim:+ return Claim(+ api_version="osgym.cua.ai/v1alpha1",+ kind="OSGymSandboxClaim",+ metadata=ResourceMetadata(+ namespace=namespace,+ name=name,+ labels=None,+ creation_timestamp=None,+ ),+ spec=ClaimSpec(+ sandbox_template_ref=SandboxTemplateRefBuilder().name("").build(),+ warmpool=None,+ bind_deadline=None,+ lifecycle=None,+ ),+ status=None,+ )- ``reconcile`` creates a pool when it is absent and updates its desired- 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- reused for sequential claims without the caller managing client lifetime.- """+class _ClaimHandle:+ """Serializable identity for a held Fleet claim."""- def __init__(self, resource: Any) -> None:+ def __init__(+ self,+ *,+ namespace: str,+ name: str,+ pool_name: str | None = None,+ service: str = "server",+ client: Any = None,+ ) -> None:+ self.namespace = namespace+ self.name = name+ self.pool_name = pool_name or namespace+ self.service = service+ self._client = client++ def to_dict(self) -> dict[str, Any]:+ return {+ "version": 1,+ "provider": "fleet",+ "namespace": self.namespace,+ "pool": self.pool_name,+ "claim": self.name,+ "service": self.service,+ }++ @classmethod+ def from_dict(cls, data: dict[str, Any]) -> "_ClaimHandle":+ if data.get("provider") != "fleet" or data.get("version") != 1:+ raise ValueError("unsupported sandbox reference")+ return cls(+ namespace=data["namespace"],+ pool_name=data["pool"],+ name=data["claim"],+ service=data.get("service", "server"),+ )++ def _operation_client(self) -> tuple[Any, bool]:+ client = self._client+ closed = bool(+ client is not None+ and (getattr(client, "_closed", False) or getattr(client, "closed", False))+ )+ if client is None or closed:+ return _FleetClient(), True+ return client, False++ async def wait(+ self, *, service: str | None = None, time_to_start: float | None = None+ ) -> Sandbox:+ service = service or self.service+ self.service = service+ client, owns_client = self._operation_client()+ self._client = client+ try:+ bound = await client.wait_claim(_claim_stub(self.namespace, self.name))+ if bound.namespace != self.namespace or bound.claim != self.name:+ raise RuntimeError("Fleet returned a sandbox bound to a different claim")+ await client.wait_service_ready(bound, service, time_to_start)+ sandbox = Sandbox(+ FleetTransport(sdk=client, bound=bound, service_name=service, owns_sdk=True),+ name=bound.name,+ )+ sandbox._claim_handle = self+ await sandbox._connect()+ return sandbox+ except BaseException:+ if owns_client:+ if self._client is client:+ self._client = None+ await client.close()+ raise++ async def renew(self, shutdown_time: str) -> None:+ client, owns_client = self._operation_client()+ try:+ await client.renew_claim(_claim_stub(self.namespace, self.name), shutdown_time)+ finally:+ if owns_client:+ await client.close()++ async def release(self) -> None:+ client, owns_client = self._operation_client()+ try:+ try:+ await client.delete_claim(_claim_stub(self.namespace, self.name))+ except SdkError.Status as error:+ if error.status != 404:+ raise+ finally:+ if owns_client:+ await client.close()+++class Pool:+ """A Fleet warm pool that can provide durable Sandbox claims."""++ def __init__(self, resource: Any, *, owned_template: Any = None) -> None:self._resource = resource+ self._owned_template = owned_template@propertydef name(self) -> str:- """The pool name."""return cast(str, self._resource.metadata.name)@propertydef resource(self) -> Any:- """The underlying Fleet SDK pool resource."""return self._resource@classmethodasync def reconcile(cls, request: CreatePoolRequest) -> "Pool":- """Create or update a Fleet pool from a native Fleet request.-- The request is passed unchanged to the generated Fleet client. Import- ``CreatePoolRequest`` and its nested schema types from ``cua_sandbox``- so callers do not depend on the generated binding package directly.- """if not isinstance(request, CreatePoolRequest):raise TypeError("Pool.reconcile requires a CreatePoolRequest")client = _FleetClient()@@ -107,55 +217,130 @@ class Pool:finally:await client.close()- @asynccontextmanager- async def claim(self, *, spec: ClaimSpec | None = None) -> AsyncIterator[Sandbox]:- """Lease a sandbox and release its Fleet claim when the block exits.+ @classmethod+ async def get(cls, name: str) -> "Pool":+ client = _FleetClient()+ try:+ return cls(await client.get_pool(name))+ finally:+ await client.close()- A claim is released after both normal and exceptional block exits. If- release fails while the block is already raising, the original block- exception is preserved and the release failure is logged. Otherwise,- the release failure is raised to the caller.- """+ @classmethod+ async def apply(+ cls,+ image: Image,+ *,+ name: str | None = None,+ replicas: int = 1,+ cpu: int | None = None,+ memory_mb: int | None = None,+ services: dict[str, int] | None = None,+ ) -> "Pool":+ FleetCloudTransport._validate_image(image)+ effective_services = services or {+ "server": 8000,+ **{f"port-{port}": port for port in image._ports if port != 8000},+ }+ if name is None:+ identity = json.dumps(+ {+ "image": image._registry,+ "replicas": replicas,+ "cpu": cpu,+ "memory_mb": memory_mb,+ "services": sorted(effective_services.items()),+ },+ separators=(",", ":"),+ sort_keys=True,+ )+ name = f"cua-{hashlib.sha256(identity.encode()).hexdigest()[:12]}"+ transport = FleetCloudTransport(+ image=image,+ name=name,+ replicas=replicas,+ cpu=cpu,+ memory_mb=memory_mb,+ services=effective_services,+ )+ pool = await cls.reconcile(transport._pool_request())+ try:+ template = await Template.reconcile(transport._template_request())+ except BaseException:+ await pool.delete()+ raise+ pool._owned_template = template.resource+ return pool++ async def delete(self) -> None:+ """Delete this Fleet pool."""client = _FleetClient()- claim: Any = None- sandbox: Sandbox | None = None- primary_error: BaseException | None = None- cleanup_error: Exception | None = None+ try:+ await client.delete_pool(self._resource)+ if self._owned_template is not None:+ await client.delete_template(self._owned_template)+ self._owned_template = None+ finally:+ await client.close()+ async def create_claim(+ self, *, spec: ClaimSpec | None = None, name: str | None = None+ ) -> _ClaimHandle:+ request = CreateClaimRequest(pool=self._resource, spec=spec, name=name)+ client = _FleetClient()try:- claim = await client.create_claim(CreateClaimRequest(pool=self._resource, spec=spec))- bound = await client.wait_claim(claim)- sandbox = Sandbox(- FleetTransport(sdk=client, bound=bound, service_name="server"), name=bound.name+ claim = await client.create_claim(request)+ return _ClaimHandle(+ namespace=claim.metadata.namespace,+ name=claim.metadata.name,+ pool_name=self.name,)- await sandbox._connect()- yield sandbox- except BaseException as error:- primary_error = error- raisefinally:- if sandbox is not None:- try:- await sandbox.disconnect()- except Exception:- logger.exception("Failed to disconnect claimed sandbox %r", sandbox.name)-- if claim is not None:- try:- await client.delete_claim(claim)- except Exception as error:- if primary_error is not None:- logger.exception("Failed to release Fleet claim after an earlier error")- else:- cleanup_error = error+ await client.close()+ def claim(+ self,+ *,+ spec: ClaimSpec | None = None,+ name: str | None = None,+ service: str = "server",+ time_to_start: float | None = None,+ ) -> _ClaimResult[Sandbox]:+ async def acquire() -> Sandbox:+ client = _FleetClient()+ claim: Any = None+ created_claim = Falsetry:+ if name is not None:+ claim = next(+ (+ existing+ for existing in await client.list_claims(+ self._resource.metadata.namespace+ )+ if existing.metadata.name == name+ ),+ None,+ )+ if claim is None:+ claim = await client.create_claim(+ CreateClaimRequest(pool=self._resource, spec=spec, name=name)+ )+ created_claim = True+ handle = _ClaimHandle(+ namespace=claim.metadata.namespace,+ name=claim.metadata.name,+ pool_name=self.name,+ service=service,+ client=client,+ )+ return await handle.wait(service=service, time_to_start=time_to_start)+ except BaseException:+ if created_claim and claim is not None:+ try:+ await client.delete_claim(claim)+ except Exception:+ logger.exception("Failed to release Fleet claim after acquisition failure")await client.close()- except Exception:- if primary_error is not None or cleanup_error is not None:- logger.exception("Failed to close Fleet client")- else:- raise+ raise- if cleanup_error is not None:- raise cleanup_error+ return _ClaimResult(acquire)diff --git a/libs/python/cua-sandbox/cua_sandbox/sandbox.py b/libs/python/cua-sandbox/cua_sandbox/sandbox.pyindex e4a3db5524..5f7569c2a1 100644--- a/libs/python/cua-sandbox/cua_sandbox/sandbox.py+++ b/libs/python/cua-sandbox/cua_sandbox/sandbox.py@@ -33,6 +33,7 @@ import timefrom collections.abc import Mappingfrom contextlib import asynccontextmanagerfrom dataclasses import dataclass+from datetime import datetime, timedelta, timezonefrom typing import (TYPE_CHECKING,Any,@@ -80,6 +81,7 @@ from cua_sandbox.transport.http import HTTPTransportfrom cua_sandbox.transport.websocket import WebSocketTransportif TYPE_CHECKING:+ from cua_sandbox.pool import Poolfrom cua_sandbox.runtime.base import Runtime, RuntimeInfologger = logging.getLogger(__name__)@@ -87,6 +89,62 @@ logger = logging.getLogger(__name__)_T = TypeVar("_T")+async def _keep_alive_or_close(sandbox: Any, minutes: float | None) -> None:+ if minutes is None:+ return+ try:+ await sandbox.keep_alive(minutes=minutes)+ except BaseException as keep_alive_error:+ try:+ await sandbox.close()+ except BaseException as close_error:+ logger.warning("Failed to close Fleet claim after keep-alive failure: %s", close_error)+ raise keep_alive_error from close_error+ raise+++async def _save_fleet_claim_or_close(+ sandbox: Any,+ claim_name: str,+ pool_name: str,+) -> None:+ from cua_sandbox import sandbox_state++ try:+ sandbox_state.save_fleet_claim(claim_name, pool_name)+ except BaseException as state_error:+ try:+ await sandbox.close()+ except BaseException as close_error:+ raise state_error from close_error+ raise+++async def _cleanup_ephemeral_fleet(+ sandbox: Any | None,+ pool: Any | None,+ *,+ suppress_errors: bool,+) -> None:+ cleanup_error: BaseException | None = None+ cleanup_operations = (+ ("claim", sandbox.close if sandbox is not None else None),+ ("pool", pool.delete if pool is not None else None),+ )+ for resource, cleanup in cleanup_operations:+ if cleanup is None:+ continue+ try:+ await cleanup()+ except BaseException as error:+ if suppress_errors or cleanup_error is not None:+ logger.warning("Failed to clean up ephemeral Fleet %s: %s", resource, error)+ else:+ cleanup_error = error+ if cleanup_error is not None:+ raise cleanup_error++@dataclassclass SandboxInfo:"""Metadata for a local or cloud sandbox."""@@ -259,6 +317,8 @@ class Sandbox:self._runtime_info = _runtime_infoself._ephemeral = _ephemeralself._has_snapshots = False+ self._claim_handle: Any = None+ self._claim_released = Falseself.telemetry_enabled = _telemetry_enabledself.screen = Screen(transport)self.mouse = Mouse(transport)@@ -284,6 +344,65 @@ class Sandbox:"""Drop the transport connection. The sandbox keeps running."""await self._transport.disconnect()+ @property+ def claim_name(self) -> str | None:+ """Fleet claim name, distinct from the bound sandbox name."""+ return self._claim_handle.name if self._claim_handle is not None else None++ @property+ def pool_name(self) -> str | None:+ """Fleet pool that owns this claim."""+ return self._claim_handle.pool_name if self._claim_handle is not None else None++ def to_dict(self) -> dict[str, Any]:+ """Serialize a durable Fleet sandbox reference."""+ if self._claim_handle is None:+ raise NotImplementedError("serialization is only supported for Fleet claims")+ return self._claim_handle.to_dict()++ @classmethod+ def from_dict(cls, data: dict[str, Any]) -> "_ConnectResult":+ """Reconnect to a serialized Fleet claim reference."""++ async def factory() -> "Sandbox":+ from cua_sandbox.pool import _ClaimHandle++ handle = _ClaimHandle.from_dict(data)+ if handle.namespace != handle.pool_name:+ raise ValueError("serialized claim does not belong to the requested pool")+ return await handle.wait()++ return _ConnectResult(factory)++ async def keep_alive(self, *, minutes: float) -> None:+ """Push a Fleet claim's controller-enforced shutdown time forward."""+ if self._claim_handle is None:+ raise NotImplementedError("keep_alive is only supported for Fleet claims")+ if minutes <= 0:+ raise ValueError("minutes must be positive")+ shutdown_time = (datetime.now(timezone.utc) + timedelta(minutes=minutes)).isoformat()+ await self._claim_handle.renew(shutdown_time.replace("+00:00", "Z"))++ async def close(self) -> None:+ """Release this Fleet claim; repeated calls are safe."""+ if self._claim_released:+ return+ if self._claim_handle is None:+ raise NotImplementedError("close is only supported for Fleet claims")+ claim_name = self.claim_name+ try:+ await self._claim_handle.release()+ self._claim_released = True+ if claim_name is not None:+ from cua_sandbox import sandbox_state++ try:+ sandbox_state.delete(claim_name)+ except OSError as error:+ logger.warning("Failed to remove Fleet claim state %r: %s", claim_name, error)+ finally:+ await self.disconnect()+async def snapshot(self, name: str | None = None, stateful: bool = False) -> "Image":"""Snapshot this sandbox's current state. Returns an Image.@@ -402,10 +521,14 @@ class Sandbox:@classmethodasync def create(cls,- image: Optional[Image] = None,+ image: Image | None = None,*,+ pool: "Pool | str | None" = None,name: Optional[str] = None,- pool: Optional[str] = None,+ replicas: int = 1,+ service: str = "server",+ claim_spec: Any = None,+ keep_alive_minutes: float | None = None,api_key: Optional[str] = None,local: bool = False,runtime: Optional["Runtime"] = None,@@ -418,46 +541,102 @@ class Sandbox:server_port: int = 8000,telemetry_enabled: bool = True,) -> "Sandbox":- """Provision a new persistent sandbox and return it connected.-- The sandbox is kept alive after your script exits — call ``close()``- when you are done, or use :meth:`ephemeral` if you want it destroyed- automatically.+ """Provision or claim a persistent sandbox and return it connected.- Args:- image: Image to run (e.g. ``Image.desktop("ubuntu")``).- name: Optional name to assign to the sandbox. Required with ``pool``.- pool: Pre-created Fleet pool to claim instead of creating from an image.- api_key: Legacy CUA API key. Providing one uses the legacy VM API;- Fleet cloud sandboxes use OAuth client credentials instead.- local: Use a local runtime instead of cloud.- runtime: Explicit runtime backend (DockerRuntime, QEMURuntime, etc.).- cpu: Number of CPUs for the cloud sandbox.- memory_mb: Memory in MB for the cloud sandbox.- disk_gb: Unsupported by Fleet; API-key legacy cloud only.- region: Fleet currently supports only ``"us-east-1"``.- time_to_start: Max seconds to wait for Fleet provisioning and- service readiness (default 600).- request_timeout: Default HTTP request timeout in seconds for- commands sent to the computer-server (default 30, cloud only).- Individual commands with a server-side timeout automatically- extend the client timeout to match.- server_port: Guest computer-server TCP port for Fleet cloud sandboxes.- Defaults to 8000. Set this when the guest image runs the CUA- computer-server ``/cmd`` API on a non-default port, for example- 5000.- telemetry_enabled: Set to False to disable telemetry for this instance.-- Example::-- sb = await Sandbox.create(Image.desktop("ubuntu"))- await sb.shell.run("uname -a")- print(sb.name) # save to reconnect later- await sb.disconnect()+ Supplying ``pool`` claims from an existing Fleet pool without changing+ its configuration. Otherwise, registry images are applied as a+ deterministic reusable pool before a claim is acquired."""- if (image is None) == (pool is None):- raise ValueError("Specify exactly one of image or pool")+ from cua_sandbox.pool import Pool+ if (+ isinstance(server_port, bool)+ or not isinstance(server_port, int)+ or server_port < 1+ or server_port > 65535+ ):+ raise ValueError("server_port must be an integer between 1 and 65535")++ if pool is not None:+ if image is not None:+ raise ValueError("image and pool are mutually exclusive")+ if replicas != 1 or cpu is not None or memory_mb is not None or disk_gb is not None:+ raise ValueError("configuration cannot be supplied for an existing pool")+ if (+ local+ or runtime is not None+ or api_key is not None+ or region != "us-east-1"+ or request_timeout is not None+ or server_port != 8000+ ):+ raise NotImplementedError("the requested option is not supported with Fleet pools")+ resolved_pool = await Pool.get(pool) if isinstance(pool, str) else pool+ sandbox = await resolved_pool.claim(+ name=name, spec=claim_spec, service=service, time_to_start=time_to_start+ )+ sandbox_claim_name = getattr(sandbox, "claim_name", None)+ sandbox_pool_name = getattr(sandbox, "pool_name", None)+ claim_name = (+ sandbox_claim_name+ if isinstance(sandbox_claim_name, str) and sandbox_claim_name+ else name+ )+ pool_name = (+ sandbox_pool_name+ if isinstance(sandbox_pool_name, str) and sandbox_pool_name+ else resolved_pool.name+ )+ await _keep_alive_or_close(sandbox, keep_alive_minutes)+ if claim_name is not None:+ await _save_fleet_claim_or_close(sandbox, claim_name, pool_name)+ return sandbox++ fleet_image = (+ image is not None+ and image._registry is not None+ and cls._uses_fleet(api_key)+ and not local+ and runtime is None+ )+ if fleet_image:+ if disk_gb is not None or region != "us-east-1" or request_timeout is not None:+ raise NotImplementedError("the requested option is not supported by Fleet")+ services = {+ "server": server_port,+ **{f"port-{port}": port for port in image._ports if port != server_port},+ }+ resolved_pool = await Pool.apply(+ image,+ replicas=replicas,+ cpu=cpu,+ memory_mb=memory_mb,+ services=services,+ )+ sandbox = await resolved_pool.claim(+ name=name, spec=claim_spec, service=service, time_to_start=time_to_start+ )+ sandbox_claim_name = getattr(sandbox, "claim_name", None)+ sandbox_pool_name = getattr(sandbox, "pool_name", None)+ claim_name = (+ sandbox_claim_name+ if isinstance(sandbox_claim_name, str) and sandbox_claim_name+ else name+ )+ pool_name = (+ sandbox_pool_name+ if isinstance(sandbox_pool_name, str) and sandbox_pool_name+ else resolved_pool.name+ )+ await _keep_alive_or_close(sandbox, keep_alive_minutes)+ if claim_name is not None:+ await _save_fleet_claim_or_close(sandbox, claim_name, pool_name)+ return sandbox++ if image is None:+ raise ValueError("image is required when pool is omitted")+ if replicas != 1 or service != "server" or claim_spec is not None:+ raise NotImplementedError("claim options are only supported by Fleet")return await cls._create(image=image,name=name,@@ -539,9 +718,15 @@ class Sandbox:@asynccontextmanagerasync def ephemeral(cls,- image: Image,+ image: Image | None = None,*,+ pool: "Pool | str | None" = None,name: Optional[str] = None,+ replicas: int = 1,+ service: str = "server",+ claim_spec: Any = None,+ keep_alive_minutes: float | None = None,+ keep_pool: bool = False,api_key: Optional[str] = None,local: bool = False,runtime: Optional["Runtime"] = None,@@ -554,37 +739,108 @@ class Sandbox:server_port: int = 8000,telemetry_enabled: bool = True,) -> AsyncIterator["Sandbox"]:- """Create an ephemeral sandbox that is automatically destroyed on exit.+ from cua_sandbox.pool import Pool++ fleet_image = (+ image is not None+ and image._registry is not None+ and cls._uses_fleet(api_key)+ and not local+ and runtime is None+ )+ if keep_pool and not fleet_image:+ raise ValueError("keep_pool is only supported for Fleet registry images")- Args:- image: Image to run (e.g. ``Image.desktop("ubuntu")``).- name: Optional name to assign to the sandbox.- api_key: Legacy CUA API key. Providing one uses the legacy VM API;- Fleet cloud sandboxes use OAuth client credentials instead.- local: Use a local runtime instead of cloud.- runtime: Explicit runtime backend (DockerRuntime, QEMURuntime, etc.).- cpu: Number of CPUs for the cloud sandbox.- memory_mb: Memory in MB for the cloud sandbox.- disk_gb: Unsupported by Fleet; API-key legacy cloud only.- region: Fleet currently supports only ``"us-east-1"``.- time_to_start: Max seconds to wait for Fleet provisioning and- service readiness (default 600).- request_timeout: Default HTTP request timeout in seconds for- commands sent to the computer-server (default 30, cloud only).- Individual commands with a server-side timeout automatically- extend the client timeout to match.- server_port: Guest computer-server TCP port for Fleet cloud sandboxes.- Defaults to 8000. Set this when the guest image runs the CUA- computer-server ``/cmd`` API on a non-default port, for example- 5000.-- Example::-- async with Sandbox.ephemeral(Image.desktop("ubuntu")) as sb:- await sb.shell.run("whoami")- # sandbox is destroyed here- """- sb = await cls._create(+ if pool is not None:+ sandbox = await cls.create(+ image,+ pool=pool,+ name=name,+ replicas=replicas,+ service=service,+ claim_spec=claim_spec,+ keep_alive_minutes=keep_alive_minutes,+ api_key=api_key,+ local=local,+ runtime=runtime,+ cpu=cpu,+ memory_mb=memory_mb,+ disk_gb=disk_gb,+ region=region,+ time_to_start=time_to_start,+ request_timeout=request_timeout,+ server_port=server_port,+ telemetry_enabled=telemetry_enabled,+ )+ try:+ yield sandbox+ except BaseException:+ await _cleanup_ephemeral_fleet(sandbox, None, suppress_errors=True)+ raise+ else:+ await _cleanup_ephemeral_fleet(sandbox, None, suppress_errors=False)+ return++ if fleet_image:+ if disk_gb is not None or region != "us-east-1" or request_timeout is not None:+ raise NotImplementedError("the requested option is not supported by Fleet")+ if (+ isinstance(server_port, bool)+ or not isinstance(server_port, int)+ or server_port < 1+ or server_port > 65535+ ):+ raise ValueError("server_port must be an integer between 1 and 65535")+ services = {+ "server": server_port,+ **{f"port-{port}": port for port in image._ports if port != server_port},+ }+ pool_options = {"name": name} if name is not None else {}+ owned_pool = await Pool.apply(+ image,+ replicas=replicas,+ cpu=cpu,+ memory_mb=memory_mb,+ services=services,+ **pool_options,+ )+ sandbox = None+ try:+ sandbox = await owned_pool.claim(+ name=name,+ spec=claim_spec,+ service=service,+ time_to_start=time_to_start,+ )+ await _keep_alive_or_close(sandbox, keep_alive_minutes)+ except BaseException:+ await _cleanup_ephemeral_fleet(+ None,+ None if keep_pool else owned_pool,+ suppress_errors=True,+ )+ raise++ try:+ yield sandbox+ except BaseException:+ await _cleanup_ephemeral_fleet(+ sandbox,+ None if keep_pool else owned_pool,+ suppress_errors=True,+ )+ raise+ else:+ await _cleanup_ephemeral_fleet(+ sandbox,+ None if keep_pool else owned_pool,+ suppress_errors=False,+ )+ return++ if image is None:+ raise ValueError("image is required when pool is omitted")+ sandbox = await cls._create(image=image,name=name,ephemeral=True,@@ -601,13 +857,12 @@ class Sandbox:telemetry_enabled=telemetry_enabled,)try:- yield sb+ yield sandboxfinally:- if sb._has_snapshots and sb.name:- # Stop instead of delete so forks can reference the snapshots.- await cls.suspend(sb.name, local=local, api_key=api_key)+ if sandbox._has_snapshots and sandbox.name:+ await cls.suspend(sandbox.name, local=local, api_key=api_key)else:- await sb.destroy()+ await sandbox.destroy()# ── Lifecycle management ─────────────────────────────────────────────diff --git a/libs/python/cua-sandbox/cua_sandbox/sync/__init__.py b/libs/python/cua-sandbox/cua_sandbox/sync/__init__.pyindex fcb8be7eee..31b1899e63 100644--- a/libs/python/cua-sandbox/cua_sandbox/sync/__init__.py+++ b/libs/python/cua-sandbox/cua_sandbox/sync/__init__.py@@ -111,10 +111,53 @@ class Pool:"""Synchronously create or update a Fleet pool."""return cls(_run(_AsyncPool.reconcile(request)))+ @classmethod+ def get(cls, name: str) -> "Pool":+ """Synchronously fetch an existing Fleet pool without changing it."""+ return cls(_run(_AsyncPool.get(name)))++ @classmethod+ def apply(+ cls,+ image: Image,+ *,+ name: str | None = None,+ replicas: int = 1,+ cpu: int | None = None,+ memory_mb: int | None = None,+ services: dict[str, int] | None = None,+ ) -> "Pool":+ """Synchronously apply an image-backed Fleet pool."""+ return cls(+ _run(+ _AsyncPool.apply(+ image,+ name=name,+ replicas=replicas,+ cpu=cpu,+ memory_mb=memory_mb,+ services=services,+ )+ )+ )++ def delete(self) -> None:+ """Synchronously delete this Fleet pool."""+ _run(self._async_pool.delete())+@contextmanager- def claim(self, *, spec: ClaimSpec | None = None) -> Iterator[_SyncProxy]:- """Synchronously lease a sandbox and release the claim on exit."""- context = self._async_pool.claim(spec=spec)+ def claim(+ self,+ *,+ spec: ClaimSpec | None = None,+ name: str | None = None,+ service: str = "server",+ time_to_start: float | None = None,+ ) -> Iterator[_SyncProxy]:+ """Synchronously claim a sandbox and release it on exit."""+ context = self._async_pool.claim(+ spec=spec, name=name, service=service, time_to_start=time_to_start+ )sandbox = _run(context.__aenter__())try:yield _SyncProxy(sandbox)diff --git a/libs/python/cua-sandbox/cua_sandbox/transport/fleet.py b/libs/python/cua-sandbox/cua_sandbox/transport/fleet.pyindex c8b9a39ccb..42254333d6 100644--- a/libs/python/cua-sandbox/cua_sandbox/transport/fleet.py+++ b/libs/python/cua-sandbox/cua_sandbox/transport/fleet.py@@ -29,13 +29,16 @@ class FleetTransport(Transport):bound: Any,service_name: str = "api",timeout: float = 30.0,+ owns_sdk: bool = False,**_: Any,) -> None:self._sdk = sdkself._bound = boundself._service_name = service_nameself._timeout = timeout+ self._owns_sdk = owns_sdkself._connected = False+ self._sdk_closed = Falseasync def connect(self) -> None:if self._service_name not in self._bound.services:@@ -44,6 +47,12 @@ class FleetTransport(Transport):async def disconnect(self) -> None:self._connected = False+ # A transport constructed with owns_sdk=True (e.g. by Lease.wait) is the+ # sole holder of its Fleet client, so disconnect is where that client's+ # HTTP resources are returned.+ if self._owns_sdk and not self._sdk_closed:+ await self._sdk.close()+ self._sdk_closed = Trueasync def request_service(self,diff --git a/libs/python/cua-sandbox/cua_sandbox/transport/fleet_cloud.py b/libs/python/cua-sandbox/cua_sandbox/transport/fleet_cloud.pyindex d136597967..fb73034a95 100644--- a/libs/python/cua-sandbox/cua_sandbox/transport/fleet_cloud.py+++ b/libs/python/cua-sandbox/cua_sandbox/transport/fleet_cloud.py@@ -154,6 +154,7 @@ class _FleetClient:"""Thin async facade over the generated Cyclops SDK."""def __init__(self) -> None:+ self._closed = Falsefleet_token = get_fleet_token()if not fleet_token:client_id = get_client_id()@@ -196,7 +197,10 @@ class _FleetClient:self._client = CyclopsClient.connect(configuration, self._http_client)async def close(self) -> None:+ if self._closed:+ returnawait self._http_client.aclose()+ self._closed = Trueasync def create_pool(self, request: CreatePoolRequest) -> Any:return await self._client.create_pool(request)@@ -247,6 +251,15 @@ class _FleetClient:async def wait_claim(self, claim: Any) -> Any:return await self._client.wait_claim(claim)+ async def renew_claim(self, claim: Any, shutdown_time: str) -> Any:+ renew = getattr(self._client, "renew_claim", None)+ if renew is None:+ raise RuntimeError(+ "the installed cua-fleet release does not support claim renewal; "+ "upgrade to a build whose CyclopsClient exposes renew_claim"+ )+ return await renew(claim, shutdown_time)+async def delete_claim(self, claim: Any) -> None:await self._client.delete_claim(claim)@@ -264,6 +277,9 @@ class _FleetClient:async def get_pool(self, name: str) -> Any:return await self._client.get_pool(name)+ async def list_claims(self, namespace: str) -> list[Any]:+ return await self._client.list_claims(namespace)+async def get_claim(self, pool: Any, name: str | None = None) -> Any:expected = name or _claim_name(pool.metadata.name)for claim in await self._client.list_claims(pool.metadata.namespace):@@ -591,7 +607,7 @@ class FleetCloudTransport(FleetTransport):@staticmethoddef _validate_image(image: Image) -> None:if not image._registry:- raise ValueError("Fleet cloud sandboxes require Image.from_registry(...)")+ raise NotImplementedError("Fleet cloud sandboxes require Image.from_registry(...)")if (image._layersor image._env@@ -599,6 +615,6 @@ class FleetCloudTransport(FleetTransport):or image._snapshot_sourceor image._disk_path):- raise ValueError(+ raise NotImplementedError("Fleet cloud supports registry images with optional exposed services only")diff --git a/libs/python/cua-sandbox/tests/live/test_fleet_ephemeral.py b/libs/python/cua-sandbox/tests/live/test_fleet_ephemeral.pyindex 0d3e2b4a06..228b01a3f7 100644--- a/libs/python/cua-sandbox/tests/live/test_fleet_ephemeral.py+++ b/libs/python/cua-sandbox/tests/live/test_fleet_ephemeral.py@@ -92,21 +92,31 @@ async def run_fleet_ephemeral_live() -> None:memory_mb=4096,server_port=8000,time_to_start=900,- request_timeout=60,telemetry_enabled=False,) as sandbox:sandbox_yielded = Truesummary["provision_seconds"] = time.monotonic() - startedsummary["sandbox_name"] = sandbox.name+ sandbox_claim_name = getattr(sandbox, "claim_name", None)+ sandbox_pool_name = getattr(sandbox, "pool_name", None)+ claim_name = sandbox_claim_name or sandbox.name+ pool_name = sandbox_pool_name or namespace+ summary["claim_name"] = claim_name+ summary["pool_name"] = pool_nametry:assert (isinstance(sandbox.name, str) and sandbox.name), "sandbox name must be a non-empty string"- assert (- sandbox.name == namespace- ), f"sandbox name {sandbox.name!r} must equal namespace {namespace!r}"-- template = await fleet.get_template(namespace, namespace)+ if sandbox_claim_name is not None:+ assert (+ claim_name == namespace+ ), f"claim name {claim_name!r} must equal requested name {namespace!r}"+ if sandbox_pool_name is not None:+ assert (+ pool_name == namespace+ ), f"pool name {pool_name!r} must equal requested name {namespace!r}"++ template = await fleet.get_template(pool_name, pool_name)assert_template_contract(template, expected_port=8000)width, height = await sandbox.screen.size()@@ -144,16 +154,18 @@ async def run_fleet_ephemeral_live() -> None:cleanup_started = time.monotonic()claims_absent: bool | None = Noneinventory: dict[str, list[str]] | None = None- try:- claims_absent = await wait_claims_absent(fleet, namespace)- summary["claims_absent"] = claims_absent- except BaseException as error:- record_cleanup_error(error)- try:- inventory = await collect_resource_inventory(fleet, namespace)- summary["persistent_resources"] = inventory- except BaseException as error:- record_cleanup_error(error)+ resource_namespace = summary.get("pool_name")+ if resource_namespace is not None:+ try:+ claims_absent = await wait_claims_absent(fleet, resource_namespace)+ summary["claims_absent"] = claims_absent+ except BaseException as error:+ record_cleanup_error(error)+ try:+ inventory = await collect_resource_inventory(fleet, resource_namespace)+ summary["persistent_resources"] = inventory+ except BaseException as error:+ record_cleanup_error(error)if claims_absent is False:try:@@ -162,7 +174,7 @@ async def run_fleet_ephemeral_live() -> None:except BaseException as error:record_cleanup_error(error)if sandbox_yielded and inventory is not None:- expected_inventory = {"templates": [namespace], "pools": [namespace], "claims": []}+ expected_inventory = {"templates": [], "pools": [], "claims": []}if inventory != expected_inventory:try:summary["unexpected_inventory"] = Truediff --git a/libs/python/cua-sandbox/tests/test_cloud.py b/libs/python/cua-sandbox/tests/test_cloud.pyindex afea3ae331..56b23aacbe 100644--- a/libs/python/cua-sandbox/tests/test_cloud.py+++ b/libs/python/cua-sandbox/tests/test_cloud.py@@ -9,9 +9,11 @@ from __future__ import annotationsimport importlibimport os+from types import SimpleNamespace+from unittest.mock import AsyncMockimport pytest-from cua_sandbox import Image, Sandbox, _config+from cua_sandbox import Image, Pool, Sandbox, _configfrom cua_sandbox.runtime.base import RuntimeInfosandbox_module = importlib.import_module("cua_sandbox.sandbox")@@ -40,19 +42,19 @@ async def test_cloud_routes_fleet_auth_without_explicit_legacy_key(monkeypatch,for variable, value in auth_environment.items():monkeypatch.setenv(variable, value)- class FleetTransport:- def __init__(self, **kwargs):- routes.append(("fleet", kwargs))- self.name = kwargs["name"]-- async def connect(self):- return None-+ class ClaimedSandbox:async def disconnect(self):return None- async def delete_vm(self):- return None+ class FleetPool:+ name = "fleet-pool"++ async def claim(self, **kwargs):+ routes.append(("fleet", kwargs))+ return ClaimedSandbox()++ async def apply_pool(cls, image, **kwargs):+ return FleetPool()class LegacyTransport:def __init__(self, **kwargs):@@ -65,7 +67,7 @@ async def test_cloud_routes_fleet_auth_without_explicit_legacy_key(monkeypatch,async def disconnect(self):return None- monkeypatch.setattr(sandbox_module, "FleetCloudTransport", FleetTransport)+ monkeypatch.setattr(Pool, "apply", classmethod(apply_pool))monkeypatch.setattr(sandbox_module, "_make_transport", lambda **kwargs: LegacyTransport(**kwargs))@@ -85,6 +87,76 @@ async def test_cloud_routes_fleet_auth_without_explicit_legacy_key(monkeypatch,][email protected]("legacy_source", ["configured", "environment", "credentials"])+async def test_registry_image_uses_legacy_auth_when_fleet_auth_is_unavailable(+ monkeypatch, legacy_source+):+ routes = []+ monkeypatch.setattr(_config, "_global_config", _config._Config())+ for variable in (+ "CUA_API_KEY",+ "FLEETS_TOKEN",+ "CUA_CLIENT_ID",+ "CUA_CLIENT_SECRET",+ ):+ monkeypatch.delenv(variable, raising=False)++ if legacy_source == "configured":+ _config.configure(api_key="sk-configured")+ elif legacy_source == "environment":+ monkeypatch.setenv("CUA_API_KEY", "sk-environment")+ else:+ monkeypatch.setattr(_config, "_read_credentials_key", lambda: "sk-credentials")++ class LegacyTransport:+ def __init__(self, **kwargs):+ routes.append(kwargs)+ self.name = kwargs["name"]++ async def connect(self):+ return None++ async def disconnect(self):+ return None++ async def reject_fleet_apply(cls, image, **kwargs):+ raise AssertionError("legacy authentication must not route registry images to Fleet")++ monkeypatch.setattr(Pool, "apply", classmethod(reject_fleet_apply))+ monkeypatch.setattr(+ sandbox_module, "_make_transport", lambda **kwargs: LegacyTransport(**kwargs)+ )++ sandbox = await Sandbox.create(Image.from_registry("example:latest"), name="legacy-demo")+ await sandbox.disconnect()++ assert not Sandbox._uses_fleet(None)+ assert [route["name"] for route in routes] == ["legacy-demo"]+++async def test_ephemeral_registry_image_uses_legacy_auth_selector(monkeypatch):+ monkeypatch.setattr(_config, "_global_config", _config._Config(api_key="sk-configured"))+ for variable in ("FLEETS_TOKEN", "CUA_CLIENT_ID", "CUA_CLIENT_SECRET"):+ monkeypatch.delenv(variable, raising=False)++ legacy_sandbox = SimpleNamespace(+ _has_snapshots=False,+ name="legacy-demo",+ destroy=AsyncMock(),+ )+ create = AsyncMock()+ create_legacy = AsyncMock(return_value=legacy_sandbox)+ monkeypatch.setattr(Sandbox, "create", create)+ monkeypatch.setattr(Sandbox, "_create", create_legacy)++ async with Sandbox.ephemeral(Image.from_registry("example:latest"), name="legacy-demo"):+ pass++ create.assert_not_awaited()+ create_legacy.assert_awaited_once()+ legacy_sandbox.destroy.assert_awaited_once()++async def test_cloud_local_creation_never_routes_to_fleet(monkeypatch):calls = []@@ -212,36 +284,26 @@ async def test_cloud_invalid_api_key_errors():async def test_pool_backed_create_persists_claim_pool_mapping(monkeypatch, tmp_path):from cua_sandbox import sandbox_state- created = []monkeypatch.setattr(sandbox_state, "SANDBOX_STATE_DIR", tmp_path)- class FleetTransport:- def __init__(self, **kwargs):- created.append(kwargs)- self.name = kwargs["name"]+ class ClaimedSandbox:+ pass- async def connect(self):- return None+ class FleetPool:+ name = "cua-cli-wif-smoke"- async def disconnect(self):- return None+ async def claim(self, **kwargs):+ assert kwargs["name"] == "wif-smoke-123"+ return ClaimedSandbox()- monkeypatch.setattr(sandbox_module, "FleetCloudTransport", FleetTransport)+ async def get_pool(cls, name):+ assert name == "cua-cli-wif-smoke"+ return FleetPool()++ monkeypatch.setattr(Pool, "get", classmethod(get_pool))await Sandbox.create(pool="cua-cli-wif-smoke", name="wif-smoke-123")- assert created == [- {- "image": None,- "name": "wif-smoke-123",- "pool_name": "cua-cli-wif-smoke",- "create_claim": True,- "region": "us-east-1",- "time_to_start": None,- "request_timeout": None,- "server_port": 8000,- }- ]assert sandbox_state.load("wif-smoke-123")["pool_name"] == "cua-cli-wif-smoke"diff --git a/libs/python/cua-sandbox/tests/test_fleet_cloud_transport.py b/libs/python/cua-sandbox/tests/test_fleet_cloud_transport.pyindex 686fc050f5..915e985960 100644--- a/libs/python/cua-sandbox/tests/test_fleet_cloud_transport.py+++ b/libs/python/cua-sandbox/tests/test_fleet_cloud_transport.py@@ -136,7 +136,7 @@ async def test_fleet_client_lookup_uses_bounded_deterministic_claim_name():"image", [Image.linux(), Image.from_registry("example:latest").apt_install("curl")])def test_rejects_unsupported_images(image):- with pytest.raises(ValueError):+ with pytest.raises(NotImplementedError):FleetCloudTransport._validate_image(image)diff --git a/libs/python/cua-sandbox/tests/test_live_fleet_e2e_support.py b/libs/python/cua-sandbox/tests/test_live_fleet_e2e_support.pyindex ff9de869e3..3055122634 100644--- a/libs/python/cua-sandbox/tests/test_live_fleet_e2e_support.py+++ b/libs/python/cua-sandbox/tests/test_live_fleet_e2e_support.py@@ -258,9 +258,7 @@ def test_selected_namespace_rejects_unsafe_override(monkeypatch) -> None:@pytest.mark.asyncio-async def test_existing_safe_namespace_is_reused_without_explicit_deletion(- monkeypatch, tmp_path-) -> None:+async def test_owned_ephemeral_namespace_is_empty_after_cleanup(monkeypatch, tmp_path) -> None:from tests.live import test_fleet_ephemeral as live_testcalls: list[str] = []@@ -306,7 +304,7 @@ async def test_existing_safe_namespace_is_reused_without_explicit_deletion(return Trueasync def collect_resource_inventory(fleet, namespace: str):- return {"templates": [namespace], "pools": [namespace], "claims": []}+ return {"templates": [], "pools": [], "claims": []}monkeypatch.setenv("CUA_LIVE_E2E_NAMESPACE", "cua-live-existing")monkeypatch.setenv("CUA_LIVE_E2E_ARTIFACT_DIR", str(tmp_path))@@ -321,8 +319,8 @@ async def test_existing_safe_namespace_is_reused_without_explicit_deletion(assert calls == ["provision", "close"]assert summaries[-1]["persistent_resources"] == {- "templates": ["cua-live-existing"],- "pools": ["cua-live-existing"],+ "templates": [],+ "pools": [],"claims": [],}@@ -567,7 +565,7 @@ async def test_provisioning_failure_before_yield_never_deletes_namespace(monkeyp@pytest.mark.asyncio-async def test_pre_yield_claim_leak_is_recorded_without_masking_provisioning_error(+async def test_pre_yield_failure_records_no_inventory_without_pool_identity(monkeypatch, tmp_path) -> None:from tests.live import test_fleet_ephemeral as live_test@@ -605,13 +603,13 @@ async def test_pre_yield_claim_leak_is_recorded_without_masking_provisioning_errwith pytest.raises(ProvisioningFailure, match="provisioning failed"):await live_test.run_fleet_ephemeral_live()- assert summaries[-1]["claim_leak"] is True- assert summaries[-1]["persistent_resources"]["claims"] == ["claim-a"]- assert summaries[-1]["cleanup_error"] == {"type": "Failed"}+ assert summaries[-1]["provisioning"] == {"attempted": True, "sandbox_yielded": False}+ assert "persistent_resources" not in summaries[-1]+ assert "cleanup_error" not in summaries[-1]@pytest.mark.asyncio-async def test_pre_yield_missing_namespace_records_empty_inventory_without_cleanup_failure(+async def test_pre_yield_missing_namespace_skips_inventory_without_pool_identity(monkeypatch, tmp_path) -> None:from tests.live import test_fleet_ephemeral as live_test@@ -650,7 +648,7 @@ async def test_pre_yield_missing_namespace_records_empty_inventory_without_cleanawait live_test.run_fleet_ephemeral_live()assert summaries[-1]["provisioning"] == {"attempted": True, "sandbox_yielded": False}- assert summaries[-1]["persistent_resources"] == {"templates": [], "pools": [], "claims": []}+ assert "persistent_resources" not in summaries[-1]assert "cleanup_error" not in summaries[-1]@@ -694,18 +692,21 @@ async def test_live_runner_uses_pinned_ephemeral_configuration(monkeypatch) -> N"memory_mb": 4096,"server_port": 8000,"time_to_start": 900,- "request_timeout": 60,"telemetry_enabled": False,}@pytest.mark.asyncio@pytest.mark.parametrize(- ("sandbox_name", "message"),- [("", "non-empty string"), ("cua-live-unexpected", "must equal namespace")],+ ("sandbox_name", "sandbox_pool_name", "message"),+ [+ ("", "cua-live-identity", "non-empty string"),+ ("cua-live-unexpected", "cua-live-identity", "claim name"),+ ("cua-live-identity", "cua-live-unexpected", "pool name"),+ ],)async def test_invalid_sandbox_identity_preserves_primary_error_and_runs_cleanup(- monkeypatch, tmp_path, sandbox_name: str, message: str+ monkeypatch, tmp_path, sandbox_name: str, sandbox_pool_name: str, message: str) -> None:from tests.live import test_fleet_ephemeral as live_test@@ -713,6 +714,8 @@ async def test_invalid_sandbox_identity_preserves_primary_error_and_runs_cleanupclass FakeSandbox:name = sandbox_name+ claim_name = sandbox_name+ pool_name = sandbox_pool_nameclass FakeEphemeral:async def __aenter__(self):diff --git a/libs/python/cua-sandbox/tests/test_pool.py b/libs/python/cua-sandbox/tests/test_pool.pyindex dd33144219..6cda02107e 100644--- a/libs/python/cua-sandbox/tests/test_pool.py+++ b/libs/python/cua-sandbox/tests/test_pool.py@@ -10,6 +10,7 @@ from cua_sandbox import (CreateTemplateRequest,CreateTemplateRequestBuilder,Firmware,+ Image,OsGymSandboxTemplateSpecBuilder,OsGymSandboxWarmPoolSpecBuilder,Pool,@@ -21,10 +22,12 @@ from cua_sandbox import (VmTemplate,VmTemplateBuilder,)+from cua_sandbox.pool import _ClaimHandlefrom cua_sandbox.sync import Pool as SyncPoolfrom cua_sandbox.sync import Template as SyncTemplatefrom cua_sandbox.transport.fleet_cloud import _FleetClientfrom fleet_sdk import Sandbox as FleetSandbox+from fleet_sdk import SdkErrordef test_public_pool_schema_exports_runtime_kind() -> None:@@ -125,6 +128,10 @@ def fleet_template(name: str = "foo") -> SimpleNamespace:)+def fake_claim(namespace: str = "foo", name: str = "claim-1") -> SimpleNamespace:+ return SimpleNamespace(metadata=SimpleNamespace(namespace=namespace, name=name))++class FakeFleetClient:def __init__(self,@@ -139,8 +146,12 @@ class FakeFleetClient:self.reconciled: list[object] = []self.reconciled_templates: list[object] = []self.claims: list[object] = []- self.released: list[object] = []+ self.released: list[str] = []+ self.deleted_pools: list[str] = []+ self.deleted_templates: list[str] = []+ self.renewed: list[tuple[str, str]] = []self.service_requests: list[object] = []+ self.wait_calls = 0self.closed = Falseasync def reconcile_pool(self, request: object) -> object:@@ -155,12 +166,16 @@ class FakeFleetClient:raise self.reconcile_errorreturn self.existing or fleet_template(request.name)+ async def get_pool(self, name: str) -> object:+ return self.existing or fleet_pool(name)+async def create_claim(self, request: object) -> object:self.claims.append(request)- return "claim-1"+ return fake_claim()async def wait_claim(self, claim: object) -> FleetSandbox:- assert claim == "claim-1"+ assert claim.metadata.name == "claim-1"+ self.wait_calls += 1return FleetSandbox(namespace="foo",claim="claim-1",@@ -168,15 +183,28 @@ class FakeFleetClient:services=["server", "mcp"],)+ async def wait_service_ready(self, sandbox, service, time_to_start=None) -> None:+ return None++ async def renew_claim(self, claim: object, shutdown_time: str) -> object:+ self.renewed.append((claim.metadata.name, shutdown_time))+ return claim+async def service_request(self, sandbox, service, path, request):self.service_requests.append((sandbox, service, path, request))return SimpleNamespace(status=200, headers=[], body=b'{"result":"ok"}')async def delete_claim(self, claim: object) -> None:- self.released.append(claim)+ self.released.append(claim.metadata.name)if self.release_error:raise self.release_error+ async def delete_pool(self, pool: object) -> None:+ self.deleted_pools.append(pool.metadata.name)++ async def delete_template(self, template: object) -> None:+ self.deleted_templates.append(template.metadata.name)+async def close(self) -> None:self.closed = True@@ -248,6 +276,17 @@ async def test_reconcile_creates_pool_referencing_a_template(monkeypatch):assert request.spec.replicas == 1+async def test_pool_delete_deletes_resource_and_closes_client(monkeypatch):+ client = FakeFleetClient()+ monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: client)++ await Pool(fleet_pool()).delete()++ assert client.deleted_pools == ["foo"]+ assert client.closed is True++@pytest.mark.asyncioasync def test_template_reconcile_creates_template_from_registry_image(monkeypatch):client = FakeFleetClient()@@ -381,6 +420,16 @@ async def test_reconcile_rejects_non_request(invalid_value):await Pool.reconcile(invalid_value)+def test_sync_pool_delete_matches_async_facade(monkeypatch):+ client = FakeFleetClient()+ monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: client)++ SyncPool(Pool(fleet_pool())).delete()++ assert client.deleted_pools == ["foo"]+ assert client.closed is True++def test_sync_pool_matches_blocking_context_manager(monkeypatch):reconcile_client = FakeFleetClient()claim_client = FakeFleetClient()@@ -536,3 +585,340 @@ async def test_claim_without_spec_uses_operator_default(monkeypatch):assert request.spec is Noneassert claim_client.released == ["claim-1"]assert claim_client.closed is True+++async def test_pool_get_fetches_without_reconciling(monkeypatch):+ client = FakeFleetClient()+ monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: client)++ pool = await Pool.get("foo")++ assert pool.name == "foo"+ assert client.reconciled == []+ assert client.closed is True+++async def test_create_claim_returns_a_serializable_lease(monkeypatch):+ reconcile_client = FakeFleetClient()+ claim_client = FakeFleetClient()+ clients = iter([reconcile_client, claim_client])+ monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: next(clients))+ pool = await Pool.reconcile(pool_request())++ lease = await pool.create_claim()++ assert (lease.namespace, lease.name) == ("foo", "claim-1")+ assert claim_client.claims[0].pool is pool.resource+ assert claim_client.claims[0].spec is None+ assert claim_client.released == []+ assert claim_client.closed is True+ assert lease.to_dict() == {+ "version": 1,+ "provider": "fleet",+ "namespace": "foo",+ "pool": "foo",+ "claim": "claim-1",+ "service": "server",+ }+ assert _ClaimHandle.from_dict(lease.to_dict()).to_dict() == lease.to_dict()+++async def test_lease_wait_connects_to_the_named_service_and_caches_the_bind(monkeypatch):+ client = FakeFleetClient()+ monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: client)+ lease = _ClaimHandle(namespace="foo", name="claim-1", pool_name="foo")++ sandbox = await lease.wait(service="mcp")++ assert sandbox.name == "sandbox-1"+ assert client.wait_calls == 1+ assert lease.to_dict()["claim"] == "claim-1"+ response = await sandbox.services.request(+ "mcp", method="POST", path="/mcp", json={"jsonrpc": "2.0", "id": 1}+ )+ assert response.status_code == 200+ assert client.closed is False+ await sandbox.disconnect()+ assert client.closed is True+++async def test_lease_reattaches_from_serialized_state_without_polling(monkeypatch):+ client = FakeFleetClient()+ monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: client)+ lease = _ClaimHandle.from_dict(+ {+ "version": 1,+ "provider": "fleet",+ "namespace": "foo",+ "pool": "foo",+ "claim": "claim-1",+ }+ )++ sandbox = await lease.wait(service="mcp")++ assert sandbox.name == "sandbox-1"+ assert client.wait_calls == 1+ await sandbox.disconnect()+ assert client.closed is True+++async def test_lease_wait_closes_its_client_when_the_bind_fails(monkeypatch):+ client = FakeFleetClient()++ async def failing_wait(claim):+ raise RuntimeError("bind failed")++ client.wait_claim = failing_wait+ monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: client)++ with pytest.raises(RuntimeError, match="bind failed"):+ await _ClaimHandle(namespace="foo", name="claim-1", pool_name="foo").wait()++ assert client.closed is True+++async def test_lease_release_deletes_the_claim_by_reference(monkeypatch):+ client = FakeFleetClient()+ monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: client)++ await _ClaimHandle(namespace="foo", name="claim-1", pool_name="foo").release()++ assert client.released == ["claim-1"]+ assert client.closed is True+++async def test_release_tolerates_claim_already_deleted_by_another_process(monkeypatch):+ first_client = FakeFleetClient()+ second_client = FakeFleetClient()++ async def already_deleted(claim):+ raise SdkError.Status("delete claim", 404, b"not found")++ second_client.delete_claim = already_deleted+ clients = iter([first_client, second_client])+ monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: next(clients))++ await _ClaimHandle(namespace="foo", name="claim-1", pool_name="foo").release()+ await _ClaimHandle(namespace="foo", name="claim-1", pool_name="foo").release()++ assert first_client.released == ["claim-1"]+ assert first_client.closed is True+ assert second_client.closed is True+++async def test_lease_renew_pushes_the_shutdown_time_forward(monkeypatch):+ client = FakeFleetClient()+ monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: client)++ await _ClaimHandle(namespace="foo", name="claim-1", pool_name="foo").renew(+ "2026-01-01T00:10:00Z"+ )++ assert client.renewed == [("claim-1", "2026-01-01T00:10:00Z")]+ assert client.closed is True+++async def test_fleet_client_renew_claim_requires_a_release_with_renew_support():+ client = object.__new__(_FleetClient)+ client._client = object()++ with pytest.raises(RuntimeError, match="renew_claim"):+ await client.renew_claim(fake_claim(), "2026-01-01T00:10:00Z")+++async def test_fleet_client_renew_claim_delegates_when_supported():+ calls = []++ class GeneratedClient:+ async def renew_claim(self, claim, shutdown_time):+ calls.append((claim, shutdown_time))+ return "renewed"++ client = object.__new__(_FleetClient)+ client._client = GeneratedClient()++ assert await client.renew_claim("claim", "2026-01-01T00:10:00Z") == "renewed"+ assert calls == [("claim", "2026-01-01T00:10:00Z")]+++async def test_named_claim_retry_reattaches_without_creating(monkeypatch):+ client = FakeFleetClient()+ client.existing_claims = [fake_claim()]++ async def list_claims(namespace: str):+ assert namespace == "foo"+ return client.existing_claims++ client.list_claims = list_claims+ monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: client)++ sandbox = await Pool(fleet_pool()).claim(name="claim-1")++ assert client.claims == []+ assert sandbox.claim_name == "claim-1"+ assert sandbox.to_dict()["service"] == "server"+ await sandbox.close()+++async def test_named_claim_reattach_failure_does_not_release_existing_claim(monkeypatch):+ client = FakeFleetClient()+ client.existing_claims = [fake_claim()]++ async def list_claims(namespace: str):+ assert namespace == "foo"+ return client.existing_claims++ async def failing_wait(claim):+ raise RuntimeError("bind failed")++ client.list_claims = list_claims+ client.wait_claim = failing_wait+ monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: client)++ with pytest.raises(RuntimeError, match="bind failed"):+ await Pool(fleet_pool()).claim(name="claim-1")++ assert client.claims == []+ assert client.released == []+ assert client.closed is True+++async def test_new_claim_acquisition_failure_releases_created_claim(monkeypatch):+ client = FakeFleetClient()++ async def list_claims(namespace: str):+ assert namespace == "foo"+ return []++ async def failing_wait(claim):+ raise RuntimeError("bind failed")++ client.list_claims = list_claims+ client.wait_claim = failing_wait+ monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: client)++ with pytest.raises(RuntimeError, match="bind failed"):+ await Pool(fleet_pool()).claim(name="claim-1")++ assert len(client.claims) == 1+ assert client.released == ["claim-1"]+ assert client.closed is True+++async def test_pool_apply_delegates_to_template_and_pool_reconcile(monkeypatch):+ template_requests = []+ pool_requests = []+ reconcile_order = []++ async def reconcile_template(cls, request):+ reconcile_order.append("template")+ template_requests.append(request)+ return Template(fleet_template(request.name))++ async def reconcile_pool(cls, request):+ reconcile_order.append("pool")+ pool_requests.append(request)+ return Pool(fleet_pool(request.namespace))++ monkeypatch.setattr(Template, "reconcile", classmethod(reconcile_template))+ monkeypatch.setattr(Pool, "reconcile", classmethod(reconcile_pool))++ pool = await Pool.apply(+ Image.from_registry("registry.example/workspace:latest"),+ cpu=4,+ memory_mb=4096,+ )++ assert reconcile_order == ["pool", "template"]+ assert len(template_requests) == 1+ assert len(pool_requests) == 1+ assert pool.name == pool_requests[0].namespace == template_requests[0].name+++async def test_pool_apply_delete_removes_owned_pool_and_template(monkeypatch):+ clients = [FakeFleetClient() for _ in range(3)]+ iterator = iter(clients)+ monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: next(iterator))++ pool = await Pool.apply(+ Image.from_registry("registry.example/workspace:latest"),+ name="workspace",+ )+ await pool.delete()++ assert clients[2].deleted_pools == ["workspace"]+ assert clients[2].deleted_templates == ["workspace"]+++async def test_pool_apply_rolls_back_pool_when_template_reconcile_fails(monkeypatch):+ clients = [+ FakeFleetClient(),+ FakeFleetClient(reconcile_error=RuntimeError("template failed")),+ FakeFleetClient(),+ ]+ iterator = iter(clients)+ monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: next(iterator))++ with pytest.raises(RuntimeError, match="template failed"):+ await Pool.apply(+ Image.from_registry("registry.example/workspace:latest"),+ name="workspace",+ )++ assert clients[2].deleted_pools == ["workspace"]+ assert clients[2].deleted_templates == []+++async def test_pool_apply_uses_stable_configuration_name(monkeypatch):+ from cua_sandbox import Image++ clients = [FakeFleetClient() for _ in range(6)]+ iterator = iter(clients)+ monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: next(iterator))+ image = Image.from_registry("registry.example/workspace:latest")++ first = await Pool.apply(image, replicas=1, cpu=4, memory_mb=4096)+ second = await Pool.apply(image, replicas=1, cpu=4, memory_mb=4096)+ explicit_default = await Pool.apply(+ image, replicas=1, cpu=4, memory_mb=4096, services={"server": 8000}+ )++ assert first.name == second.name == explicit_default.name+ assert first.name.startswith("cua-")+ assert clients[0].reconciled[0].namespace == first.name+ assert clients[1].reconciled_templates[0].name == first.name+++async def test_close_after_disconnect_reopens_client_for_release(monkeypatch):+ claim_client = FakeFleetClient()+ release_client = FakeFleetClient()+ clients = iter([claim_client, release_client])+ monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: next(clients))++ sandbox = await Pool(fleet_pool()).claim()+ await sandbox.disconnect()+ await sandbox.close()++ assert claim_client.closed is True+ assert claim_client.released == []+ assert release_client.released == ["claim-1"]+ assert release_client.closed is Truediff --git a/libs/python/cua-sandbox/tests/test_sandbox_fleet_lifecycle.py b/libs/python/cua-sandbox/tests/test_sandbox_fleet_lifecycle.pynew file mode 100644index 0000000000..781df3d58e--- /dev/null+++ b/libs/python/cua-sandbox/tests/test_sandbox_fleet_lifecycle.py@@ -0,0 +1,419 @@+from __future__ import annotations++from types import SimpleNamespace+from unittest.mock import AsyncMock++import pytest+from cua_sandbox import Image, Pool, Sandbox++[email protected](autouse=True)+def select_fleet_for_lifecycle_tests(monkeypatch):+ monkeypatch.setattr(Sandbox, "_uses_fleet", staticmethod(lambda api_key: api_key is None))+++class FakePool:+ def __init__(self, name: str = "workspace") -> None:+ self.name = name+ self.claims: list[dict] = []+ self.deletes = 0++ async def claim(self, **kwargs):+ self.claims.append(kwargs)+ return SimpleNamespace(name="sandbox-1", claim_name=kwargs.get("name"), pool_name=self.name)++ async def delete(self):+ self.deletes += 1+++async def test_create_with_pool_name_uses_read_only_pool_lookup(monkeypatch):+ pool = FakePool()+ looked_up: list[str] = []++ async def get_pool(cls, name: str):+ looked_up.append(name)+ return pool++ monkeypatch.setattr(Pool, "get", classmethod(get_pool), raising=False)++ sandbox = await Sandbox.create(pool="workspace", name="job-123", service="mcp")++ assert looked_up == ["workspace"]+ assert pool.claims == [+ {"name": "job-123", "spec": None, "service": "mcp", "time_to_start": None}+ ]+ assert sandbox.claim_name == "job-123"+++async def test_create_without_pool_applies_image_then_claims(monkeypatch):+ pool = FakePool("derived-pool")+ applied: list[dict] = []++ async def apply_pool(cls, image, **kwargs):+ applied.append({"image": image, **kwargs})+ return pool++ monkeypatch.setattr(Pool, "apply", classmethod(apply_pool), raising=False)+ image = Image.from_registry("registry.example/workspace:latest")++ sandbox = await Sandbox.create(+ image,+ name="job-123",+ replicas=1,+ cpu=4,+ memory_mb=4096,+ service="mcp",+ )++ assert applied == [+ {+ "image": image,+ "replicas": 1,+ "cpu": 4,+ "memory_mb": 4096,+ "services": {"server": 8000},+ }+ ]+ assert pool.claims[0]["name"] == "job-123"+ assert sandbox.pool_name == "derived-pool"+++async def test_image_create_persists_generated_claim_pool_mapping(monkeypatch, tmp_path):+ from cua_sandbox import sandbox_state++ class ClaimedSandbox:+ name = "bound-sandbox-1"+ claim_name = "generated-claim-1"+ pool_name = "derived-pool"++ pool = FakePool("derived-pool")++ async def claim(**kwargs):+ pool.claims.append(kwargs)+ return ClaimedSandbox()++ pool.claim = claim+ monkeypatch.setattr(sandbox_state, "SANDBOX_STATE_DIR", tmp_path)+ monkeypatch.setattr(Pool, "apply", AsyncMock(return_value=pool))++ sandbox = await Sandbox.create(Image.from_registry("registry.example/workspace:latest"))++ assert sandbox.name == "bound-sandbox-1"+ assert sandbox.claim_name == "generated-claim-1"+ assert sandbox_state.load("generated-claim-1")["pool_name"] == "derived-pool"++[email protected]("source", ["existing-pool", "image"])+async def test_keep_alive_failure_releases_claim_without_persisting_state(+ monkeypatch, tmp_path, source+):+ from cua_sandbox import sandbox_state++ claimed = SimpleNamespace(+ name="bound-sandbox-1",+ claim_name="job-123",+ pool_name="workspace",+ keep_alive=AsyncMock(side_effect=RuntimeError("renew failed")),+ close=AsyncMock(),+ )+ pool = FakePool("workspace")+ pool.claim = AsyncMock(return_value=claimed)+ monkeypatch.setattr(sandbox_state, "SANDBOX_STATE_DIR", tmp_path)++ if source == "existing-pool":+ monkeypatch.setattr(Pool, "get", AsyncMock(return_value=pool))+ create = Sandbox.create(pool="workspace", name="job-123", keep_alive_minutes=30)+ else:+ monkeypatch.setattr(Pool, "apply", AsyncMock(return_value=pool))+ create = Sandbox.create(+ Image.from_registry("registry.example/workspace:latest"),+ name="job-123",+ keep_alive_minutes=30,+ )++ with pytest.raises(RuntimeError, match="renew failed"):+ await create++ claimed.close.assert_awaited_once()+ assert sandbox_state.load("job-123") is None+++async def test_state_persistence_failure_releases_acquired_claim(monkeypatch, tmp_path):+ from cua_sandbox import sandbox_state++ claimed = SimpleNamespace(+ name="bound-sandbox-1",+ claim_name="job-123",+ pool_name="workspace",+ close=AsyncMock(),+ )+ pool = FakePool("workspace")+ pool.claim = AsyncMock(return_value=claimed)+ monkeypatch.setattr(Pool, "get", AsyncMock(return_value=pool))+ monkeypatch.setattr(sandbox_state, "SANDBOX_STATE_DIR", tmp_path)+ monkeypatch.setattr(+ sandbox_state,+ "save_fleet_claim",+ lambda *args, **kwargs: (_ for _ in ()).throw(OSError("state write failed")),+ )++ with pytest.raises(OSError, match="state write failed"):+ await Sandbox.create(pool="workspace", name="job-123")++ claimed.close.assert_awaited_once()+++async def test_keep_alive_failure_preserves_error_when_claim_close_fails(monkeypatch):+ claimed = SimpleNamespace(+ name="bound-sandbox-1",+ claim_name="job-123",+ pool_name="workspace",+ keep_alive=AsyncMock(side_effect=RuntimeError("renew failed")),+ close=AsyncMock(side_effect=RuntimeError("close failed")),+ )+ pool = FakePool("workspace")+ pool.claim = AsyncMock(return_value=claimed)+ monkeypatch.setattr(Pool, "apply", AsyncMock(return_value=pool))++ with pytest.raises(RuntimeError, match="renew failed") as error:+ await Sandbox.create(+ Image.from_registry("registry.example/workspace:latest"),+ name="job-123",+ keep_alive_minutes=30,+ )++ assert isinstance(error.value.__cause__, RuntimeError)+ assert str(error.value.__cause__) == "close failed"+++async def test_create_rejects_pool_and_image_together():+ with pytest.raises(ValueError, match="mutually exclusive"):+ await Sandbox.create(Image.from_registry("registry.example/workspace:latest"), pool="pool")+++async def test_create_rejects_pool_configuration_for_existing_pool():+ with pytest.raises(ValueError, match="existing pool"):+ await Sandbox.create(pool="pool", replicas=2)+++class FakeTransport:+ def __init__(self) -> None:+ self.disconnects = 0++ async def connect(self) -> None:+ return None++ async def disconnect(self) -> None:+ self.disconnects += 1+++class FakeClaimHandle:+ name = "job-123"+ pool_name = "workspace"++ def __init__(self) -> None:+ self.releases = 0+ self.renewals: list[str] = []++ def to_dict(self):+ return {+ "version": 1,+ "provider": "fleet",+ "namespace": "workspace",+ "pool": "workspace",+ "claim": "job-123",+ }++ async def release(self) -> None:+ self.releases += 1++ async def renew(self, shutdown_time: str) -> None:+ self.renewals.append(shutdown_time)+++async def test_disconnect_keeps_claim_and_close_releases_once():+ transport = FakeTransport()+ handle = FakeClaimHandle()+ sandbox = Sandbox(transport, name="sandbox-1")+ sandbox._claim_handle = handle++ await sandbox.disconnect()+ assert handle.releases == 0++ await sandbox.close()+ await sandbox.close()++ assert handle.releases == 1+ assert transport.disconnects == 2+++async def test_close_removes_persisted_claim_mapping(monkeypatch, tmp_path):+ from cua_sandbox import sandbox_state++ monkeypatch.setattr(sandbox_state, "SANDBOX_STATE_DIR", tmp_path)+ sandbox_state.save_fleet_claim("job-123", "workspace")+ handle = FakeClaimHandle()+ sandbox = Sandbox(FakeTransport(), name="sandbox-1")+ sandbox._claim_handle = handle++ await sandbox.close()++ assert sandbox_state.load("job-123") is None+++async def test_keep_alive_renews_with_utc_deadline():+ handle = FakeClaimHandle()+ sandbox = Sandbox(FakeTransport(), name="sandbox-1")+ sandbox._claim_handle = handle++ await sandbox.keep_alive(minutes=30)++ assert len(handle.renewals) == 1+ assert handle.renewals[0].endswith("Z")+++def test_to_dict_serializes_claim_not_bound_transport():+ handle = FakeClaimHandle()+ sandbox = Sandbox(FakeTransport(), name="sandbox-1")+ sandbox._claim_handle = handle++ assert sandbox.claim_name == "job-123"+ assert sandbox.pool_name == "workspace"+ assert sandbox.to_dict()["claim"] == "job-123"+ assert "sandbox-1" not in str(sandbox.to_dict())+++async def test_ephemeral_pool_closes_claim(monkeypatch):+ closed: list[bool] = []++ class Claimed:+ async def close(self):+ closed.append(True)++ async def create(cls, *args, **kwargs):+ return Claimed()++ monkeypatch.setattr(Sandbox, "create", classmethod(create))++ async with Sandbox.ephemeral(pool="workspace"):+ pass++ assert closed == [True]+++async def test_ephemeral_image_uses_name_for_owned_pool_and_claim(monkeypatch):+ claimed = SimpleNamespace(close=AsyncMock())+ pool = FakePool("cua-live-main-source-manual")+ pool.claim = AsyncMock(return_value=claimed)+ applied: list[dict] = []++ async def apply_pool(cls, image, **kwargs):+ applied.append({"image": image, **kwargs})+ return pool++ monkeypatch.setattr(Pool, "apply", classmethod(apply_pool), raising=False)+ image = Image.from_registry("registry.example/workspace:latest")++ async with Sandbox.ephemeral(+ image,+ name="cua-live-main-source-manual",+ cpu=4,+ memory_mb=4096,+ ):+ pass++ assert applied == [+ {+ "image": image,+ "name": "cua-live-main-source-manual",+ "replicas": 1,+ "cpu": 4,+ "memory_mb": 4096,+ "services": {"server": 8000},+ }+ ]+ pool.claim.assert_awaited_once_with(+ name="cua-live-main-source-manual",+ spec=None,+ service="server",+ time_to_start=None,+ )+ claimed.close.assert_awaited_once()+ assert pool.deletes == 1+++async def test_ephemeral_image_keep_pool_reuses_deterministic_pool(monkeypatch):+ claimed = SimpleNamespace(close=AsyncMock())+ pool = FakePool("shared-pool")+ pool.claim = AsyncMock(return_value=claimed)+ apply_pool = AsyncMock(return_value=pool)+ monkeypatch.setattr(Pool, "apply", apply_pool)+ image = Image.from_registry("registry.example/workspace:latest")++ async with Sandbox.ephemeral(image, keep_pool=True):+ pass++ assert "name" not in apply_pool.await_args.kwargs+ claimed.close.assert_awaited_once()+ assert pool.deletes == 0+++async def test_ephemeral_rejects_keep_pool_for_existing_pool():+ with pytest.raises(ValueError, match="keep_pool"):+ async with Sandbox.ephemeral(pool="workspace", keep_pool=True):+ pass+++async def test_ephemeral_rejects_keep_pool_outside_fleet_image_mode():+ with pytest.raises(ValueError, match="keep_pool"):+ async with Sandbox.ephemeral(+ Image.from_registry("registry.example/workspace:latest"),+ api_key="legacy-key",+ keep_pool=True,+ ):+ pass+++async def test_ephemeral_image_deletes_owned_pool_when_claim_fails(monkeypatch):+ pool = FakePool("owned-pool")+ pool.claim = AsyncMock(side_effect=RuntimeError("claim failed"))+ monkeypatch.setattr(Pool, "apply", AsyncMock(return_value=pool))++ with pytest.raises(RuntimeError, match="claim failed"):+ async with Sandbox.ephemeral(Image.from_registry("registry.example/workspace:latest")):+ pass++ assert pool.deletes == 1+++async def test_ephemeral_image_preserves_body_error_when_owned_pool_cleanup_fails(monkeypatch):+ claimed = SimpleNamespace(close=AsyncMock(side_effect=RuntimeError("claim cleanup failed")))+ pool = FakePool("owned-pool")+ pool.claim = AsyncMock(return_value=claimed)+ pool.delete = AsyncMock(side_effect=RuntimeError("pool cleanup failed"))+ monkeypatch.setattr(Pool, "apply", AsyncMock(return_value=pool))++ with pytest.raises(ValueError, match="body failed"):+ async with Sandbox.ephemeral(Image.from_registry("registry.example/workspace:latest")):+ raise ValueError("body failed")++ claimed.close.assert_awaited_once()+ pool.delete.assert_awaited_once()diff --git a/libs/python/cua-sandbox/tests/test_vm_cleanup.py b/libs/python/cua-sandbox/tests/test_vm_cleanup.pyindex 710aa58250..d42cd468ea 100644--- a/libs/python/cua-sandbox/tests/test_vm_cleanup.py+++ b/libs/python/cua-sandbox/tests/test_vm_cleanup.py@@ -59,6 +59,10 @@ def _make_sandbox(transport: FleetCloudTransport, **kwargs) -> Sandbox:class TestCreateCleansUpOnConnectFailure:"""Sandbox._create() should delete the cloud VM when _connect() raises."""+ @pytest.fixture(autouse=True)+ def _select_fleet(self, monkeypatch):+ monkeypatch.setattr(Sandbox, "_uses_fleet", staticmethod(lambda api_key: True))+async def test_delete_vm_called_on_timeout(self):"""ReadTimeout during _connect() triggers delete_vm()."""transport = _make_cloud_transport(name="orphan-vm")@@ -72,7 +76,6 @@ class TestCreateCleansUpOnConnectFailure:with pytest.raises(httpx.ReadTimeout):await Sandbox._create(image=Image.from_registry("registry.example/workspace:latest"),- api_key="sk-fake",telemetry_enabled=False,)@@ -91,7 +94,6 @@ class TestCreateCleansUpOnConnectFailure:with pytest.raises(RuntimeError, match="unexpected"):await Sandbox._create(image=Image.from_registry("registry.example/workspace:latest"),- api_key="sk-fake",telemetry_enabled=False,)@@ -110,7 +112,6 @@ class TestCreateCleansUpOnConnectFailure:with pytest.raises(TimeoutError, match="poll timeout"):await Sandbox._create(image=Image.from_registry("registry.example/workspace:latest"),- api_key="sk-fake",telemetry_enabled=False,)@@ -131,7 +132,6 @@ class TestCreateCleansUpOnConnectFailure:with pytest.raises(ValueError, match="no api key"):await Sandbox._create(image=Image.from_registry("registry.example/workspace:latest"),- api_key="sk-fake",telemetry_enabled=False,)@@ -150,7 +150,6 @@ class TestCreateCleansUpOnConnectFailure:with pytest.raises(KeyboardInterrupt):await Sandbox._create(image=Image.from_registry("registry.example/workspace:latest"),- api_key="sk-fake",telemetry_enabled=False,)@@ -250,34 +249,51 @@ class TestDestroyResilience:class TestFleetServerPortForwarding:"""Sandbox factories should pass server_port to Fleet and validate it early."""+ @pytest.fixture(autouse=True)+ def _select_fleet(self, monkeypatch):+ monkeypatch.setattr(Sandbox, "_uses_fleet", staticmethod(lambda api_key: api_key is None))+@pytest.mark.parametrize("server_port", [1, 65535])async def test_create_forwards_server_port(self, server_port):- sandbox = object()- with patch.object(Sandbox, "_create", AsyncMock(return_value=sandbox)) as create:+ claimed = object()+ pool = MagicMock()+ pool.claim = AsyncMock(return_value=claimed)+ apply = AsyncMock(return_value=pool)++ with patch("cua_sandbox.pool.Pool.apply", new=apply):result = await Sandbox.create(Image.from_registry("registry.example/workspace:latest"),server_port=server_port,telemetry_enabled=False,)- assert result is sandbox- assert create.await_args.kwargs["server_port"] == server_port+ assert result is claimed+ assert apply.await_args.kwargs["services"] == {"server": server_port}async def test_create_forwards_default_server_port(self):- sandbox = object()- with patch.object(Sandbox, "_create", AsyncMock(return_value=sandbox)) as create:+ claimed = object()+ pool = MagicMock()+ pool.claim = AsyncMock(return_value=claimed)+ apply = AsyncMock(return_value=pool)++ with patch("cua_sandbox.pool.Pool.apply", new=apply):result = await Sandbox.create(Image.from_registry("registry.example/workspace:latest"),telemetry_enabled=False,)- assert result is sandbox- assert create.await_args.kwargs["server_port"] == 8000+ assert result is claimed+ assert apply.await_args.kwargs["services"] == {"server": 8000}async def test_ephemeral_forwards_server_port(self):- sandbox = _make_sandbox(_make_cloud_transport(name="port-e2e"), ephemeral=True)- sandbox.destroy = AsyncMock()- with patch.object(Sandbox, "_create", AsyncMock(return_value=sandbox)) as create:+ claimed = MagicMock()+ claimed.close = AsyncMock()+ pool = MagicMock()+ pool.claim = AsyncMock(return_value=claimed)+ pool.delete = AsyncMock()+ apply = AsyncMock(return_value=pool)++ with patch("cua_sandbox.pool.Pool.apply", new=apply):async with Sandbox.ephemeral(Image.from_registry("registry.example/workspace:latest"),server_port=5000,@@ -285,7 +301,9 @@ class TestFleetServerPortForwarding:):pass- assert create.await_args.kwargs["server_port"] == 5000+ assert apply.await_args.kwargs["services"] == {"server": 5000}+ claimed.close.assert_awaited_once()+ pool.delete.assert_awaited_once()async def test_create_passes_server_port_to_fleet_transport(self):transport = _make_cloud_transport(name="port-fleet")@@ -377,89 +395,58 @@ class TestFleetServerPortForwarding:class TestEphemeralCleanup:- """Sandbox.ephemeral() should destroy the VM on normal and error exits."""+ """Sandbox.ephemeral() closes Fleet claims on every exit path."""++ @pytest.fixture(autouse=True)+ def _select_fleet(self, monkeypatch):+ monkeypatch.setattr(Sandbox, "_uses_fleet", staticmethod(lambda api_key: api_key is None))async def test_ephemeral_destroys_on_normal_exit(self):- """VM is destroyed when the async-with block exits normally."""- transport = _make_cloud_transport(name="eph-ok")- transport.connect = AsyncMock()- transport.disconnect = AsyncMock()- transport.delete_vm = AsyncMock()+ claimed = MagicMock()+ claimed.close = AsyncMock()+ pool = MagicMock()+ pool.claim = AsyncMock(return_value=claimed)+ pool.delete = AsyncMock()- with (- patch.object(- FleetCloudTransport,- "__init__",- lambda self, **kw: None,- ),- patch.object(- FleetCloudTransport,- "__new__",- lambda cls, **kw: transport,- ),- ):+ with patch("cua_sandbox.pool.Pool.apply", new=AsyncMock(return_value=pool)):async with Sandbox.ephemeral(Image.from_registry("registry.example/workspace:latest"),- api_key="sk-fake",telemetry_enabled=False,- ) as sb:- assert sb.name == "eph-ok"+ ):+ pass- transport.delete_vm.assert_awaited_once()+ claimed.close.assert_awaited_once()+ pool.delete.assert_awaited_once()async def test_ephemeral_destroys_on_test_failure(self):- """VM is destroyed even when the body raises an assertion error."""- transport = _make_cloud_transport(name="eph-fail")- transport.connect = AsyncMock()- transport.disconnect = AsyncMock()- transport.delete_vm = AsyncMock()+ claimed = MagicMock()+ claimed.close = AsyncMock()+ pool = MagicMock()+ pool.claim = AsyncMock(return_value=claimed)+ pool.delete = AsyncMock()- with (- patch.object(- FleetCloudTransport,- "__init__",- lambda self, **kw: None,- ),- patch.object(- FleetCloudTransport,- "__new__",- lambda cls, **kw: transport,- ),- ):+ with patch("cua_sandbox.pool.Pool.apply", new=AsyncMock(return_value=pool)):with pytest.raises(AssertionError):async with Sandbox.ephemeral(Image.from_registry("registry.example/workspace:latest"),- api_key="sk-fake",telemetry_enabled=False,- ) as _sb:+ ):raise AssertionError("test failed")- transport.delete_vm.assert_awaited_once()+ claimed.close.assert_awaited_once()+ pool.delete.assert_awaited_once()- async def test_ephemeral_cleans_up_when_create_connect_fails(self):- """If _create raises after VM provisioning, the VM is still cleaned up."""- transport = _make_cloud_transport(name="eph-connect-fail")- transport.connect = AsyncMock(side_effect=httpx.ReadTimeout("poll timed out"))- transport.delete_vm = AsyncMock()+ async def test_ephemeral_propagates_claim_failure(self):+ pool = MagicMock()+ pool.claim = AsyncMock(side_effect=httpx.ReadTimeout("poll timed out"))+ pool.delete = AsyncMock()- with (- patch.object(- FleetCloudTransport,- "__init__",- lambda self, **kw: None,- ),- patch.object(- FleetCloudTransport,- "__new__",- lambda cls, **kw: transport,- ),- ):+ with patch("cua_sandbox.pool.Pool.apply", new=AsyncMock(return_value=pool)):with pytest.raises(httpx.ReadTimeout):async with Sandbox.ephemeral(Image.from_registry("registry.example/workspace:latest"),- api_key="sk-fake",telemetry_enabled=False,- ) as _sb:- pass # never reached+ ):+ pass- transport.delete_vm.assert_awaited_once()+ pool.delete.assert_awaited_once()