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
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ All implemented guardrails have corresponding tests. When adding a new guardrail
| RBAC (CallerIdentity + PolicyFile) | `authorization.py` + `policy_authorizer.py` + `temporal_api.py` | `test_authorization.py`, `test_policy_authorizer.py`, `temporal/test_api.py` |
| Circuit breaker | `circuit_breaker.py` + `temporal_activities.py` | `test_circuit_breaker.py`, `temporal/test_activities.py` |
| Cleanup failure metrics | `temporal_metrics.py` + `temporal_activities.py` | `temporal/test_cleanup_metrics.py` |
| Orphan reconciliation | `temporal_entrypoint.py` + `openshell_spawner.py` | `temporal/test_startup_reconciliation.py`, `spawner/test_openshell_spawner.py` -- `OpenShellSpawner._do_list_active()`/`_do_destroy()` now query the gateway's durable `ListSandboxes`/labels (issue #224) instead of the in-memory `self._sandbox_names` dict, so orphans from a previous process instance are discoverable across a restart. `agent_name` is recovered via a `cloud-agents/agent-name` label rather than the sandbox name itself -- the gateway caps caller-supplied names at 19 characters. |
| Orphan reconciliation | `temporal_entrypoint.py` + `openshell_spawner.py` | `temporal/test_startup_reconciliation.py`, `spawner/test_openshell_spawner.py` -- `OpenShellSpawner._do_list_active()`/`_do_destroy()` now query the gateway's durable `ListSandboxes`/labels (issue #224) instead of the in-memory `self._sandbox_names` dict, so orphans from a previous process instance are discoverable across a restart. `agent_name` is recovered via a `cloud-agents/agent-name` label rather than the sandbox name itself -- the gateway caps caller-supplied names at 19 characters. Reconcile destroys only sandboxes past their `cloud-agents/expires-at` label, by exact gateway sandbox name (`list_sandbox_labels()`/`destroy_sandbox()`, never by agent name); there is no runner-identity fast path. `expires-at` = ceil(stamp) + max(per-sandbox lifetime, `SANDBOX_MIN_LIFETIME_SECONDS`) + `SANDBOX_EXPIRY_SKEW_SECONDS`, where the lifetime is the sum of enforced deadlines in `spawner/lifetime.py` (420s spawn budget + run POST incl. client close + 30s transcript fetch + 30s save + 5×5s cancel grace + 120s grace; the spawn and each post-spawn phase run via `await_within()`, which abandons work that ignores cancellation); lifecycles without an enforced bound (CLI sessions) get no expiry. Old runners destroy every `spawned-by` sandbox, so drain them before new runners admit work -- see `docs/sandbox-contract.md#labels`. |
| E2E guardrails | `openshell_spawner.py` | `e2e/test_guardrails.py::TestOpenShellGuardrails`, `TestOpenShellQueryTLS` |

