Skip to content

armgit / cua

Public Imported from GitHub
0

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

feat(cua-sandbox): expose creation TTL for pools and claims (0.4.2) (#3256)

r33drichardsd5037005b90c
diff --git a/docs/content/docs/how-to-guides/sandbox/create-pool-with-python.mdx b/docs/content/docs/how-to-guides/sandbox/create-pool-with-python.mdx
index 667cae1340..75e7f746b1 100644
--- a/docs/content/docs/how-to-guides/sandbox/create-pool-with-python.mdx
+++ b/docs/content/docs/how-to-guides/sandbox/create-pool-with-python.mdx
@@ -141,6 +141,57 @@ Each field is optional (pass `None` to accept the server default). With
`min_pool_size=0` the pool scales to zero when no claims are held, so the
first claim after an idle period cold-starts a sandbox.
+## Expire pools and claims automatically
+
+Pools and claims accept an optional creation-age TTL. Pass
+`ttl_seconds_after_created=` (requires `cua-sandbox>=0.4.2`) and the resource
+is deleted once it has existed that many seconds, whether or not it is in use:
+
+```python
+# Delete the whole pool 24 hours after it was first created.
+pool = await Pool.apply(
+ Image.from_registry(IMAGE),
+ name=POOL_NAME,
+ replicas=1,
+ ttl_seconds_after_created=86400,
+)
+
+# Delete this claim and its sandbox one hour after the claim was created.
+async with pool.claim(
+ name=CLAIM_NAME,
+ ttl_seconds_after_created=3600,
+) as sandbox:
+ ...
+```
+
+The clock starts at the resource's original creation, not its last use:
+re-running `Pool.apply()` reconciles the existing pool without resetting its
+age, and reconnecting to a named claim keeps the deadline set when the claim
+was first created. Without the argument nothing is reaped — pools and claims
+live until you delete them.
+
+A claim TTL fills in the claim's lifecycle shutdown time with a `Delete`
+policy; a claim that already carries an explicit lifecycle keeps it. When you
+build a claim spec by hand, put the TTL inside it — passing both
+`spec=` and `ttl_seconds_after_created=` raises `ValueError`:
+
+```python
+spec = ClaimSpec(
+ sandbox_template_ref=pool.resource.spec.sandbox_template_ref,
+ warmpool=None,
+ bind_deadline=None,
+ lifecycle=None,
+ ttl_seconds_after_created=3600,
+)
+async with pool.claim(spec=spec) as sandbox:
+ ...
+```
+
+Treat a pool TTL that can expire while claims are held as a capacity event,
+not just cleanup: deleting the pool drains its sandboxes, and a claim that
+outlives its pool destroys its sandbox on release instead of returning it to
+the pool.
+
## Choose pool and claim names
The defaults use the same value for the pool and claim. Override either name
diff --git a/libs/python/cua-sandbox/cua_sandbox/pool.py b/libs/python/cua-sandbox/cua_sandbox/pool.py
index e8e9e55951..849366659f 100644
--- a/libs/python/cua-sandbox/cua_sandbox/pool.py
+++ b/libs/python/cua-sandbox/cua_sandbox/pool.py
@@ -14,6 +14,7 @@ from cua_sandbox.transport.fleet_cloud import (
_canonicalize_pool_access_denied,
_FleetClient,
_pool_access_denied,
+ validate_ttl_seconds_after_created,
)
from fleet_sdk import (
Claim,
@@ -255,6 +256,7 @@ class Pool:
memory_mb: int | None = None,
services: dict[str, int] | None = None,
autoscaling: WarmPoolAutoscaling | None = None,
+ ttl_seconds_after_created: int | None = None,
) -> "Pool":
if not isinstance(name, str) or not name:
raise ValueError(
@@ -274,6 +276,7 @@ class Pool:
memory_mb=memory_mb,
services=effective_services,
autoscaling=autoscaling,
+ ttl_seconds_after_created=ttl_seconds_after_created,
)
pool = await cls.reconcile(transport._pool_request())
try:
@@ -300,9 +303,32 @@ class Pool:
finally:
await client.close()
+ def _claim_spec(
+ self, spec: ClaimSpec | None, ttl_seconds_after_created: int | None
+ ) -> ClaimSpec | None:
+ if ttl_seconds_after_created is None:
+ return spec
+ if spec is not None:
+ raise ValueError(
+ "pass ttl_seconds_after_created inside spec when supplying an explicit ClaimSpec"
+ )
+ validate_ttl_seconds_after_created(ttl_seconds_after_created)
+ return ClaimSpec(
+ sandbox_template_ref=self._resource.spec.sandbox_template_ref,
+ warmpool=None,
+ bind_deadline=None,
+ lifecycle=None,
+ ttl_seconds_after_created=ttl_seconds_after_created,
+ )
+
async def create_claim(
- self, *, spec: ClaimSpec | None = None, name: str | None = None
+ self,
+ *,
+ spec: ClaimSpec | None = None,
+ name: str | None = None,
+ ttl_seconds_after_created: int | None = None,
) -> _ClaimHandle:
+ spec = self._claim_spec(spec, ttl_seconds_after_created)
request = CreateClaimRequest(pool=self._resource, spec=spec, name=name)
client = _FleetClient()
try:
@@ -322,7 +348,10 @@ class Pool:
name: str | None = None,
service: str = "server",
time_to_start: float | None = None,
+ ttl_seconds_after_created: int | None = None,
) -> _ClaimResult[Sandbox]:
+ spec = self._claim_spec(spec, ttl_seconds_after_created)
+
async def acquire() -> Sandbox:
client = _FleetClient()
claim: Any = None
diff --git a/libs/python/cua-sandbox/cua_sandbox/sync/__init__.py b/libs/python/cua-sandbox/cua_sandbox/sync/__init__.py
index d797d028c5..3a0da5c36d 100644
--- a/libs/python/cua-sandbox/cua_sandbox/sync/__init__.py
+++ b/libs/python/cua-sandbox/cua_sandbox/sync/__init__.py
@@ -132,6 +132,7 @@ class Pool:
memory_mb: int | None = None,
services: dict[str, int] | None = None,
autoscaling: WarmPoolAutoscaling | None = None,
+ ttl_seconds_after_created: int | None = None,
) -> "Pool":
"""Synchronously apply an image-backed Fleet pool."""
return cls(
@@ -144,6 +145,7 @@ class Pool:
memory_mb=memory_mb,
services=services,
autoscaling=autoscaling,
+ ttl_seconds_after_created=ttl_seconds_after_created,
)
)
)
@@ -160,10 +162,15 @@ class Pool:
name: str | None = None,
service: str = "server",
time_to_start: float | None = None,
+ ttl_seconds_after_created: int | 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
+ spec=spec,
+ name=name,
+ service=service,
+ time_to_start=time_to_start,
+ ttl_seconds_after_created=ttl_seconds_after_created,
)
sandbox = _run(context.__aenter__())
try:
diff --git a/libs/python/cua-sandbox/cua_sandbox/transport/fleet_cloud.py b/libs/python/cua-sandbox/cua_sandbox/transport/fleet_cloud.py
index 0389ce11cd..d8504393b3 100644
--- a/libs/python/cua-sandbox/cua_sandbox/transport/fleet_cloud.py
+++ b/libs/python/cua-sandbox/cua_sandbox/transport/fleet_cloud.py
@@ -406,6 +406,18 @@ def _needs_ecr_pull_secret(image: "str | None") -> bool:
return _ECR_HOST_MARKER in host and host.endswith(_ECR_HOST_SUFFIX)
+_TTL_SECONDS_MAX = 2**32 - 1
+
+
+def validate_ttl_seconds_after_created(value: "int | None") -> None:
+ if value is not None and (
+ isinstance(value, bool) or not isinstance(value, int) or not 0 <= value <= _TTL_SECONDS_MAX
+ ):
+ raise ValueError(
+ f"ttl_seconds_after_created must be an integer between 0 and {_TTL_SECONDS_MAX}"
+ )
+
+
class FleetCloudTransport(FleetTransport):
"""Provision image-backed pools or claim pre-created pools through Fleet."""
@@ -426,6 +438,7 @@ class FleetCloudTransport(FleetTransport):
replicas: int = 1,
services: Mapping[str, int] | None = None,
autoscaling: Optional[WarmPoolAutoscaling] = None,
+ ttl_seconds_after_created: Optional[int] = None,
) -> None:
if (
isinstance(server_port, bool)
@@ -474,6 +487,7 @@ class FleetCloudTransport(FleetTransport):
raise ValueError(
"autoscaling.min_pool_size must not exceed autoscaling.max_pool_size"
)
+ validate_ttl_seconds_after_created(ttl_seconds_after_created)
self._image = image
self._name = name
self._explicit_pool = pool_name is not None
@@ -488,6 +502,7 @@ class FleetCloudTransport(FleetTransport):
self._replicas = replicas
self._services = dict(services) if services is not None else None
self._autoscaling = autoscaling
+ self._ttl_seconds_after_created = ttl_seconds_after_created
self._provisioned = False
self._owns_resources = image is not None or create_claim
self._template: Any = None
@@ -724,6 +739,10 @@ class FleetCloudTransport(FleetTransport):
)
if self._autoscaling is not None:
pool_spec_builder = pool_spec_builder.autoscaling(self._autoscaling)
+ if self._ttl_seconds_after_created is not None:
+ pool_spec_builder = pool_spec_builder.ttl_seconds_after_created(
+ self._ttl_seconds_after_created
+ )
return (
CreatePoolRequestBuilder()
.namespace(self._pool_name)
diff --git a/libs/python/cua-sandbox/pyproject.toml b/libs/python/cua-sandbox/pyproject.toml
index 513ea75863..c568e1d353 100644
--- a/libs/python/cua-sandbox/pyproject.toml
+++ b/libs/python/cua-sandbox/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "cua-sandbox"
-version = "0.4.1"
+version = "0.4.2"
description = "CUA Sandbox — ephemeral and persistent sandboxed computer environments"
readme = "README.md"
license = "MIT"
@@ -29,7 +29,7 @@ requires-python = ">=3.11,<3.14"
dependencies = [
"cua-core>=0.3.0,<0.4.0",
"cua-auto>=0.1.2",
- "cua-fleet==0.1.12",
+ "cua-fleet==0.1.14",
"websockets>=12.0",
"httpx>=0.27.0",
"oras>=0.2.40",
diff --git a/libs/python/cua-sandbox/tests/test_fleet_cloud_transport.py b/libs/python/cua-sandbox/tests/test_fleet_cloud_transport.py
index beaa05626e..45191cf318 100644
--- a/libs/python/cua-sandbox/tests/test_fleet_cloud_transport.py
+++ b/libs/python/cua-sandbox/tests/test_fleet_cloud_transport.py
@@ -139,6 +139,35 @@ def test_pool_request_accepts_partial_autoscaling_bounds():
assert request.spec.autoscaling == autoscaling
+def test_pool_request_carries_the_requested_creation_ttl():
+ request = FleetCloudTransport(
+ image=Image.from_registry("registry.example/workspace@sha256:abc"),
+ name="demo",
+ ttl_seconds_after_created=3600,
+ )._pool_request()
+
+ assert request.spec.ttl_seconds_after_created == 3600
+
+
+def test_pool_request_leaves_creation_ttl_unset_by_default():
+ request = FleetCloudTransport(
+ image=Image.from_registry("registry.example/workspace@sha256:abc"),
+ name="demo",
+ )._pool_request()
+
+ assert request.spec.ttl_seconds_after_created is None
+
+
[email protected]("ttl", [-1, True, "3600", 1.5, 2**32])
+def test_transport_rejects_invalid_creation_ttl(ttl):
+ with pytest.raises(ValueError, match="ttl_seconds_after_created"):
+ FleetCloudTransport(
+ image=Image.from_registry("registry.example/workspace@sha256:abc"),
+ name="demo",
+ ttl_seconds_after_created=ttl,
+ )
+
+
def test_transport_rejects_untyped_autoscaling():
with pytest.raises(TypeError, match="WarmPoolAutoscaling"):
FleetCloudTransport(
diff --git a/libs/python/cua-sandbox/tests/test_fleet_sdk_distribution.py b/libs/python/cua-sandbox/tests/test_fleet_sdk_distribution.py
index 12925d1cd8..313dce7042 100644
--- a/libs/python/cua-sandbox/tests/test_fleet_sdk_distribution.py
+++ b/libs/python/cua-sandbox/tests/test_fleet_sdk_distribution.py
@@ -10,6 +10,6 @@ def test_fleet_sdk_is_provided_by_published_fleet_distribution():
distribution_root = Path(cua_fleet_distribution.locate_file(".")).resolve()
binding_path = Path(fleet_sdk.__file__).resolve()
- assert cua_fleet_distribution.version == "0.1.11"
+ assert cua_fleet_distribution.version == "0.1.14"
assert "fleet_sdk/__init__.py" in installed_files
assert binding_path.is_relative_to(distribution_root)
diff --git a/libs/python/cua-sandbox/tests/test_fleet_sdk_packaging.py b/libs/python/cua-sandbox/tests/test_fleet_sdk_packaging.py
index 0f6fcdd7fb..76c2a43239 100644
--- a/libs/python/cua-sandbox/tests/test_fleet_sdk_packaging.py
+++ b/libs/python/cua-sandbox/tests/test_fleet_sdk_packaging.py
@@ -18,7 +18,7 @@ class FleetSdkPackagingTests(unittest.TestCase):
project = tomllib.load(pyproject_file)
dependencies = project["project"]["dependencies"]
- self.assertIn("cua-fleet==0.1.11", dependencies)
+ self.assertIn("cua-fleet==0.1.14", dependencies)
self.assertFalse(any(dependency.startswith("cua-train") for dependency in dependencies))
self.assertNotIn("cua-fleet", project["tool"]["uv"]["sources"])
self.assertNotIn("cua-train", project["tool"]["uv"]["sources"])
@@ -49,7 +49,7 @@ class FleetSdkPackagingTests(unittest.TestCase):
self.assertNotIn("cua-train", sandbox_dependencies)
self.assertIn("cua-fleet", sandbox_requires_dist)
self.assertNotIn("cua-train", sandbox_requires_dist)
- self.assertEqual(packages["cua-fleet"]["version"], "0.1.11")
+ self.assertEqual(packages["cua-fleet"]["version"], "0.1.14")
self.assertEqual(
packages["cua-fleet"]["source"], {"registry": "https://wheels.cua.ai/simple"}
)
diff --git a/libs/python/cua-sandbox/tests/test_pool.py b/libs/python/cua-sandbox/tests/test_pool.py
index 637f5dc2f1..deebefb6b3 100644
--- a/libs/python/cua-sandbox/tests/test_pool.py
+++ b/libs/python/cua-sandbox/tests/test_pool.py
@@ -626,6 +626,51 @@ async def test_create_claim_returns_a_serializable_lease(monkeypatch):
assert _ClaimHandle.from_dict(lease.to_dict()).to_dict() == lease.to_dict()
+async def test_create_claim_forwards_creation_ttl_in_a_derived_spec(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())
+
+ await pool.create_claim(ttl_seconds_after_created=1800)
+
+ spec = claim_client.claims[0].spec
+ assert spec.ttl_seconds_after_created == 1800
+ assert spec.sandbox_template_ref is pool.resource.spec.sandbox_template_ref
+ assert spec.warmpool is None
+ assert spec.bind_deadline is None
+ assert spec.lifecycle is None
+
+
+async def test_create_claim_rejects_ttl_alongside_an_explicit_spec(monkeypatch):
+ reconcile_client = FakeFleetClient()
+ clients = iter([reconcile_client, FakeFleetClient()])
+ monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: next(clients))
+ pool = await Pool.reconcile(pool_request())
+
+ with pytest.raises(ValueError, match="inside spec"):
+ await pool.create_claim(spec=SimpleNamespace(), ttl_seconds_after_created=1800)
+
+
+async def test_pool_claim_forwards_creation_ttl_in_a_derived_spec(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())
+
+ async with pool.claim(ttl_seconds_after_created=900):
+ pass
+
+ spec = claim_client.claims[0].spec
+ assert spec.ttl_seconds_after_created == 900
+ assert spec.sandbox_template_ref is pool.resource.spec.sandbox_template_ref
+
+
@pytest.mark.asyncio
async def test_lease_wait_connects_to_the_named_service_and_caches_the_bind(monkeypatch):
client = FakeFleetClient()
@@ -946,6 +991,47 @@ def test_sync_pool_apply_forwards_autoscaling(monkeypatch):
assert clients[0].reconciled[0].spec.autoscaling == autoscaling
+async def test_pool_apply_forwards_creation_ttl_to_the_pool_request(monkeypatch):
+ clients = [FakeFleetClient() for _ in range(2)]
+ iterator = iter(clients)
+ monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: next(iterator))
+
+ await Pool.apply(
+ Image.from_registry("registry.example/workspace:latest"),
+ name="workspace",
+ ttl_seconds_after_created=86400,
+ )
+
+ assert clients[0].reconciled[0].spec.ttl_seconds_after_created == 86400
+
+
+async def test_pool_apply_without_creation_ttl_leaves_the_pool_unreaped(monkeypatch):
+ clients = [FakeFleetClient() for _ in range(2)]
+ iterator = iter(clients)
+ monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: next(iterator))
+
+ await Pool.apply(
+ Image.from_registry("registry.example/workspace:latest"),
+ name="workspace",
+ )
+
+ assert clients[0].reconciled[0].spec.ttl_seconds_after_created is None
+
+
+async def test_pool_apply_rejects_invalid_creation_ttl(monkeypatch):
+ monkeypatch.setattr("cua_sandbox.pool._FleetClient", FakeFleetClient)
+
+ with pytest.raises(ValueError, match="ttl_seconds_after_created"):
+ await Pool.apply(
+ Image.from_registry("registry.example/workspace:latest"),
+ name="workspace",
+ ttl_seconds_after_created=-1,
+ )
+
+
def _forbidden(operation: str) -> SdkError.Status:
return SdkError.Status(operation=operation, status=403, body="k8s request is not allowed")
diff --git a/libs/python/cua-sandbox/uv.lock b/libs/python/cua-sandbox/uv.lock
index 979e38095f..1daa96aebc 100644
--- a/libs/python/cua-sandbox/uv.lock
+++ b/libs/python/cua-sandbox/uv.lock
@@ -528,19 +528,19 @@ dev = [{ name = "pytest", specifier = ">=8.3.5" }]
[[package]]
name = "cua-fleet"
-version = "0.1.12"
+version = "0.1.14"
source = { registry = "https://wheels.cua.ai/simple" }
wheels = [
- { url = "https://wheels.cua.ai/simple/cua-fleet/cua_fleet-0.1.12-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:d5114ba97ef208e257bef261f6d3585b265f1f2c32cb627bcc9f44d753e60b75" },
- { url = "https://wheels.cua.ai/simple/cua-fleet/cua_fleet-0.1.12-py3-none-macosx_11_0_arm64.whl", hash = "sha256:82762fae4943b20aae05b39362f5bd0c179f84c16dac1e948debb3d58db5adc2" },
- { url = "https://wheels.cua.ai/simple/cua-fleet/cua_fleet-0.1.12-py3-none-manylinux_2_34_aarch64.whl", hash = "sha256:0a39e52cbec94a2bc71f45282dd34c896fd154bc7f7a137fc6ceff82edfc0973" },
- { url = "https://wheels.cua.ai/simple/cua-fleet/cua_fleet-0.1.12-py3-none-manylinux_2_34_x86_64.whl", hash = "sha256:d8ef6a0c8ac6e6f8dda937e3aebeef7f5b4fa9e3f29edc55a602a1c874f3f96a" },
- { url = "https://wheels.cua.ai/simple/cua-fleet/cua_fleet-0.1.12-py3-none-win_amd64.whl", hash = "sha256:c280d7ceadedc1d5c4c59869940c3390aac321f12ac9c9ee52250f212b6aac75" },
+ { url = "https://wheels.cua.ai/simple/cua-fleet/cua_fleet-0.1.14-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:d370f83773574da8edcca080e9d86aec8eb7ed758d6c551b900482a8575f6810" },
+ { url = "https://wheels.cua.ai/simple/cua-fleet/cua_fleet-0.1.14-py3-none-macosx_11_0_arm64.whl", hash = "sha256:e19784c0ce8aa2d9a77bf096fc6ff10e990842f05c67bdfb96a16ecd5e7123e2" },
+ { url = "https://wheels.cua.ai/simple/cua-fleet/cua_fleet-0.1.14-py3-none-manylinux_2_34_aarch64.whl", hash = "sha256:d6ea25902cf9ffc89779530b6ae7cff5413383ea7dc3c632a4fb47e00699a6d4" },
+ { url = "https://wheels.cua.ai/simple/cua-fleet/cua_fleet-0.1.14-py3-none-manylinux_2_34_x86_64.whl", hash = "sha256:2dc70e98b3e8c691bf0fff0494b0a85d2405e872f1ca99dbfa2680473cea565b" },
+ { url = "https://wheels.cua.ai/simple/cua-fleet/cua_fleet-0.1.14-py3-none-win_amd64.whl", hash = "sha256:3e73327b7c99dc95a4b4194628d3575a8707cab77d6929ed1bf34a82192a4464" },
]
[[package]]
name = "cua-sandbox"
-version = "0.4.1"
+version = "0.4.2"
source = { editable = "." }
dependencies = [
{ name = "cua-auto" },
@@ -577,7 +577,7 @@ dev = [
requires-dist = [
{ name = "cua-auto", specifier = ">=0.1.2" },
{ name = "cua-core", specifier = ">=0.3.0,<0.4.0" },
- { name = "cua-fleet", specifier = "==0.1.12" },
+ { name = "cua-fleet", specifier = "==0.1.14" },
{ name = "grpcio", specifier = "==1.78.0" },
{ name = "httpx", specifier = ">=0.27.0" },
{ name = "oras", specifier = ">=0.2.40" },
@@ -620,7 +620,7 @@ name = "ewmhlib"
version = "0.2"
source = { registry = "https://pypi.org/simple" }
dependencies = [
- { name = "python-xlib", marker = "sys_platform == 'linux'" },
+ { name = "python-xlib" },
{ name = "typing-extensions" },
]
wheels = [