Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ on:
jobs:
checks:
if: github.event.pull_request.draft == false
runs-on: ubuntu-latest
# setup-python has no Python 3.9 for Ubuntu 26.04 (ubuntu-latest).
runs-on: ubuntu-24.04

strategy:
matrix:
Expand Down
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,17 @@
# Changelog

## 0.4.0 (2026-12-02)

- New: `Sandbox.create()` / `acreate()` take `image` again, now that the
server accepts one: any public image from Docker Hub, `ghcr.io`, `quay.io`,
`gcr.io`, `public.ecr.aws`, `mcr.microsoft.com` or `nvcr.io` that has
`/bin/sh`. The server pins it to its linux/amd64 digest, which
`Sandbox.image` reports. With an image, `create()`, `start()` and
`wait_until_running()` wait up to 600 s by default instead of 300 s.
- New: `Sandbox.fail_reason`. `SandboxFailedError` carries it as
`.fail_reason` and in its message, so a custom image that cannot start says
why.

## 0.3.0 (2026-08-12)

- Breaking: `Sandbox.create()` / `acreate()` no longer take `image`. The server
Expand Down
23 changes: 21 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,28 @@ sb.terminate() # deletes the sandbox (stays fetchable by id as "deleted" brief
```

`/workspace` is the only location `fs` accepts, and the only one that survives
`stop()`/`start()` — the rest of the filesystem comes back from the base image, so
`stop()`/`start()` — the rest of the filesystem comes back from the sandbox's image, so
packages installed at runtime are gone after a restart. Sandboxes also auto-stop
once idle for `timeout` (1 hour by default), which has the same effect.

### Custom images

Boot from a public container image instead of the default one:

```python
sb = Sandbox.create(image="python:3.12-slim")
print(sb.image) # docker.io/library/python:3.12-slim@sha256:...
```

The image comes from Docker Hub, `ghcr.io`, `quay.io`, `gcr.io`,
`public.ecr.aws`, `mcr.microsoft.com` or `nvcr.io`. It needs `/bin/sh`
(busybox is enough) and may be at most 4 GiB compressed and 20 GB unpacked.
It is pinned to its linux/amd64 digest at create, so `start()` later runs the
same image. Commands run as root, and the image's `ENTRYPOINT` and `CMD` are
not run. A first pull can take minutes, so with an image `create()` waits up
to 600 s by default. An image that cannot start leaves the sandbox `failed`,
and `SandboxFailedError.fail_reason` (or `sb.fail_reason`) says why.

Every network method has an async twin prefixed with `a`:

```python
Expand Down Expand Up @@ -88,7 +106,8 @@ Errors are typed: `AuthenticationError` (401), `NotFoundError` (404),
an alias), `CapacityError` (503), plus SDK-side `SandboxTimeoutError` /
`SandboxFailedError` / `CommandFailedError`. If `Sandbox.create(wait=True)`
fails while waiting, the raised error carries `.sandbox_id` so you can
inspect or terminate the sandbox it created.
inspect or terminate the sandbox it created; `SandboxFailedError` also
carries the server's `.fail_reason`.

Roadmap (API designed, lands in an upcoming release): `exec_stream` (live
output), `snapshot()` / `Sandbox.from_snapshot()`, `expose_port()`,
Expand Down
13 changes: 12 additions & 1 deletion deepinfra/_exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,18 @@ class SandboxTimeoutError(SandboxWaitError):


class SandboxFailedError(SandboxWaitError):
"""The sandbox entered a terminal failed/deleted state."""
"""The sandbox entered a terminal failed/deleted state.

``fail_reason`` is the server's reason, e.g. why a custom image did not start.
"""

fail_reason: str

def __init__(
self, message: str, *, sandbox_id: str | None = None, fail_reason: str = ""
) -> None:
super().__init__(message, sandbox_id=sandbox_id)
self.fail_reason = fail_reason