## Database Migrations (Alembic)
Expand Down
2 changes: 1 addition & 1 deletion docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ Temporal provides durable execution for workflow runs:
- **Retry and timeout** — `RetryPolicy` on each activity controls retry count; `start_to_close_timeout` enforces hard deadlines. Heartbeat-based cancellation detection ensures sandbox cleanup on timeout ([T2](archived/gaps-implementation-plan.md#t2-explicit-sandbox-termination-on-timeoutcancellation)).
- **Approval signals** — human approval is implemented as a Temporal signal (`AgentWorkflow.approve`), with `wait_condition` blocking until the signal arrives or times out.
- **Parallel execution** — steps sharing a `parallel_group` are dispatched via `asyncio.gather` within the workflow.
- **Crash recovery** — content-hash pod naming for idempotent retries + startup orphan reconciliation for leaked containers.
- **Crash recovery** — content-hash pod naming for idempotent retries + startup orphan reconciliation that destroys only sandboxes past their `cloud-agents/expires-at` label, computed from enforced spawn/run/transcript deadlines (see [sandbox-contract.md](sandbox-contract.md#labels), including the assumptions, the drain-before-upgrade requirement and one-time legacy cleanup).

### Dual Deployment

Expand Down
119 changes: 117 additions & 2 deletions docs/sandbox-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -127,5 +127,120 @@ Spawned sandbox pods carry these labels for lifecycle management:
| `cloud-agents/workflow-id` | Workflow execution ID |
| `cloud-agents/step-name` | Step name within the workflow |
| `cloud-agents/attempt` | Retry attempt number |

Used for: label-based orphan cleanup after worker crashes.
| `spawned-by` | `workflow-runner` (always set) |
| `cloud-agents/agent-name` | Agent name (always set; the gateway assigns the sandbox name) |
| `cloud-agents/expires-at` | Unix seconds: ceil(spawn time) + max(per-sandbox lifetime, `SANDBOX_MIN_LIFETIME_SECONDS`) + `SANDBOX_EXPIRY_SKEW_SECONDS` (set only when the caller passes a lifetime) |

Used for: label-based orphan cleanup after worker crashes. On startup a runner
lists `spawned-by=workflow-runner` sandboxes once and destroys exactly those
(by their unique gateway sandbox name, never by agent name) whose
`cloud-agents/expires-at` is in the past, whichever runner spawned them.
Expiry is the only criterion: a runner identity can't prove a sandbox's
previous owner is gone. Sandboxes with no `expires-at` and sandboxes with a
malformed one are left alone and logged. Caller-supplied `expires-at` labels
(and the retired `cloud-agents/owner-instance`) are always dropped.

**Assumptions.** Expiry is only as safe as the deadlines behind it: it relies
on every phase that can use a sandbox after `expires-at` is stamped being
bounded by an enforced wall-clock deadline, plus clocks between replicas
agreeing within `SANDBOX_EXPIRY_SKEW_SECONDS`. Labels alone guarantee
nothing.

**Per-sandbox lifetime** (`cloud_agents/spawner/lifetime.py`), the sum of the
enforced deadlines measured from when `expires-at` is stamped:

- **Spawn: 420s + 5s cancel grace** (`SANDBOX_SPAWN_DEADLINE_SECONDS`). One
budget in `OpenShellSpawner._do_spawn`, run through `await_within()` (see
below), that starts at the same instant `expires-at` is stamped and covers
CreateSandbox (30s SDK RPC timeout), the 300s gateway
ready wait, the 60s HTTP readiness check and ~30s of post-create
exec/expose calls (MCP secret writes, skill materialization, server start,
ExposeService). On timeout the spawn fails, and the sandbox is deleted on a
best-effort basis if CreateSandbox returned its name. That failure-path
cleanup (sandbox delete, provider delete) is bounded too, at 30s per step
(`SANDBOX_SPAWN_CLEANUP_TIMEOUT_SECONDS`), so it can't block the caller. It
isn't part of the lifetime, because a sandbox whose spawn failed is no
longer used. Cancelling the
awaiting coroutine doesn't stop a blocking SDK call already running in a
worker thread, so a CreateSandbox can still complete remotely after the
deadline. That sandbox exists with its `expires-at` label and is reaped
once expired. If its name is unknown, no delete is guessed.
- **Run: `permissions.timeout_seconds`** (default 600) **+ 5s cancel grace.**
Both engines enforce it as an overall deadline on `POST /v1/agent/run`
*including the HTTP client's close*, since httpx's own timeout is per read.
Temporal's `start_to_close_timeout` can only end a step earlier.
- **Progress-stream cleanup: 5s cancel grace.**
- **Transcript fetch: 30s + 5s grace** (including its client's close).
**Transcript-store save: 30s + 5s grace.**
- **Destroy grace: 120s.** A margin, not a safety requirement: once the
transcript save finishes the sandbox is no longer used.

So a step's lifetime is 420 + run timeout + 30 + 30 + 5 × 5 + 120 seconds.

**Bounded vs. abandoned work.** The spawn and each post-spawn phase run through
`await_within()`/`cancel_within()` (`spawner/lifetime.py`). The work runs as
a task that's waited on for at most its deadline. Then it's cancelled and
waited on for at most `SANDBOX_CANCEL_GRACE_SECONDS` (5s). Cooperative I/O
(httpx, asyncpg, asyncio) stops within that grace and is fully bounded. A
task still running after the grace is uncooperative: it's abandoned (logged,
never awaited again) and the step fails or moves on without using the
sandbox from that phase again. In particular, a timed-out run never goes on
to fetch the transcript. Python can't preempt arbitrary code, so abandoned
work may keep running in the background. The bound is on how long the step
itself keeps using the sandbox, not a hard guarantee about uncooperative
code.

Each retry attempt spawns a new sandbox (the attempt number is part of the
`ca-` name; the activity runs with `maximum_attempts=1`), so the lifetime is
per attempt. A lifecycle without an enforced latest-use bound gets no
lifetime and no `expires-at`, so startup reconcile never reaps it. CLI
sessions are one: their timeout monitor can stop or block.

`SANDBOX_MIN_LIFETIME_SECONDS` (default 86400) and `SANDBOX_EXPIRY_SKEW_SECONDS`
(default 600) are operational margins, not enforcement: the floor only delays
how soon an expired orphan is reaped, and the skew covers clock differences
between replicas. Both must be non-negative integers or startup fails.

**Upgrades and rollbacks.** Runners from before expiry-based reconcile destroy
*every* `spawned-by=workflow-runner` sandbox on startup, so a single old
runner starting up can destroy live sandboxes of new runners. Stop and drain
all old runners **before** any new runner admits work. Running both versions
side by side for any length of time isn't safe. A rollback needs the same
order in reverse: stop and drain the new runners before starting old ones.

**Legacy sandboxes.** Sandboxes spawned by older runners carry no `expires-at`
and are never reaped automatically. Once no old-version runner (and no
workflow it started) is still running, clean them up once with the OpenShell
SDK (add the TLS/bearer-token arguments your gateway needs, as in
`cloud_agents/spawner/factory.py`). CLI session sandboxes also lack
`expires-at` by design, so the script skips them. Run it with `DRY_RUN = True`
first:

```python
from openshell import SandboxClient

DRY_RUN = True
client = SandboxClient(endpoint="<gateway host:port>")
legacy, offset, page = [], 0, 100
while True:
refs = client.list(
workspace="default",
label_selector="spawned-by=workflow-runner",
limit=page,
offset=offset,
)
legacy += [
ref.name
for ref in refs
if "cloud-agents/expires-at" not in ref.labels
and ref.labels.get("cloud-agents/session-type") != "cli-handoff"
]
if len(refs) < page:
break
offset += page
# Delete after listing so deletions don't shift later pages.
for name in legacy:
print("would delete" if DRY_RUN else "deleting", name)
if not DRY_RUN:
client.delete(name, workspace="default")
```
59 changes: 58 additions & 1 deletion src/cloud_agents/spawner/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,7 @@ async def spawn(
credential_secret_name: str | None = None,
mcp_secret_mounts: list[tuple[str, str, str]] | None = None,
tls_certs: EphemeralCerts | None = None,
lifetime_seconds: int | None = None,
) -> str:
"""Spawn an agent pod and return its endpoint URL.

Expand Down Expand Up @@ -171,6 +172,11 @@ async def spawn(
mcp_secret_mounts: List of (secret_name, key, mount_path) tuples
for MCP server Secret-backed auth headers.
tls_certs: Optional ephemeral TLS certs to inject into sandbox.
lifetime_seconds: Latest legitimate life of this sandbox (see
cloud_agents.spawner.lifetime). OpenShellSpawner stamps an
expiry label from it so any replica's startup reconcile can
reap the sandbox once expired; None means no expiry, so only
the owning replica can reap it.

Returns:
HTTP endpoint URL of the spawned pod.
Expand Down Expand Up @@ -200,9 +206,11 @@ async def spawn(
credential_secret_name=credential_secret_name,
mcp_secret_mounts=mcp_secret_mounts,
tls_certs=tls_certs,
lifetime_seconds=lifetime_seconds,
)
return endpoint
except Exception:
except BaseException:
# Includes cancellation, so a cancelled spawn frees its slot too.
async with self._lock:
self._active_count -= 1
raise
Expand Down Expand Up @@ -264,6 +272,55 @@ async def _do_list_active(
) -> list[str]:
"""Implementation-specific listing of active agents."""

async def list_sandbox_labels(
self,
labels: dict[str, str] | None = None,
) -> list[tuple[str, dict[str, str]]]:
"""List active sandboxes as (exact sandbox name, labels).

A spawner that reports labels (overrides _do_list_sandbox_labels) must
also implement _do_destroy_sandbox() for the names it returns.

Args:
labels: Optional label selector to filter results.

Returns:
One pair per sandbox, keyed by a name destroy_sandbox() deletes
exactly, so callers can filter on label values a selector can't
express (e.g. reconcile_orphaned_sandboxes()' expiry check).
"""
return await self._do_list_sandbox_labels(labels)

async def _do_list_sandbox_labels(
self,
labels: dict[str, str] | None = None,
) -> list[tuple[str, dict[str, str]]]:
"""Default for spawners that can't report labels: empty labels each.

Startup reconciliation never destroys a sandbox without an expiry
label, so this default is fail-safe.
"""
return [(name, {}) for name in await self._do_list_active(labels)]

async def destroy_sandbox(self, sandbox_name: str) -> None:
"""Destroy exactly the sandbox list_sandbox_labels() reported by this name.

Raises:
NotImplementedError: If the spawner doesn't support exact deletion.
"""
await self._do_destroy_sandbox(sandbox_name)

async def _do_destroy_sandbox(self, sandbox_name: str) -> None:
"""Implementation-specific exact deletion of one sandbox.

Deliberately no fallback to destroy(): that takes an agent name, and
an agent name can map to several sandboxes, so falling back could
delete sandboxes other than the one selected.
"""
raise NotImplementedError(
f"{type(self).__name__} cannot destroy a sandbox by its exact name"
)

async def read_file(self, agent_name: str, path: str) -> str:
"""Read a file from a spawned agent container.

Expand Down
10 changes: 9 additions & 1 deletion src/cloud_agents/spawner/factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,15 @@
# cause. Filtering here lets a caller pass a broader config object (e.g. a
# lightspeed-stack Pydantic model_dump() with `type`/`sandbox_image`/etc.
# mixed in) without needing to hand-pick fields first.
_OPENSHELL_EXTRA_PARAMS = frozenset({"max_pods", "extra_readable_paths", "extra_env"})
_OPENSHELL_EXTRA_PARAMS = frozenset(
{
"max_pods",
"extra_readable_paths",
"extra_env",
"min_lifetime_seconds",
"expiry_skew_seconds",
}
)


def _filtered(params: dict[str, Any], known: frozenset[str]) -> dict[str, Any]:
Expand Down
Loading
Loading