class SandboxExecError(SandboxError):
Expand Down
1 change: 1 addition & 0 deletions deepinfra/_sandbox_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ class SandboxInfo(pydantic.BaseModel):
tags: dict[str, str] = pydantic.Field(default_factory=dict)
created_at: int = 0
provider: str = ""
fail_reason: str = ""

model_config = pydantic.ConfigDict(extra="ignore")

Expand Down
2 changes: 1 addition & 1 deletion deepinfra/_version.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = "0.3.0"
__version__ = "0.4.0"
94 changes: 60 additions & 34 deletions deepinfra/sandbox_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@

Only paths under /workspace are readable/writable through fs, and /workspace is
the only directory that survives stop/start -- everything else reverts to the
base image.
sandbox's image. Pass image="python:3.12-slim" (any public image with /bin/sh)
to boot from your own image instead of the default one.

Every network method has an async twin prefixed with "a" (exec/aexec,
create/acreate, ...).
Expand All @@ -36,6 +37,8 @@

_SANDBOXES = "/v1/sandboxes"
_DEFAULT_WAIT_TIMEOUT = 300.0
# The server gives a custom image's first pull up to 480 s.
_IMAGE_WAIT_TIMEOUT = 600.0
_DEFAULT_EXEC_TIMEOUT = 60
_EXEC_HTTP_GRACE = 30.0

Expand Down Expand Up @@ -89,6 +92,11 @@ def created_at(self) -> int:
def provider(self) -> str:
return self._info.provider

@property
def fail_reason(self) -> str:
"""Why the sandbox failed; empty unless its state is "failed"."""
return self._info.fail_reason

def __repr__(self) -> str:
return f"Sandbox(id={self.id!r}, state={self.state!r}, plan={self.plan!r})"

Expand All @@ -99,18 +107,24 @@ def create(
cls,
*,
plan: str = "",
image: str = "",
timeout: Duration | None = None,
tags: Mapping[str, str] | None = None,
wait: bool = True,
wait_timeout: float = _DEFAULT_WAIT_TIMEOUT,
wait_timeout: float | None = None,
client: DeepInfraClient | None = None,
) -> Sandbox:
"""Create a sandbox; by default block until it is running."""
"""Create a sandbox; by default block until it is running.

``image`` boots a public container image instead of the default one.
``wait_timeout`` defaults to 300 s, or 600 s with an image, whose first
pull can take minutes.
"""
client = client or default_client()
reply = client.request(cls._create_spec(plan, timeout, tags)).json()
reply = client.request(cls._create_spec(plan, image, timeout, tags)).json()
sandbox = cls(SandboxInfo(sandbox_id=reply["sandbox_id"]), client=client)
if wait:
sandbox.wait_until_running(timeout=wait_timeout)
sandbox.wait_until_running(timeout=_wait_timeout(wait_timeout, image))
else:
sandbox.refresh()
return sandbox
Expand All @@ -120,17 +134,20 @@ async def acreate(
cls,
*,
plan: str = "",
image: str = "",
timeout: Duration | None = None,
tags: Mapping[str, str] | None = None,
wait: bool = True,
wait_timeout: float = _DEFAULT_WAIT_TIMEOUT,
wait_timeout: float | None = None,
client: DeepInfraClient | None = None,
) -> Sandbox:
client = client or default_client()
reply = (await client.arequest(cls._create_spec(plan, timeout, tags))).json()
reply = (
await client.arequest(cls._create_spec(plan, image, timeout, tags))
).json()
sandbox = cls(SandboxInfo(sandbox_id=reply["sandbox_id"]), client=client)
if wait:
await sandbox.await_until_running(timeout=wait_timeout)
await sandbox.await_until_running(timeout=_wait_timeout(wait_timeout, image))
else:
await sandbox.arefresh()
return sandbox
Expand Down Expand Up @@ -213,15 +230,14 @@ async def arefresh(self) -> Sandbox:
)
return self

def wait_until_running(self, timeout: float = _DEFAULT_WAIT_TIMEOUT) -> Sandbox:
def wait_until_running(self, timeout: float | None = None) -> Sandbox:
"""``timeout`` defaults to 300 s, or 600 s for a custom image."""
return self._wait_for_state(_RUNNING, timeout)

def wait_until_stopped(self, timeout: float = _DEFAULT_WAIT_TIMEOUT) -> Sandbox:
return self._wait_for_state(_STOPPED, timeout)

async def await_until_running(
self, timeout: float = _DEFAULT_WAIT_TIMEOUT
) -> Sandbox:
async def await_until_running(self, timeout: float | None = None) -> Sandbox:
return await self._await_for_state(_RUNNING, timeout)

async def await_until_stopped(
Expand All @@ -248,15 +264,14 @@ async def astop(
if wait:
await self.await_until_stopped(timeout=wait_timeout)

def start(
self, *, wait: bool = True, wait_timeout: float = _DEFAULT_WAIT_TIMEOUT
) -> None:
def start(self, *, wait: bool = True, wait_timeout: float | None = None) -> None:
"""Start a stopped sandbox; on another node a custom image is pulled again."""
self._client.request(_op_spec(self.id, "start"))
if wait:
self.wait_until_running(timeout=wait_timeout)

async def astart(
self, *, wait: bool = True, wait_timeout: float = _DEFAULT_WAIT_TIMEOUT
self, *, wait: bool = True, wait_timeout: float | None = None
) -> None:
await self._client.arequest(_op_spec(self.id, "start"))
if wait:
Expand Down Expand Up @@ -316,37 +331,42 @@ async def __aexit__(self, *exc_info: Any) -> None:

# -- internals --

def _wait_for_state(self, target: str, timeout: float) -> Sandbox:
deadline = time.monotonic() + timeout
def _wait_for_state(self, target: str, timeout: float | None) -> Sandbox:
started = time.monotonic()
for delay in backoff_delays():
self.refresh()
self._check_wait_state(target)
if self.state == target:
return self
if time.monotonic() + delay > deadline:
raise self._wait_timeout_error(target, timeout)
# Set after a refresh: a handle that has not loaded yet has no image.
limit = _wait_timeout(timeout, self.image)
if time.monotonic() + delay > started + limit:
raise self._wait_timeout_error(target, limit)
time.sleep(delay)
raise AssertionError("unreachable")

async def _await_for_state(self, target: str, timeout: float) -> Sandbox:
async def _await_for_state(self, target: str, timeout: float | None) -> Sandbox:
import asyncio

deadline = time.monotonic() + timeout
started = time.monotonic()
for delay in backoff_delays():
await self.arefresh()
self._check_wait_state(target)
if self.state == target:
return self
if time.monotonic() + delay > deadline:
raise self._wait_timeout_error(target, timeout)
limit = _wait_timeout(timeout, self.image)
if time.monotonic() + delay > started + limit:
raise self._wait_timeout_error(target, limit)
await asyncio.sleep(delay)
raise AssertionError("unreachable")

def _check_wait_state(self, target: str) -> None:
if self.state in _TERMINAL_STATES and self.state != target:
reason = f": {self.fail_reason}" if self.fail_reason else ""
raise SandboxFailedError(
f"Sandbox {self.id} entered state {self.state!r}",
f"Sandbox {self.id} entered state {self.state!r}{reason}",
sandbox_id=self.id,
fail_reason=self.fail_reason,
)

def _wait_timeout_error(self, target: str, timeout: float) -> SandboxTimeoutError:
Expand Down Expand Up @@ -375,18 +395,18 @@ def _exec_spec(
@staticmethod
def _create_spec(
plan: str,
image: str,
timeout: Duration | None,
tags: Mapping[str, str] | None,
) -> RequestSpec:
return RequestSpec(
"POST",
_SANDBOXES,
json={
"plan": plan,
"tags": dict(tags or {}),
"timeout_seconds": parse_duration(timeout) if timeout is not None else 0,
},
)
body: dict[str, Any] = {
"plan": plan,
"tags": dict(tags or {}),
"timeout_seconds": parse_duration(timeout) if timeout is not None else 0,
}
if image:
body["image"] = image
return RequestSpec("POST", _SANDBOXES, json=body)

@classmethod
def _from_list(
Expand Down Expand Up @@ -443,6 +463,12 @@ def _content_path(self) -> str:
return _id_path(self._sandbox.id, "fs", "content")


def _wait_timeout(wait_timeout: float | None, image: str) -> float:
if wait_timeout is not None:
return wait_timeout
return _IMAGE_WAIT_TIMEOUT if image else _DEFAULT_WAIT_TIMEOUT


def _id_path(sandbox_id: str, *suffix: str) -> str:
"""Build a /v1/sandboxes/{id}[/...] path with the id URL-quoted.

Expand Down
52 changes: 48 additions & 4 deletions tests/test_sandbox.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import json
from types import SimpleNamespace

import httpx
import pytest
Expand All @@ -8,8 +9,10 @@
NotFoundError,
Sandbox,
SandboxFailedError,
SandboxInfo,
SandboxTimeoutError,
TooManySandboxesError,
sandbox_api,
)

from .conftest import BASE_URL
Expand All @@ -26,6 +29,7 @@ def _info(state="running", **kw):
"tags": kw.get("tags", {}),
"created_at": 1,
"provider": "kata-qemu",
"fail_reason": kw.get("fail_reason", ""),
}


Expand Down Expand Up @@ -77,12 +81,52 @@ def test_from_id_empty_raises(client):


@respx.mock
def test_create_failed_state_raises(client):
@pytest.mark.parametrize("image, wait_timeout", [("", 300.0), ("python:3.12-slim", 600.0)])
def test_create_sends_an_image_only_when_given_and_waits_longer_for_one(
client, monkeypatch, image, wait_timeout
):
create = respx.post(f"{BASE_URL}/v1/sandboxes").respond(json={"sandbox_id": SB_ID})
waited = []
monkeypatch.setattr(
Sandbox, "wait_until_running", lambda self, timeout: waited.append(timeout)
)
Sandbox.create(image=image, client=client)
body = json.loads(create.calls.last.request.content)
assert body.get("image") == (image or None)
assert waited == [wait_timeout]


@respx.mock
def test_create_failed_state_raises_with_the_reason(client):
reason = "Container failed to start (StartError)"
respx.post(f"{BASE_URL}/v1/sandboxes").respond(json={"sandbox_id": SB_ID})
respx.get(f"{BASE_URL}/v1/sandboxes/{SB_ID}").respond(json=_info("failed"))
with pytest.raises(SandboxFailedError, match="failed") as excinfo:
Sandbox.create(client=client)
respx.get(f"{BASE_URL}/v1/sandboxes/{SB_ID}").respond(
json=_info("failed", fail_reason=reason)
)
with pytest.raises(SandboxFailedError, match=r"failed.*StartError") as excinfo:
Sandbox.create(image="gcr.io/distroless/static-debian12", client=client)
assert excinfo.value.sandbox_id == SB_ID
assert excinfo.value.fail_reason == reason
assert Sandbox.from_id(SB_ID, client=client).fail_reason == reason


@respx.mock
@pytest.mark.parametrize("image, waited", [("", 300), ("python@sha256:ab", 600)])
def test_wait_until_running_waits_longer_for_an_image_by_default(
client, monkeypatch, image, waited
):
respx.get(f"{BASE_URL}/v1/sandboxes/{SB_ID}").respond(
json=_info("starting", image=image)
)
now = [0.0]
clock = SimpleNamespace(
monotonic=lambda: now[0], sleep=lambda s: now.__setitem__(0, now[0] + s)
)
monkeypatch.setattr(sandbox_api, "time", clock)
sandbox = Sandbox(SandboxInfo(sandbox_id=SB_ID), client=client)
with pytest.raises(SandboxTimeoutError, match=f"after {waited}s"):
sandbox.wait_until_running()
assert waited - 4 < now[0] <= waited


@respx.mock
Expand Down
Loading