diff --git a/CLAUDE.md b/CLAUDE.md index 39377db..3f2561f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 37ef01c..64ad8fe 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -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 diff --git a/docs/sandbox-contract.md b/docs/sandbox-contract.md index b6ecace..8c028ba 100644 --- a/docs/sandbox-contract.md +++ b/docs/sandbox-contract.md @@ -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="") +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") +``` diff --git a/src/cloud_agents/spawner/base.py b/src/cloud_agents/spawner/base.py index a17c121..d900597 100644 --- a/src/cloud_agents/spawner/base.py +++ b/src/cloud_agents/spawner/base.py @@ -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. @@ -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. @@ -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 @@ -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. diff --git a/src/cloud_agents/spawner/factory.py b/src/cloud_agents/spawner/factory.py index bd91596..fee5e9d 100644 --- a/src/cloud_agents/spawner/factory.py +++ b/src/cloud_agents/spawner/factory.py @@ -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]: diff --git a/src/cloud_agents/spawner/lifetime.py b/src/cloud_agents/spawner/lifetime.py new file mode 100644 index 0000000..ef5eacd --- /dev/null +++ b/src/cloud_agents/spawner/lifetime.py @@ -0,0 +1,163 @@ +"""Sandbox expiry labels and the enforced deadlines they're computed from. + +Shared by OpenShellSpawner (which stamps the labels at spawn time), +reconcile_orphaned_sandboxes() (which filters on them at startup) and the +spawn call sites that compute each sandbox's lifetime. Kept dependency-free +so the Temporal workflow module can import it. + +A sandbox's cloud-agents/expires-at label must never be earlier than its +latest legitimate use, or another replica's startup reconcile could destroy +it while still in use. Each workflow step therefore passes a lifetime equal +to the sum of the wall-clock deadlines enforced on everything that can use +the sandbox after expires-at is stamped (spawn budget, run call, transcript +fetch and save) plus destroy grace; the spawner adds a clock-skew margin. +Lifecycles without an enforced latest-use bound (e.g. CLI sessions) pass no +lifetime and get no expiry, so startup reconcile never reaps them. + +Spawn and each post-spawn I/O phase run through await_within(): the work runs as a +task that's waited on for at most its deadline, then cancelled and waited on +for at most SANDBOX_CANCEL_GRACE_SECONDS. Cooperative I/O (httpx, asyncpg, +asyncio) stops within that grace. A task still running after it is +uncooperative: it's abandoned (logged, never awaited again) and the caller +fails or moves on without touching the sandbox from that phase again. +Python can't preempt arbitrary code, so abandoned work may keep running in +the background; the bound is on how long the step keeps using the sandbox. +""" + +from __future__ import annotations + +import asyncio +import logging +import math +from collections.abc import Awaitable +from typing import Any, TypeVar + +logger = logging.getLogger(__name__) + +T = TypeVar("T") + +# Attached to every sandbox so reconcile can find sandboxes spawned by a +# previous process instance via ListSandboxes(label_selector=...) (issue #224). +SPAWNED_BY_LABEL: dict[str, str] = {"spawned-by": "workflow-runner"} +# Unix seconds after which any replica's reconcile may destroy the sandbox. +EXPIRES_AT_LABEL_KEY = "cloud-agents/expires-at" +# Written by an earlier, unreleased owner-scoping design; never stamped now. +RETIRED_OWNER_INSTANCE_LABEL_KEY = "cloud-agents/owner-instance" +# Set only by the spawner (or not at all); dropped from caller labels. +RESERVED_LABEL_KEYS = frozenset({EXPIRES_AT_LABEL_KEY, RETIRED_OWNER_INSTANCE_LABEL_KEY}) + +# Step run timeout (permissions.timeout_seconds) when unset; also the Temporal +# start_to_close_timeout default for a step without timeout_seconds. +DEFAULT_STEP_TIMEOUT_SECONDS = 600 +# OpenShellSpawner._do_spawn: gateway wait_ready after CreateSandbox ... +SANDBOX_GATEWAY_READY_TIMEOUT_SECONDS = 300 +# ... then the gateway-proxied HTTP health check. +SANDBOX_HTTP_READY_TIMEOUT_SECONDS = 60 +# Overall budget for OpenShellSpawner._do_spawn, starting when expires-at is +# stamped and covering CreateSandbox (30s SDK RPC timeout), the gateway ready +# wait, the HTTP health check, and 30s for post-create exec/expose calls. +SANDBOX_SPAWN_DEADLINE_SECONDS = ( + 30 + SANDBOX_GATEWAY_READY_TIMEOUT_SECONDS + SANDBOX_HTTP_READY_TIMEOUT_SECONDS + 30 +) +# run_sandbox_step's heartbeat_timeout (temporal/workflow.py). Not part of the +# lifetime: the run call is bounded locally, not by heartbeat cancellation. +SANDBOX_ACTIVITY_HEARTBEAT_TIMEOUT_SECONDS = 180 +# Wall-clock bound on the post-run GET /v1/agent/events transcript fetch ... +SANDBOX_TRANSCRIPT_TIMEOUT_SECONDS = 30 +# ... and on persisting it to the transcript store, before destroy. +SANDBOX_TRANSCRIPT_SAVE_TIMEOUT_SECONDS = 30 +# After a phase's deadline: how long to wait for its cancelled task to +# finish (e.g. an HTTP client's close) before abandoning it. +SANDBOX_CANCEL_GRACE_SECONDS = 5 +# Bound on each best-effort cleanup step (sandbox delete, provider delete) +# after a failed spawn. Not part of the lifetime: a sandbox whose spawn has +# failed is no longer used, so reaping it mid-cleanup is harmless. This only +# keeps a stuck cleanup from blocking the caller. +SANDBOX_SPAWN_CLEANUP_TIMEOUT_SECONDS = 30 +# Margin for the remaining in-process work and the finally-block destroy(); +# not a safety requirement, since a sandbox is no longer used once the +# transcript save has finished. +SANDBOX_DESTROY_GRACE_SECONDS = 120 + + +def run_timeout_seconds(step: dict[str, Any]) -> float: + """Wall-clock deadline on a step's POST /v1/agent/run call.""" + permissions = step.get("permissions") or {} + return float(permissions.get("timeout_seconds", DEFAULT_STEP_TIMEOUT_SECONDS)) + + +def step_sandbox_lifetime_seconds(step: dict[str, Any]) -> int: + """Latest legitimate use of one workflow step attempt's sandbox, measured + from when expires-at is stamped: the sum of the enforced spawn, run, + transcript fetch and transcript save deadlines, a cancel grace for each + of the five await_within() phases (spawn, run, progress cleanup, + transcript fetch, transcript save), plus destroy grace. Each retry attempt spawns a + fresh sandbox (attempt is part of compute_pod_name()), so this is per + attempt. + """ + return ( + SANDBOX_SPAWN_DEADLINE_SECONDS + + math.ceil(run_timeout_seconds(step)) + + SANDBOX_TRANSCRIPT_TIMEOUT_SECONDS + + SANDBOX_TRANSCRIPT_SAVE_TIMEOUT_SECONDS + + 5 * SANDBOX_CANCEL_GRACE_SECONDS + + SANDBOX_DESTROY_GRACE_SECONDS + ) + + +class SandboxDeadlineExceeded(TimeoutError): + """Raised by await_within() when its own deadline expired, as opposed to + a TimeoutError raised by the awaited work itself.""" + + +async def await_within(work: Awaitable[T], timeout: float, *, what: str) -> T: + """Await work for at most timeout + SANDBOX_CANCEL_GRACE_SECONDS. + + Runs work as a task rather than under asyncio.timeout(): a timeout fires + once, so cleanup that runs after it (e.g. a client __aexit__) would get + no bound of its own. + + Raises: + SandboxDeadlineExceeded: If work didn't finish within timeout. It is + cancelled and, if still running after the cancel grace, abandoned. + """ + task = asyncio.ensure_future(work) + try: + done, _ = await asyncio.wait({task}, timeout=timeout) + except asyncio.CancelledError: + await cancel_within(task, what=what) + raise + if task in done: + return task.result() + await cancel_within(task, what=what) + raise SandboxDeadlineExceeded(f"{what} timed out after {timeout:g}s") + + +async def cancel_within(task: asyncio.Future[Any], *, what: str) -> None: + """Cancel task and wait at most SANDBOX_CANCEL_GRACE_SECONDS for it. + + A task that hasn't finished by then is abandoned: logged and never + awaited again. Its eventual result or error is consumed, not raised. + """ + task.cancel() + # Attached before waiting, so the outcome is consumed even if this wait + # is itself cancelled (consuming twice is harmless). + task.add_done_callback(_consume) + try: + done, _ = await asyncio.wait({task}, timeout=SANDBOX_CANCEL_GRACE_SECONDS) + except asyncio.CancelledError: + if not task.done(): + logger.warning("%s still running when its caller was cancelled — abandoning it", what) + raise + if task not in done: + logger.warning( + "%s did not stop within %ss of cancellation — abandoning it", + what, + SANDBOX_CANCEL_GRACE_SECONDS, + ) + + +def _consume(task: asyncio.Future[Any]) -> None: + """Retrieve a finished task's outcome so asyncio doesn't log it as lost.""" + if not task.cancelled(): + task.exception() diff --git a/src/cloud_agents/spawner/openshell_spawner.py b/src/cloud_agents/spawner/openshell_spawner.py index 3190f79..1e71c38 100644 --- a/src/cloud_agents/spawner/openshell_spawner.py +++ b/src/cloud_agents/spawner/openshell_spawner.py @@ -17,14 +17,27 @@ import asyncio import json import logging +import math import os import ssl +import time from collections.abc import Callable from typing import TYPE_CHECKING, Any, AsyncIterator, ClassVar import httpx from cloud_agents.spawner.base import AGENT_EVENT_LOG_PATH, AgentSpawner +from cloud_agents.spawner.lifetime import ( + EXPIRES_AT_LABEL_KEY, + RESERVED_LABEL_KEYS, + SANDBOX_GATEWAY_READY_TIMEOUT_SECONDS, + SANDBOX_HTTP_READY_TIMEOUT_SECONDS, + SANDBOX_SPAWN_CLEANUP_TIMEOUT_SECONDS, + SANDBOX_SPAWN_DEADLINE_SECONDS, + SPAWNED_BY_LABEL, + SandboxDeadlineExceeded, + await_within, +) if TYPE_CHECKING: from cloud_agents.spawner.base import SpawnConfig @@ -158,12 +171,20 @@ class OpenShellSpawner(AgentSpawner): # label instead of the sandbox name (issue #224). _AGENT_NAME_LABEL_KEY: ClassVar[str] = "cloud-agents/agent-name" + # ListSandboxes page size used by _list_refs(). + _LIST_PAGE_SIZE: ClassVar[int] = 1000 + # Attached to every sandbox at create time (merged with caller-supplied # labels) so reconcile_orphaned_sandboxes() can find sandboxes spawned by # a *previous* process instance via ListSandboxes(label_selector=...) - # (issue #224). Must match the label reconcile_orphaned_sandboxes() in - # workflow/executor/temporal/entrypoint.py filters on. - _SPAWNED_BY_LABEL: ClassVar[dict[str, str]] = {"spawned-by": "workflow-runner"} + # (issue #224). Shared with reconcile via cloud_agents.spawner.lifetime. + _SPAWNED_BY_LABEL: ClassVar[dict[str, str]] = SPAWNED_BY_LABEL + + # Unix seconds after which the sandbox has outlived any legitimate use + # (spawn time + max(lifetime_seconds, min_lifetime_seconds) + skew). Any + # replica's reconcile_orphaned_sandboxes() may reap a sandbox once it's + # past this. Omitted when the caller passes no lifetime_seconds. + _EXPIRES_AT_LABEL_KEY: ClassVar[str] = EXPIRES_AT_LABEL_KEY # Baked into the sandbox image (lightspeed-agentic-sandbox's # Containerfile); copies the allowed_skills subset from _SKILLS_ROOT @@ -285,6 +306,9 @@ def __init__( bearer_token_provider: Callable[[], str] | None = None, extra_readable_paths: list[str] | None = None, extra_env: dict[str, str] | None = None, + min_lifetime_seconds: int = 0, + expiry_skew_seconds: int = 600, + clock: Callable[[], float] = time.time, **kwargs: Any, ) -> None: """Initialize the OpenShell spawner. @@ -330,8 +354,28 @@ def __init__( (see _DEFAULT_EXTRA_ENV). A derived image with a different layout, or no need for this at all, should override this (pass {} to disable). See issue #192. + min_lifetime_seconds: Floor for a sandbox's expiry: the + _EXPIRES_AT_LABEL_KEY label is spawn time + + max(spawn()'s lifetime_seconds, this) + expiry_skew_seconds, + so startup reconciliation on any replica can reap it once + expired. Only applies when spawn() is given lifetime_seconds. + An operational margin (how soon orphans may be reaped), not + what makes expiry safe -- that's the enforced deadlines in + lifetime_seconds. + expiry_skew_seconds: Margin added to every expiry for clock skew + between replicas. + clock: Returns the current unix time; injectable for tests. """ super().__init__(**kwargs) + for name, value in ( + ("min_lifetime_seconds", min_lifetime_seconds), + ("expiry_skew_seconds", expiry_skew_seconds), + ): + if value < 0: + raise ValueError(f"{name} must not be negative, got {value}") + self._min_lifetime_seconds = min_lifetime_seconds + self._expiry_skew_seconds = expiry_skew_seconds + self._clock = clock self._client = openshell_client self._workspace = workspace self._endpoint = endpoint @@ -885,6 +929,7 @@ async def _do_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: """Create an OpenShell sandbox, start HTTP server, return endpoint.""" from openshell._proto import openshell_pb2 @@ -1025,12 +1070,31 @@ async def _do_spawn( # Merge caller labels with the fixed spawned-by label and the # agent_name recovery label; both always win over caller-supplied # labels of the same key so a caller can't accidentally suppress - # orphan discovery (issue #224). + # orphan discovery (issue #224). Caller-supplied expires-at (and the + # retired owner-instance) are always dropped: only this spawner may + # mark a sandbox as expired for every replica. sandbox_labels = { - **(labels or {}), + **{k: v for k, v in (labels or {}).items() if k not in RESERVED_LABEL_KEYS}, **self._SPAWNED_BY_LABEL, self._AGENT_NAME_LABEL_KEY: agent_name, } + # The spawn budget starts at the same instant expires-at is stamped, + # so the label covers create plus every post-create phase below. + stamped_at = self._clock() + spawn_deadline = asyncio.get_running_loop().time() + SANDBOX_SPAWN_DEADLINE_SECONDS + if lifetime_seconds is None: + logger.debug( + "No lifetime_seconds for agent '%s' — no expires-at label; startup " + "reconcile will never reap it", + agent_name, + ) + else: + # Rounded up: flooring would expire the sandbox up to 1s early. + sandbox_labels[self._EXPIRES_AT_LABEL_KEY] = str( + math.ceil(stamped_at) + + max(lifetime_seconds, self._min_lifetime_seconds) + + self._expiry_skew_seconds + ) spec = openshell_pb2.SandboxSpec( template=openshell_pb2.SandboxTemplate( @@ -1060,14 +1124,21 @@ async def _do_spawn( else: self._build_baseline_filesystem_policy(spec, allowed_skills=allowed_skills) - try: + # Cancelling the awaiting coroutine on timeout doesn't stop a + # blocking SDK call already running in its worker thread: a + # CreateSandbox may still complete remotely after we give up. Such a + # sandbox carries its expires-at label and is reaped once expired. + created_name: str | None = None + + async def _create_and_start() -> str: + nonlocal sandbox_name, created_name sandbox_ref = await asyncio.to_thread( self._client.create, workspace=self._workspace, spec=spec, labels=sandbox_labels, ) - sandbox_name = sandbox_ref.name + sandbox_name = created_name = sandbox_ref.name sandbox_id = sandbox_ref.id self._sandbox_names[agent_name] = sandbox_name self._sandbox_ids[agent_name] = sandbox_id @@ -1076,7 +1147,7 @@ async def _do_spawn( self._client.wait_ready, sandbox_name, workspace=self._workspace, - timeout_seconds=300, + timeout_seconds=SANDBOX_GATEWAY_READY_TIMEOUT_SECONDS, ) # Credential Provider already created and attached via spec.providers @@ -1129,11 +1200,23 @@ async def _do_spawn( ready = await self._wait_ready_with_host( endpoint, virtual_host, - timeout=60.0, + timeout=SANDBOX_HTTP_READY_TIMEOUT_SECONDS, ) if not ready: raise RuntimeError(f"Sandbox '{sandbox_name}' HTTP server did not become ready") - except Exception: + return endpoint + + try: + # The rest of the budget that started at the expires-at stamp. + # await_within() also bounds cleanup that runs after the deadline + # (e.g. the readiness check's client close) by the cancel grace. + endpoint = await await_within( + _create_and_start(), + spawn_deadline - asyncio.get_running_loop().time(), + what=f"Spawning sandbox for agent '{agent_name}'", + ) + except BaseException as exc: + # BaseException so a cancelled spawn also cleans up what it created. logger.warning( "Post-create step failed for sandbox '%s' (agent=%s); " "deleting sandbox to prevent orphan", @@ -1146,11 +1229,33 @@ async def _do_spawn( # BEFORE deleting the provider itself -- the gateway refuses # DeleteProvider while it's still attached to a sandbox # (FAILED_PRECONDITION), which previously leaked the provider - # on every post-create failure (issue #214). - await self._cleanup_sandbox(agent_name, sandbox_name) + # on every post-create failure (issue #214). Best-effort, and only + # for the exact sandbox CreateSandbox returned: if it never + # returned, its identity is unknown and no delete is guessed. + # Each step is bounded so a stuck cleanup can't block the caller. + if created_name is not None: + try: + await await_within( + self._cleanup_sandbox(agent_name, created_name), + SANDBOX_SPAWN_CLEANUP_TIMEOUT_SECONDS, + what=f"Cleanup of sandbox '{created_name}'", + ) + except Exception: + logger.warning( + "Cleanup of sandbox '%s' did not finish — it will be reaped " + "once expired, if it has an expires-at label", + created_name, + exc_info=True, + ) + else: + self._provider_ids.pop(agent_name, None) if provider_id: try: - await self._delete_provider(provider_id) + await await_within( + self._delete_provider(provider_id), + SANDBOX_SPAWN_CLEANUP_TIMEOUT_SECONDS, + what=f"Deletion of provider '{provider_id}'", + ) logger.info( "Cleaned up orphaned provider '%s' after failed create", provider_id ) @@ -1158,6 +1263,13 @@ async def _do_spawn( logger.warning( "Failed to delete orphaned provider '%s'", provider_id, exc_info=True ) + if isinstance(exc, SandboxDeadlineExceeded): + # Only for the budget actually expiring; a phase's own + # TimeoutError propagates unchanged. + raise TimeoutError( + f"Spawning sandbox for agent '{agent_name}' exceeded its " + f"{SANDBOX_SPAWN_DEADLINE_SECONDS}s deadline" + ) from None raise logger.info( @@ -2105,15 +2217,56 @@ async def _do_list_active( of being silently dropped -- destroy() falls back to treating such a name literally, so this remains cleanable. """ - label_selector = ",".join(f"{key}={value}" for key, value in (labels or {}).items()) - refs = await asyncio.to_thread( - self._client.list, - workspace=self._workspace, - label_selector=label_selector or None, - # SandboxClient.list() defaults to limit=100 with no built-in - # pagination here; raised well above expected orphan counts as a - # cheap mitigation. True pagination is a follow-up if a workspace - # ever legitimately exceeds this. - limit=1000, + return [ + ref.labels.get(self._AGENT_NAME_LABEL_KEY) or ref.name + for ref in await self._list_refs(labels) + ] + + async def _do_list_sandbox_labels( + self, + labels: dict[str, str] | None = None, + ) -> list[tuple[str, dict[str, str]]]: + """List (exact gateway sandbox name, labels) from one gateway call. + + Unlike _do_list_active(), names are the sandboxes' own unique gateway + names, not their agent-name label (which several refs can share), so + reconcile_orphaned_sandboxes() can delete exactly the refs it selects + via _do_destroy_sandbox(). + """ + return [(ref.name, dict(ref.labels)) for ref in await self._list_refs(labels)] + + async def _do_destroy_sandbox(self, sandbox_name: str) -> None: + """Delete exactly this gateway sandbox, with no agent-name expansion. + + A sandbox tracked by this process goes through destroy() for the full + provider/task cleanup (its tracked path deletes only the tracked + name); an untracked one is deleted by name and nothing else. + """ + agent_name = next( + (agent for agent, name in self._sandbox_names.items() if name == sandbox_name), + None, ) - return [ref.labels.get(self._AGENT_NAME_LABEL_KEY) or ref.name for ref in refs] + if agent_name is not None: + await self.destroy(agent_name) + return + await asyncio.to_thread(self._client.delete, sandbox_name, workspace=self._workspace) + logger.info("Destroyed OpenShell sandbox '%s'", sandbox_name) + + async def _list_refs(self, labels: dict[str, str] | None = None) -> list[Any]: + """ListSandboxes for this workspace, filtered by a label selector.""" + label_selector = ",".join(f"{key}={value}" for key, value in (labels or {}).items()) + refs: list[Any] = [] + offset = 0 + while True: + # SandboxClient.list() returns at most `limit` refs per call. + page = await asyncio.to_thread( + self._client.list, + workspace=self._workspace, + label_selector=label_selector or None, + limit=self._LIST_PAGE_SIZE, + offset=offset, + ) + refs.extend(page) + if len(page) < self._LIST_PAGE_SIZE: + return refs + offset += self._LIST_PAGE_SIZE diff --git a/src/cloud_agents/workflow/cli_session.py b/src/cloud_agents/workflow/cli_session.py index 46cdb4f..93b3a8d 100644 --- a/src/cloud_agents/workflow/cli_session.py +++ b/src/cloud_agents/workflow/cli_session.py @@ -161,6 +161,9 @@ async def launch( } try: + # No lifetime_seconds (so no expires-at label): the timeout monitor + # can stop or block, so nothing enforces a latest-use bound, and + # startup reconcile must never reap a CLI session sandbox. endpoint = await spawner.spawn( agent_name=agent_name, image=image, diff --git a/src/cloud_agents/workflow/core/execution.py b/src/cloud_agents/workflow/core/execution.py index 8687100..c4c648a 100644 --- a/src/cloud_agents/workflow/core/execution.py +++ b/src/cloud_agents/workflow/core/execution.py @@ -77,6 +77,7 @@ from pydantic import BaseModel, ConfigDict, Field, NonNegativeInt, PositiveInt from cloud_agents.spawner.base import SpawnConfig +from cloud_agents.spawner.lifetime import DEFAULT_STEP_TIMEOUT_SECONDS from cloud_agents.workflow.core.interpolation import interpolate from cloud_agents.workflow.core.mcp_resolver import resolve_mcp_servers from cloud_agents.workflow.core.models import MCPServerConfig @@ -1357,7 +1358,7 @@ def build_step_input( tools_module=run_context.get("tools_module"), context=dict(step_results), execution_context=dict(normalized.context), - timeout_seconds=normalized.timeout_seconds or 600, + timeout_seconds=normalized.timeout_seconds or DEFAULT_STEP_TIMEOUT_SECONDS, sandbox_image=sandbox_image, skills_image=run_context.get("skills_image"), skills_paths=run_context.get("skills_paths"), diff --git a/src/cloud_agents/workflow/core/step_runner.py b/src/cloud_agents/workflow/core/step_runner.py index a7530be..6d6cf1c 100644 --- a/src/cloud_agents/workflow/core/step_runner.py +++ b/src/cloud_agents/workflow/core/step_runner.py @@ -12,7 +12,6 @@ from __future__ import annotations import asyncio -import contextlib import json import logging import os @@ -26,6 +25,14 @@ from cloud_agents.runtime.audit import emit_audit from cloud_agents.runtime.circuit_breaker import ProviderCircuitBreaker from cloud_agents.spawner.base import AGENT_EVENT_LOG_PATH +from cloud_agents.spawner.lifetime import ( + SANDBOX_TRANSCRIPT_SAVE_TIMEOUT_SECONDS, + SANDBOX_TRANSCRIPT_TIMEOUT_SECONDS, + await_within, + cancel_within, + run_timeout_seconds, + step_sandbox_lifetime_seconds, +) from cloud_agents.workflow.core.mcp_resolver import resolve_mcp_servers from cloud_agents.workflow.executor.step.provider import resolve_credential_env_key from cloud_agents.workflow.security.redact import redact_secrets @@ -72,11 +79,22 @@ async def _collect_transcript( empty = StepTranscript(step_name=step_name) try: - async with httpx.AsyncClient(**client_kwargs) as client: - response = await client.get( - f"{endpoint}/v1/agent/events", - headers=http_headers or None, - ) + # Own short bound rather than the step-sized run timeout, as a + # wall-clock deadline (httpx's timeout is per read), so the fetch fits + # the sandbox lifetime in cloud_agents.spawner.lifetime. Run via + # await_within() so a stalled client close is bounded too. + async def _fetch() -> httpx.Response: + async with httpx.AsyncClient( + **{**client_kwargs, "timeout": SANDBOX_TRANSCRIPT_TIMEOUT_SECONDS} + ) as client: + return await client.get( + f"{endpoint}/v1/agent/events", + headers=http_headers or None, + ) + + response = await await_within( + _fetch(), SANDBOX_TRANSCRIPT_TIMEOUT_SECONDS, what=f"Transcript fetch for '{step_name}'" + ) if response.status_code == 404: return empty @@ -306,7 +324,7 @@ async def _run_step_inner( permissions = step.get("permissions") or {} if sa := permissions.get("service_account"): env_vars["LIGHTSPEED_SERVICE_ACCOUNT"] = sa - http_timeout = float(permissions.get("timeout_seconds", 600)) + http_timeout = run_timeout_seconds(step) if spawner is None: logger.info("No spawner configured — returning stub result for '%s'", step_name) @@ -361,6 +379,7 @@ async def _run_step_inner( credential_secret_name=credential_env_key, mcp_secret_mounts=mcp_secret_mounts or None, tls_certs=tls_certs, + lifetime_seconds=step_sandbox_lifetime_seconds(step), ) ready = await spawner.wait_ready( endpoint, @@ -426,10 +445,10 @@ async def _run_step_inner( _stream_progress(spawner, sandbox_id, on_progress) ) - try: + async def _run_call() -> httpx.Response: async with httpx.AsyncClient(**client_kwargs) as client: try: - response = await client.post( + return await client.post( f"{endpoint}/v1/agent/run", json=request_body, headers=http_headers or None, @@ -449,11 +468,26 @@ async def _run_step_inner( error_type="ssl_error", ).inc() raise + + try: + try: + # Covers the client's close too, and abandons a close that + # ignores cancellation; httpx's own timeout is per read. + response = await await_within(_run_call(), http_timeout, what="Agent run") + except TimeoutError: + ls_sandbox_timeout_total.labels(step_name=step_name, reason="timeout").inc() + emit_audit( + event_type="sandbox_timeout", + workflow_id=workflow_id, + step_name=step_name, + details={"pod_name": pod_name, "reason": "timeout"}, + ) + # str(TimeoutError()) is empty, which the secret + # redaction below would turn into a blank error. + raise TimeoutError(f"Agent run timed out after {http_timeout:g}s") from None finally: if progress_task is not None: - progress_task.cancel() - with contextlib.suppress(asyncio.CancelledError): - await progress_task + await cancel_within(progress_task, what=f"Progress stream for '{step_name}'") if response.status_code == 502: _circuit_breaker.record_failure(provider_name) @@ -468,7 +502,13 @@ async def _run_step_inner( output_key = step.get("output_key", step_name) if transcript_store is not None and transcript.events: try: - await transcript_store.save(workflow_id, output_key, transcript) + # Runs before destroy, so it's bounded like every other + # phase in the sandbox lifetime (cloud_agents.spawner.lifetime). + await await_within( + transcript_store.save(workflow_id, output_key, transcript), + SANDBOX_TRANSCRIPT_SAVE_TIMEOUT_SECONDS, + what="Transcript save", + ) except Exception: logger.warning( "Failed to save transcript to store for step '%s'", diff --git a/src/cloud_agents/workflow/executor/temporal/activities.py b/src/cloud_agents/workflow/executor/temporal/activities.py index b93849b..73c2ddb 100644 --- a/src/cloud_agents/workflow/executor/temporal/activities.py +++ b/src/cloud_agents/workflow/executor/temporal/activities.py @@ -24,6 +24,14 @@ from cloud_agents.runtime.audit import emit_audit from cloud_agents.runtime.circuit_breaker import ProviderCircuitBreaker from cloud_agents.spawner.base import AGENT_EVENT_LOG_PATH +from cloud_agents.spawner.lifetime import ( + SANDBOX_TRANSCRIPT_SAVE_TIMEOUT_SECONDS, + SANDBOX_TRANSCRIPT_TIMEOUT_SECONDS, + await_within, + cancel_within, + run_timeout_seconds, + step_sandbox_lifetime_seconds, +) from cloud_agents.workflow.notifiers.escalation import LogPackager from cloud_agents.workflow.notifiers.notifier import NullNotifier from cloud_agents.workflow.core.mcp_resolver import resolve_mcp_servers @@ -311,11 +319,22 @@ async def _collect_transcript( empty = StepTranscript(step_name=step_name) try: - async with httpx.AsyncClient(**client_kwargs) as client: - response = await client.get( - f"{endpoint}/v1/agent/events", - headers=http_headers or None, - ) + # Own short bound rather than the step-sized run timeout, as a + # wall-clock deadline (httpx's timeout is per read), so the fetch fits + # the sandbox lifetime in cloud_agents.spawner.lifetime. Run via + # await_within() so a stalled client close is bounded too. + async def _fetch() -> httpx.Response: + async with httpx.AsyncClient( + **{**client_kwargs, "timeout": SANDBOX_TRANSCRIPT_TIMEOUT_SECONDS} + ) as client: + return await client.get( + f"{endpoint}/v1/agent/events", + headers=http_headers or None, + ) + + response = await await_within( + _fetch(), SANDBOX_TRANSCRIPT_TIMEOUT_SECONDS, what=f"Transcript fetch for '{step_name}'" + ) if response.status_code == 404: logger.debug("Event log not found for step '%s' (HTTP 404)", step_name) @@ -524,7 +543,7 @@ async def _run_sandbox_step_inner( permissions = step.get("permissions") or {} if sa := permissions.get("service_account"): env_vars["LIGHTSPEED_SERVICE_ACCOUNT"] = sa - http_timeout = float(permissions.get("timeout_seconds", 600)) + http_timeout = run_timeout_seconds(step) if spawner is None: logger.info("No spawner configured — returning stub result for '%s'", step_name) @@ -557,6 +576,9 @@ async def _run_sandbox_step_inner( endpoint = None was_cancelled = False + # Heartbeat from before spawn() until the activity ends: a long spawn + # would otherwise trip the heartbeat_timeout. + heartbeat_task = asyncio.create_task(_heartbeat_loop()) try: try: sa = permissions.get("service_account") @@ -577,6 +599,7 @@ async def _run_sandbox_step_inner( credential_secret_name=credential_env_key, mcp_secret_mounts=mcp_secret_mounts or None, tls_certs=tls_certs, + lifetime_seconds=step_sandbox_lifetime_seconds(step), ) ready = await spawner.wait_ready( endpoint, @@ -638,11 +661,10 @@ async def _run_sandbox_step_inner( _progress_streaming_loop(spawner, sandbox_id) ) - heartbeat_task = asyncio.create_task(_heartbeat_loop()) - try: + async def _run_call() -> httpx.Response: async with httpx.AsyncClient(**client_kwargs) as client: try: - response = await client.post( + return await client.post( f"{endpoint}/v1/agent/run", json=request_body, headers=http_headers or None, @@ -662,14 +684,30 @@ async def _run_sandbox_step_inner( error_type="ssl_error", ).inc() raise + + try: + try: + # Covers the client's close too, and abandons a close that + # ignores cancellation; httpx's own timeout is per read. + response = await await_within(_run_call(), http_timeout, what="Agent run") + except TimeoutError: + from cloud_agents.workflow.executor.temporal.metrics import ( + ls_sandbox_timeout_total, + ) + + ls_sandbox_timeout_total.labels(step_name=step_name, reason="timeout").inc() + emit_audit( + event_type="sandbox_timeout", + workflow_id=workflow_id, + step_name=step_name, + details={"pod_name": pod_name, "reason": "timeout"}, + ) + # str(TimeoutError()) is empty, which the secret + # redaction below would turn into a blank error. + raise TimeoutError(f"Agent run timed out after {http_timeout:g}s") from None finally: - heartbeat_task.cancel() - with contextlib.suppress(asyncio.CancelledError): - await heartbeat_task if progress_task is not None: - progress_task.cancel() - with contextlib.suppress(asyncio.CancelledError): - await progress_task + await cancel_within(progress_task, what=f"Progress stream for '{step_name}'") if response.status_code == 502: _circuit_breaker.record_failure(provider_name) @@ -688,7 +726,13 @@ async def _run_sandbox_step_inner( output_key = step.get("output_key", step_name) if transcript_store is not None and transcript.events: try: - await transcript_store.save(workflow_id, output_key, transcript) + # Runs before destroy, so it's bounded like every other + # phase in the sandbox lifetime (cloud_agents.spawner.lifetime). + await await_within( + transcript_store.save(workflow_id, output_key, transcript), + SANDBOX_TRANSCRIPT_SAVE_TIMEOUT_SECONDS, + what="Transcript save", + ) except Exception: logger.warning( "Failed to save transcript to store for step '%s'", @@ -737,6 +781,7 @@ async def _run_sandbox_step_inner( raise finally: + await cancel_within(heartbeat_task, what=f"Heartbeat for '{step_name}'") if was_cancelled and endpoint: from cloud_agents.workflow.executor.temporal.metrics import ls_sandbox_timeout_total diff --git a/src/cloud_agents/workflow/executor/temporal/entrypoint.py b/src/cloud_agents/workflow/executor/temporal/entrypoint.py index c14124c..764de6b 100644 --- a/src/cloud_agents/workflow/executor/temporal/entrypoint.py +++ b/src/cloud_agents/workflow/executor/temporal/entrypoint.py @@ -10,6 +10,7 @@ import logging import os +import time from collections.abc import AsyncGenerator from contextlib import asynccontextmanager from typing import TYPE_CHECKING @@ -19,6 +20,7 @@ from temporalio.worker import Worker from cloud_agents.runtime.tracing import init_tracing +from cloud_agents.spawner.lifetime import EXPIRES_AT_LABEL_KEY, SPAWNED_BY_LABEL from cloud_agents.storage.transcript_store import TranscriptStore from cloud_agents.workflow.core.definition_store import DefinitionStore from cloud_agents.runtime.logging import configure_logging @@ -73,6 +75,40 @@ def _build_tls_config(): SPAWNER_TYPE = os.environ.get("WORKFLOW_SPAWNER", "") +# Operational margins on every sandbox's expires-at label, not enforcement: +# expiry safety comes from the per-sandbox lifetime (the enforced deadlines in +# cloud_agents.spawner.lifetime). The floor only delays how soon an expired +# orphan may be reaped. +DEFAULT_SANDBOX_MIN_LIFETIME_SECONDS = 86400 +# Added to every expires-at for clock skew between replicas. +DEFAULT_SANDBOX_EXPIRY_SKEW_SECONDS = 600 + + +def _non_negative_int_env(name: str, default: int) -> int: + """Parse a non-negative integer env var, failing startup on bad values.""" + raw = os.environ.get(name, "") + if not raw: + return default + try: + value = int(raw) + except ValueError: + raise ValueError(f"{name}={raw!r} is not an integer") from None + if value < 0: + raise ValueError(f"{name}={value} must not be negative") + return value + + +def _sandbox_min_lifetime_seconds() -> int: + """SANDBOX_MIN_LIFETIME_SECONDS (default 86400): floor for sandbox expiry.""" + return _non_negative_int_env( + "SANDBOX_MIN_LIFETIME_SECONDS", DEFAULT_SANDBOX_MIN_LIFETIME_SECONDS + ) + + +def _sandbox_expiry_skew_seconds() -> int: + """SANDBOX_EXPIRY_SKEW_SECONDS (default 600): clock-skew margin on expiry.""" + return _non_negative_int_env("SANDBOX_EXPIRY_SKEW_SECONDS", DEFAULT_SANDBOX_EXPIRY_SKEW_SECONDS) + def _create_spawner(): """Create spawner based on environment config. @@ -86,7 +122,8 @@ def _create_spawner(): or empty. This must be fail-closed, not a silent stub fallback -- e.g. a leftover "kubernetes"/"podman" value from an unmigrated deploy manifest (or a typo) would otherwise silently disable - ephemeral spawning instead of refusing to start. + ephemeral spawning instead of refusing to start. Also raised for + an invalid SANDBOX_MIN_LIFETIME_SECONDS / SANDBOX_EXPIRY_SKEW_SECONDS. """ if SPAWNER_TYPE == "openshell": from cloud_agents.spawner.factory import build_spawner @@ -100,6 +137,8 @@ def _create_spawner(): tls_cert=os.environ.get("OPENSHELL_TLS_CERT", ""), tls_key=os.environ.get("OPENSHELL_TLS_KEY", ""), bearer_token=os.environ.get("OPENSHELL_BEARER_TOKEN", ""), + min_lifetime_seconds=_sandbox_min_lifetime_seconds(), + expiry_skew_seconds=_sandbox_expiry_skew_seconds(), ) if SPAWNER_TYPE == "": logger.info("No spawner configured — sandbox activity will use stub mode") @@ -109,26 +148,62 @@ def _create_spawner(): ) -async def reconcile_orphaned_sandboxes(spawner: AgentSpawner | None) -> None: - """Destroy orphaned sandbox containers left from a previous crash. +async def reconcile_orphaned_sandboxes( + spawner: AgentSpawner | None, now: float | None = None +) -> None: + """Destroy expired orphaned sandboxes left from a previous crash. + + On startup, lists sandboxes labelled "spawned-by=workflow-runner" once and + destroys exactly those whose "cloud-agents/expires-at" is in the past, + whichever runner spawned them. Expiry is the only criterion: no runner + identity can prove a sandbox's previous owner is gone, so an unexpired + sandbox may still be in use by a live replica. - On startup, scans for containers/Jobs with the "spawned-by=workflow-runner" - label and destroys them. This prevents resource leaks after unclean shutdowns. + Sandboxes with no expires-at label (spawned before expiry labelling + existed, or with no enforced lifetime, e.g. CLI sessions) and sandboxes + with a malformed one are left alone and logged. Args: spawner: The spawner instance, or None if no spawner is configured. + now: Current unix time; defaults to time.time(). Injectable for tests. """ if spawner is None: return - - orphans = await spawner.list_active({"spawned-by": "workflow-runner"}) + now = time.time() if now is None else now + + orphans = [] + no_expiry = 0 + for name, labels in await spawner.list_sandbox_labels(SPAWNED_BY_LABEL): + expires_at = labels.get(EXPIRES_AT_LABEL_KEY) + if expires_at is None: + no_expiry += 1 + continue + try: + expired = int(expires_at) < now + except ValueError: + logger.warning( + "Leaving sandbox '%s' untouched: malformed expires-at label %r", + name, + expires_at, + ) + continue + if expired: + orphans.append(name) + if no_expiry: + logger.info("Leaving %d sandbox(es) with no expires-at label untouched", no_expiry) cleaned = 0 failed_names = [] for name in orphans: logger.warning("Destroying orphaned sandbox '%s'", name) try: - await spawner.destroy(name) + await spawner.destroy_sandbox(name) cleaned += 1 + except NotImplementedError: + # Never fall back to agent-name destroy(): it may not be exact. + logger.warning( + "Skipping orphaned sandbox '%s': spawner can't destroy by exact name", name + ) + failed_names.append(name) except Exception as exc: logger.error("Failed to destroy orphaned sandbox '%s': %s", name, exc) failed_names.append(name) diff --git a/src/cloud_agents/workflow/executor/temporal/workflow.py b/src/cloud_agents/workflow/executor/temporal/workflow.py index 30751a0..763d1ba 100644 --- a/src/cloud_agents/workflow/executor/temporal/workflow.py +++ b/src/cloud_agents/workflow/executor/temporal/workflow.py @@ -16,6 +16,10 @@ from temporalio.exceptions import ActivityError with workflow.unsafe.imports_passed_through(): + from cloud_agents.spawner.lifetime import ( + DEFAULT_STEP_TIMEOUT_SECONDS, + SANDBOX_ACTIVITY_HEARTBEAT_TIMEOUT_SECONDS, + ) from cloud_agents.workflow.security.advisory import AdvisoryEnforcer from cloud_agents.workflow.security.auto_approve import ApprovalPolicy, classify_step_risk from cloud_agents.workflow.core.conditions import evaluate_condition @@ -354,7 +358,7 @@ async def _handle_agent_step( return result step_name = normalized.name output_key = normalized.output_key - timeout_seconds = normalized.timeout_seconds or 600 + timeout_seconds = normalized.timeout_seconds or DEFAULT_STEP_TIMEOUT_SECONDS max_retries = normalized.max_retries # Sandbox-image precedence (issue #268): step spawn_config → # definition spawn_config → run-level input image. The run-level @@ -435,7 +439,7 @@ async def attempt() -> Any: } ], start_to_close_timeout=timedelta(seconds=timeout_seconds), - heartbeat_timeout=timedelta(seconds=180), + heartbeat_timeout=timedelta(seconds=SANDBOX_ACTIVITY_HEARTBEAT_TIMEOUT_SECONDS), retry_policy=RetryPolicy(maximum_attempts=1), ) diff --git a/tests/unit/spawner/test_base.py b/tests/unit/spawner/test_base.py index 60107f6..97f47b2 100644 --- a/tests/unit/spawner/test_base.py +++ b/tests/unit/spawner/test_base.py @@ -1,5 +1,7 @@ """Unit tests for AgentSpawner base class.""" +import asyncio + import pytest from pydantic import ValidationError @@ -435,3 +437,50 @@ def test_millicore_cpu_exceeds_max_rejected(self) -> None: """Millicore CPU above 4000m is rejected.""" with pytest.raises(ValidationError, match="cpu_limit"): SpawnConfig(cpu_limit="5000m") + + +class TestListSandboxLabelsDefault: + """Spawners without label support report no labels, so reconcile treats + their sandboxes as having no expiry and never destroys them.""" + + @pytest.mark.asyncio + async def test_default_returns_empty_labels(self) -> None: + spawner = MockSpawner() + await spawner.spawn("a1", "img", env={}) + + assert await spawner.list_sandbox_labels({"spawned-by": "workflow-runner"}) == [("a1", {})] + + @pytest.mark.asyncio + async def test_default_destroy_sandbox_not_implemented(self) -> None: + """No agent-name fallback: a spawner must implement exact deletion + together with list_sandbox_labels().""" + spawner = MockSpawner() + await spawner.spawn("a1", "img", env={}) + + with pytest.raises(NotImplementedError): + await spawner.destroy_sandbox("a1") + + assert spawner.destroyed == [] + + @pytest.mark.asyncio + async def test_cancelled_spawn_restores_active_count(self) -> None: + class SlowSpawner(MockSpawner): + async def _do_spawn(self, *args, **kwargs): + await asyncio.sleep(3600) + + spawner = SlowSpawner() + task = asyncio.create_task(spawner.spawn("a1", "img", env={})) + await asyncio.sleep(0.01) + task.cancel() + + with pytest.raises(asyncio.CancelledError): + await task + assert spawner._active_count == 0 + + +class TestSpawnForwardsLifetime: + @pytest.mark.asyncio + async def test_lifetime_seconds_forwarded_to_do_spawn(self) -> None: + spawner = MockSpawner() + await spawner.spawn("a1", "img", env={}, lifetime_seconds=1234) + assert spawner.last_do_spawn_kwargs["lifetime_seconds"] == 1234 diff --git a/tests/unit/spawner/test_factory.py b/tests/unit/spawner/test_factory.py index f0bcc3f..cff32ec 100644 --- a/tests/unit/spawner/test_factory.py +++ b/tests/unit/spawner/test_factory.py @@ -26,6 +26,22 @@ def test_builds_openshell_spawner_no_auth(self, mocker: MockerFixture) -> None: assert spawner._tls_ca == "" assert spawner._bearer_token == "" + def test_lifetime_settings_forwarded(self, mocker: MockerFixture) -> None: + """Owner/lifetime settings reach OpenShellSpawner (stamped as labels on spawn).""" + from cloud_agents.spawner.factory import build_spawner + + mocker.patch("openshell.SandboxClient") + + spawner = build_spawner( + "openshell", + gateway_url="gw:17670", + min_lifetime_seconds=7200, + expiry_skew_seconds=30, + ) + + assert spawner._min_lifetime_seconds == 7200 + assert spawner._expiry_skew_seconds == 30 + def test_strips_http_scheme_from_gateway_url(self, mocker: MockerFixture) -> None: """http(s):// prefix is stripped before building the gRPC endpoint.""" from cloud_agents.spawner.factory import build_spawner diff --git a/tests/unit/spawner/test_lifetime.py b/tests/unit/spawner/test_lifetime.py new file mode 100644 index 0000000..a88fe72 --- /dev/null +++ b/tests/unit/spawner/test_lifetime.py @@ -0,0 +1,50 @@ +"""Tests for per-sandbox lifetime bounds used to stamp expires-at labels.""" + +from __future__ import annotations + +from cloud_agents.spawner import lifetime +from cloud_agents.spawner.lifetime import run_timeout_seconds, step_sandbox_lifetime_seconds + +# Enforced deadlines around the run itself: spawn budget + transcript fetch + +# transcript save, a cancel grace for each of the five bounded phases (spawn, +# run call, progress cleanup, transcript fetch, transcript save), plus destroy +# grace. +STEP_OVERHEAD = 420 + 30 + 30 + 5 * 5 + 120 + + +class TestRunTimeout: + def test_default(self) -> None: + assert run_timeout_seconds({"name": "s"}) == 600 + + def test_permissions_timeout(self) -> None: + assert run_timeout_seconds({"permissions": {"timeout_seconds": 5000}}) == 5000 + + +class TestStepSandboxLifetime: + """Lifetime = sum of the enforced deadlines a step's sandbox can live through.""" + + def test_default_run_timeout(self) -> None: + assert step_sandbox_lifetime_seconds({"name": "s"}) == 600 + STEP_OVERHEAD + + def test_follows_enforced_run_timeout(self) -> None: + step = {"timeout_seconds": 100, "permissions": {"timeout_seconds": 200_000}} + assert step_sandbox_lifetime_seconds(step) == 200_000 + STEP_OVERHEAD + + def test_rounds_fractional_run_timeout_up(self) -> None: + step = {"permissions": {"timeout_seconds": 0.5}} + assert step_sandbox_lifetime_seconds(step) == 1 + STEP_OVERHEAD + + def test_constants(self) -> None: + """Spawn budget covers the 30s SDK RPC timeout for CreateSandbox, the + 300s gateway ready wait, the 60s HTTP readiness check and 30s of + post-create exec/expose calls.""" + assert lifetime.SANDBOX_SPAWN_DEADLINE_SECONDS == 420 + assert lifetime.SANDBOX_SPAWN_DEADLINE_SECONDS >= ( + 30 + + lifetime.SANDBOX_GATEWAY_READY_TIMEOUT_SECONDS + + lifetime.SANDBOX_HTTP_READY_TIMEOUT_SECONDS + ) + assert lifetime.DEFAULT_STEP_TIMEOUT_SECONDS == 600 + assert lifetime.SANDBOX_TRANSCRIPT_TIMEOUT_SECONDS == 30 + assert lifetime.SANDBOX_TRANSCRIPT_SAVE_TIMEOUT_SECONDS == 30 + assert lifetime.SANDBOX_CANCEL_GRACE_SECONDS == 5 diff --git a/tests/unit/spawner/test_openshell_spawner.py b/tests/unit/spawner/test_openshell_spawner.py index ca9fde3..c80946e 100644 --- a/tests/unit/spawner/test_openshell_spawner.py +++ b/tests/unit/spawner/test_openshell_spawner.py @@ -759,6 +759,108 @@ async def mock_ready(*args, **kwargs): "cloud-agents/agent-name": "agent-1", } + @staticmethod + def _spawner_with_mocks(mocker: MockerFixture, **kwargs: Any): + """OpenShellSpawner with gateway calls mocked, for label assertions.""" + from cloud_agents.spawner.openshell_spawner import OpenShellSpawner + + class SandboxRef: + id: str = "test-id" + + def __init__(self, name): + self.name = name + + mock_client = mocker.Mock() + mock_client.create.return_value = SandboxRef("sb") + mock_client.wait_ready.return_value = SandboxRef("sb") + mock_client.exec_stream = lambda *a, **k: iter([]) + + spawner = OpenShellSpawner(openshell_client=mock_client, **kwargs) + mocker.patch.object( + spawner, "_expose_service", return_value=("http://gateway:17670", "host") + ) + + async def mock_ready(*args, **kwargs): + return True + + mocker.patch.object(spawner, "_wait_ready_with_host", side_effect=mock_ready) + mocker.patch.object(OpenShellSpawner, "_build_network_policy") + return spawner, mock_client + + @pytest.mark.asyncio + async def test_spawn_expires_at_uses_per_sandbox_lifetime(self, mocker: MockerFixture) -> None: + """expires-at = clock + max(lifetime_seconds, min_lifetime) + skew, so a + step longer than the global minimum still gets its full lifetime.""" + spawner, mock_client = self._spawner_with_mocks( + mocker, + min_lifetime_seconds=86400, + expiry_skew_seconds=600, + clock=lambda: 1_700_000_000.9, + ) + + await spawner.spawn("agent-1", "sandbox:latest", env={}, lifetime_seconds=200_000) + + labels = mock_client.create.call_args.kwargs["labels"] + # Rounded up, never down: flooring the stamp would expire it early. + assert labels["cloud-agents/expires-at"] == str(1_700_000_001 + 200_000 + 600) + + @pytest.mark.asyncio + async def test_spawn_expires_at_floors_at_min_lifetime(self, mocker: MockerFixture) -> None: + spawner, mock_client = self._spawner_with_mocks( + mocker, min_lifetime_seconds=86400, expiry_skew_seconds=600, clock=lambda: 1000.0 + ) + + await spawner.spawn("agent-1", "sandbox:latest", env={}, lifetime_seconds=60) + + labels = mock_client.create.call_args.kwargs["labels"] + assert labels["cloud-agents/expires-at"] == str(1000 + 86400 + 600) + + @pytest.mark.asyncio + async def test_spawn_without_lifetime_has_no_expiry(self, mocker: MockerFixture) -> None: + """No lifetime from the caller -> no expires-at (startup reconcile never reaps + it); the spawner never guesses a lifetime.""" + spawner, mock_client = self._spawner_with_mocks( + mocker, min_lifetime_seconds=86400, clock=lambda: 1000.0 + ) + + await spawner.spawn("agent-1", "sandbox:latest", env={}) + + assert "cloud-agents/expires-at" not in mock_client.create.call_args.kwargs["labels"] + + @pytest.mark.parametrize("kwargs", [{"min_lifetime_seconds": -1}, {"expiry_skew_seconds": -1}]) + def test_negative_lifetime_settings_rejected(self, mocker: MockerFixture, kwargs) -> None: + """A negative floor/skew could stamp an expiry before the sandbox's end.""" + from cloud_agents.spawner.openshell_spawner import OpenShellSpawner + + with pytest.raises(ValueError, match=next(iter(kwargs))): + OpenShellSpawner(openshell_client=mocker.Mock(), **kwargs) + + @pytest.mark.asyncio + async def test_spawn_strips_reserved_caller_labels_when_unconfigured( + self, mocker: MockerFixture + ) -> None: + """Caller-supplied expires-at (and the retired owner-instance) labels + are always dropped, even with no lifetime to stamp -- otherwise a + caller could make a sandbox look expired to every replica.""" + spawner, mock_client = self._spawner_with_mocks(mocker) + + await spawner.spawn( + "agent-1", + "sandbox:latest", + env={}, + labels={ + "cloud-agents/owner-instance": "runner-b", + "cloud-agents/expires-at": "1", + "keep": "me", + }, + ) + + assert mock_client.create.call_args.kwargs["labels"] == { + "keep": "me", + "spawned-by": "workflow-runner", + "cloud-agents/agent-name": "agent-1", + } + @pytest.mark.asyncio async def test_spawn_with_credential_does_not_expose_real_value( self, mocker: MockerFixture @@ -1445,8 +1547,69 @@ async def test_list_active_queries_gateway_not_local_state(self, mocker: MockerF workspace=spawner._workspace, label_selector="spawned-by=workflow-runner", limit=1000, + offset=0, + ) + + @pytest.mark.asyncio + async def test_list_sandbox_labels_returns_exact_sandbox_names( + self, mocker: MockerFixture + ) -> None: + """One ListSandboxes call yields each sandbox's exact gateway name (not + its agent-name label, which several refs may share) with its labels, + so reconcile can select and delete exactly the expired refs.""" + from cloud_agents.spawner.openshell_spawner import OpenShellSpawner + + mock_client = mocker.Mock() + mock_client.list.return_value = [ + self._FakeRef("petname-1", {"cloud-agents/agent-name": "agent-1", "k": "v"}), + self._FakeRef("petname-2"), + ] + spawner = OpenShellSpawner(openshell_client=mock_client) + + result = await spawner.list_sandbox_labels({"spawned-by": "workflow-runner"}) + + assert result == [ + ("petname-1", {"cloud-agents/agent-name": "agent-1", "k": "v"}), + ("petname-2", {}), + ] + mock_client.list.assert_called_once_with( + workspace=spawner._workspace, + label_selector="spawned-by=workflow-runner", + limit=1000, + offset=0, ) + @pytest.mark.asyncio + async def test_list_pages_through_all_sandboxes(self, mocker: MockerFixture) -> None: + """ListSandboxes is paged with offset until a short page, so orphans + beyond the first page are still found.""" + from cloud_agents.spawner.openshell_spawner import OpenShellSpawner + + refs = [self._FakeRef(f"sb-{i}") for i in range(5)] + mock_client = mocker.Mock() + mock_client.list.side_effect = lambda *, limit, offset, **kw: refs[offset : offset + limit] + spawner = OpenShellSpawner(openshell_client=mock_client) + mocker.patch.object(OpenShellSpawner, "_LIST_PAGE_SIZE", 2) + + result = await spawner.list_sandbox_labels({"spawned-by": "workflow-runner"}) + + assert [name for name, _ in result] == [f"sb-{i}" for i in range(5)] + assert [c.kwargs["offset"] for c in mock_client.list.call_args_list] == [0, 2, 4] + + @pytest.mark.asyncio + async def test_destroy_sandbox_deletes_only_that_ref(self, mocker: MockerFixture) -> None: + """No re-expansion by agent-name label: an untracked sandbox name is + deleted as-is, without listing other refs.""" + from cloud_agents.spawner.openshell_spawner import OpenShellSpawner + + mock_client = mocker.Mock() + spawner = OpenShellSpawner(openshell_client=mock_client) + + await spawner.destroy_sandbox("petname-1") + + mock_client.list.assert_not_called() + mock_client.delete.assert_called_once_with("petname-1", workspace=spawner._workspace) + @pytest.mark.asyncio async def test_list_active_without_labels_sends_no_selector( self, mocker: MockerFixture @@ -1463,6 +1626,7 @@ async def test_list_active_without_labels_sends_no_selector( workspace=spawner._workspace, label_selector=None, limit=1000, + offset=0, ) @pytest.mark.asyncio diff --git a/tests/unit/workflow/temporal/test_activities.py b/tests/unit/workflow/temporal/test_activities.py index 9c7b9ff..a59f549 100644 --- a/tests/unit/workflow/temporal/test_activities.py +++ b/tests/unit/workflow/temporal/test_activities.py @@ -375,6 +375,51 @@ async def test_permissions_service_account_passed(self, mocker: MockerFixture) - env_vars = spawn_call[1].get("env", {}) assert env_vars.get("LIGHTSPEED_SERVICE_ACCOUNT") == "custom-sa" + @pytest.mark.asyncio + async def test_spawn_gets_per_step_lifetime(self, mocker: MockerFixture) -> None: + """The sandbox's lifetime covers this step's enforced run deadline + (permissions.timeout_seconds), so a long run's expires-at outlasts it.""" + from cloud_agents.spawner.lifetime import step_sandbox_lifetime_seconds + + mock_spawner = mocker.AsyncMock() + mock_spawner.spawn.return_value = "http://pod-1:8080" + mock_spawner.wait_ready.return_value = True + + mock_response = mocker.MagicMock() + mock_response.status_code = 200 + mock_response.json.return_value = {"success": True, "output": {}} + + mock_http = mocker.patch( + "cloud_agents.workflow.executor.temporal.activities.httpx.AsyncClient", + ) + mock_http.return_value.__aenter__ = mocker.AsyncMock( + return_value=mocker.MagicMock( + post=mocker.AsyncMock(return_value=mock_response), + ), + ) + mock_http.return_value.__aexit__ = mocker.AsyncMock(return_value=False) + + step = { + "name": "s1", + "prompt": "check", + "output_key": "r1", + "permissions": {"timeout_seconds": 200_000}, + } + await run_sandbox_step( + { + "step": step, + "workflow_id": "wf-1", + "provider": {"name": "openai", "model": "gpt-4", "credentials_secret": "k"}, + "sandbox_image": "sandbox:latest", + "context": {}, + }, + spawner=mock_spawner, + ) + + lifetime = mock_spawner.spawn.call_args.kwargs["lifetime_seconds"] + assert lifetime == step_sandbox_lifetime_seconds(step) + assert lifetime >= 200_000 + @pytest.mark.asyncio async def test_permissions_timeout_overrides_default(self, mocker: MockerFixture) -> None: """Permissions timeout_seconds overrides default HTTP timeout.""" @@ -417,7 +462,9 @@ async def test_permissions_timeout_overrides_default(self, mocker: MockerFixture spawner=mock_spawner, ) - http_init_call = mock_http.call_args + # First client is the POST /v1/agent/run; the transcript fetch after it + # uses its own short timeout. + http_init_call = mock_http.call_args_list[0] assert http_init_call[1].get("timeout") == 120.0 diff --git a/tests/unit/workflow/temporal/test_cleanup_metrics.py b/tests/unit/workflow/temporal/test_cleanup_metrics.py index c1a3d00..d1f2e51 100644 --- a/tests/unit/workflow/temporal/test_cleanup_metrics.py +++ b/tests/unit/workflow/temporal/test_cleanup_metrics.py @@ -104,7 +104,10 @@ async def test_orphan_cleanup_increments_counter(self, mocker: MockerFixture) -> from cloud_agents.workflow.executor.temporal.entrypoint import reconcile_orphaned_sandboxes mock_spawner = mocker.AsyncMock() - mock_spawner.list_active.return_value = ["orphan-1", "orphan-2"] + mock_spawner.list_sandbox_labels.return_value = [ + ("orphan-1", {"cloud-agents/expires-at": "1"}), + ("orphan-2", {"cloud-agents/expires-at": "1"}), + ] before = _get_counter_value("ls_sandbox_orphans_cleaned") @@ -119,7 +122,7 @@ async def test_no_orphans_no_increment(self, mocker: MockerFixture) -> None: from cloud_agents.workflow.executor.temporal.entrypoint import reconcile_orphaned_sandboxes mock_spawner = mocker.AsyncMock() - mock_spawner.list_active.return_value = [] + mock_spawner.list_sandbox_labels.return_value = [] before = _get_counter_value("ls_sandbox_orphans_cleaned") @@ -136,7 +139,11 @@ async def test_partial_destroy_failure_counts_only_successes( from cloud_agents.workflow.executor.temporal.entrypoint import reconcile_orphaned_sandboxes mock_spawner = mocker.AsyncMock() - mock_spawner.list_active.return_value = ["orphan-ok", "orphan-fail", "orphan-ok2"] + mock_spawner.list_sandbox_labels.return_value = [ + ("orphan-ok", {"cloud-agents/expires-at": "1"}), + ("orphan-fail", {"cloud-agents/expires-at": "1"}), + ("orphan-ok2", {"cloud-agents/expires-at": "1"}), + ] call_count = 0 @@ -146,7 +153,7 @@ async def destroy_side_effect(name: str) -> None: if name == "orphan-fail": raise RuntimeError("destroy failed") - mock_spawner.destroy.side_effect = destroy_side_effect + mock_spawner.destroy_sandbox.side_effect = destroy_side_effect before = _get_counter_value("ls_sandbox_orphans_cleaned") diff --git a/tests/unit/workflow/temporal/test_progress_streaming.py b/tests/unit/workflow/temporal/test_progress_streaming.py index 7f56f06..5ad4b03 100644 --- a/tests/unit/workflow/temporal/test_progress_streaming.py +++ b/tests/unit/workflow/temporal/test_progress_streaming.py @@ -53,8 +53,17 @@ def _mock_http_success(mocker: MockerFixture) -> MagicMock: mock_http = mocker.patch( "cloud_agents.workflow.executor.temporal.activities.httpx.AsyncClient", ) + + async def post(*args, **kwargs): + # A real agent run takes time; yield so the progress task gets to run + # (an AsyncMock returns without ever suspending). + await asyncio.sleep(0.05) + return mock_response + mock_client_instance = mocker.MagicMock( - post=mocker.AsyncMock(return_value=mock_response), + post=mocker.AsyncMock(side_effect=post), + # The transcript fetch runs after every successful run. + get=mocker.AsyncMock(return_value=mocker.MagicMock(status_code=404)), ) mock_http.return_value.__aenter__ = mocker.AsyncMock( return_value=mock_client_instance, @@ -193,6 +202,9 @@ class TestGracefulDegradation: async def test_non_openshell_spawner_skips_progress(self, mocker: MockerFixture) -> None: """Non-OpenShell spawners skip progress streaming entirely.""" mock_spawner = mocker.AsyncMock() + # Sync on the real spawner; an AsyncMock attribute would return an + # un-awaited coroutine. + mock_spawner.get_query_ssl_context = mocker.Mock(return_value=None) mock_spawner.spawn.return_value = "http://pod-1:8080" mock_spawner.wait_ready.return_value = True @@ -218,6 +230,9 @@ async def test_non_openshell_spawner_no_progress(self, mocker: MockerFixture) -> # Just verify isinstance check works by using a plain AsyncMock # (which is not an OpenShellSpawner) mock_spawner = mocker.AsyncMock() + # Sync on the real spawner; an AsyncMock attribute would return an + # un-awaited coroutine. + mock_spawner.get_query_ssl_context = mocker.Mock(return_value=None) mock_spawner.spawn.return_value = "http://pod-1:8080" mock_spawner.wait_ready.return_value = True diff --git a/tests/unit/workflow/temporal/test_startup_reconciliation.py b/tests/unit/workflow/temporal/test_startup_reconciliation.py index 47debd6..6c8db6b 100644 --- a/tests/unit/workflow/temporal/test_startup_reconciliation.py +++ b/tests/unit/workflow/temporal/test_startup_reconciliation.py @@ -2,62 +2,649 @@ from __future__ import annotations -from unittest.mock import AsyncMock +import asyncio +import threading +import time +from typing import Any +from unittest.mock import AsyncMock, MagicMock import pytest +from cloud_agents.workflow.executor.temporal import entrypoint from cloud_agents.workflow.executor.temporal.entrypoint import reconcile_orphaned_sandboxes +AGENT_KEY = "cloud-agents/agent-name" +EXPIRES_KEY = "cloud-agents/expires-at" +NOW = 1_700_000_000.0 +PAST = str(int(NOW) - 1) +FUTURE = str(int(NOW) + 3600) + + +def _fake_spawner(sandboxes: dict[str, dict[str, str]]) -> AsyncMock: + """Spawner whose list_sandbox_labels() returns sandboxes as-is. + + sandboxes maps gateway sandbox name -> labels beyond spawned-by (an empty + dict is a legacy sandbox carrying only spawned-by=workflow-runner). + """ + spawner = AsyncMock() + + async def list_sandbox_labels(labels: dict[str, str] | None = None): + assert labels == {"spawned-by": "workflow-runner"} + return [ + (name, {"spawned-by": "workflow-runner", **extra}) for name, extra in sandboxes.items() + ] + + spawner.list_sandbox_labels.side_effect = list_sandbox_labels + return spawner + + +def _destroyed(spawner: AsyncMock) -> set[str]: + return {c.args[0] for c in spawner.destroy_sandbox.call_args_list} + class TestStartupReconciliation: - """Tests for reconcile_orphaned_sandboxes.""" + """reconcile_orphaned_sandboxes() destroys expired sandboxes only.""" + + @pytest.mark.asyncio + async def test_expired_sandboxes_destroyed_by_exact_name(self) -> None: + mock_spawner = _fake_spawner( + {"sb-old1": {EXPIRES_KEY: PAST}, "sb-old2": {EXPIRES_KEY: PAST}} + ) + + await reconcile_orphaned_sandboxes(mock_spawner, now=NOW) + + mock_spawner.list_sandbox_labels.assert_called_once() + mock_spawner.destroy.assert_not_called() + assert _destroyed(mock_spawner) == {"sb-old1", "sb-old2"} @pytest.mark.asyncio - async def test_orphaned_containers_destroyed_on_startup(self) -> None: - """Startup reconciliation destroys orphaned sandbox containers.""" - mock_spawner = AsyncMock() - mock_spawner.list_active.return_value = ["ca-orphan1", "ca-orphan2"] + async def test_unexpired_sandboxes_survive(self) -> None: + mock_spawner = _fake_spawner({"sb-live": {EXPIRES_KEY: FUTURE}}) + + await reconcile_orphaned_sandboxes(mock_spawner, now=NOW) - await reconcile_orphaned_sandboxes(mock_spawner) + mock_spawner.destroy_sandbox.assert_not_called() - mock_spawner.list_active.assert_called_once_with( - {"spawned-by": "workflow-runner"}, + @pytest.mark.asyncio + async def test_owner_label_never_triggers_destroy(self) -> None: + """A matching runner identity doesn't prove the previous owner is + dead, so an owner-instance label (left by an earlier build) is + ignored: unexpired sandboxes survive whatever their owner label.""" + mock_spawner = _fake_spawner( + {"sb-live": {"cloud-agents/owner-instance": "runner-a", EXPIRES_KEY: FUTURE}} ) - assert mock_spawner.destroy.call_count == 2 - mock_spawner.destroy.assert_any_call("ca-orphan1") - mock_spawner.destroy.assert_any_call("ca-orphan2") + + await reconcile_orphaned_sandboxes(mock_spawner, now=NOW) + + mock_spawner.destroy_sandbox.assert_not_called() + + @pytest.mark.asyncio + async def test_malformed_expires_at_kept_and_logged(self, caplog) -> None: + mock_spawner = _fake_spawner({"sb-weird": {EXPIRES_KEY: "soon"}}) + + with caplog.at_level("WARNING"): + await reconcile_orphaned_sandboxes(mock_spawner, now=NOW) + + mock_spawner.destroy_sandbox.assert_not_called() + assert "sb-weird" in caplog.text + + @pytest.mark.asyncio + async def test_sandboxes_without_expiry_left_alone_and_logged(self, caplog) -> None: + mock_spawner = _fake_spawner({"sb-legacy": {}, "sb-cli": {AGENT_KEY: "cli-1"}}) + + with caplog.at_level("INFO"): + await reconcile_orphaned_sandboxes(mock_spawner, now=NOW) + + mock_spawner.destroy_sandbox.assert_not_called() + assert "2 sandbox(es)" in caplog.text @pytest.mark.asyncio async def test_no_orphans_no_destroy(self) -> None: - """Startup with no orphans calls no destroy.""" - mock_spawner = AsyncMock() - mock_spawner.list_active.return_value = [] + mock_spawner = _fake_spawner({}) - await reconcile_orphaned_sandboxes(mock_spawner) + await reconcile_orphaned_sandboxes(mock_spawner, now=NOW) - mock_spawner.list_active.assert_called_once_with( - {"spawned-by": "workflow-runner"}, - ) - mock_spawner.destroy.assert_not_called() + mock_spawner.destroy_sandbox.assert_not_called() @pytest.mark.asyncio async def test_destroy_failure_logged_not_raised(self) -> None: """If destroy fails for one orphan, others are still attempted.""" - mock_spawner = AsyncMock() - mock_spawner.list_active.return_value = ["orphan1", "orphan2", "orphan3"] - mock_spawner.destroy.side_effect = [ - None, - RuntimeError("destroy failed"), - None, - ] + mock_spawner = _fake_spawner({n: {EXPIRES_KEY: PAST} for n in ("o1", "o2", "o3")}) + mock_spawner.destroy_sandbox.side_effect = [None, RuntimeError("destroy failed"), None] # Should not raise - await reconcile_orphaned_sandboxes(mock_spawner) + await reconcile_orphaned_sandboxes(mock_spawner, now=NOW) - assert mock_spawner.destroy.call_count == 3 + assert mock_spawner.destroy_sandbox.call_count == 3 @pytest.mark.asyncio async def test_none_spawner_is_noop(self) -> None: """reconcile_orphaned_sandboxes with None spawner does nothing.""" # Should not raise await reconcile_orphaned_sandboxes(None) + + +class TestNoRunnerIdentity: + """The owner-identity mechanism is gone: nothing resolves or stamps it.""" + + def test_entrypoint_has_no_identity_resolution(self) -> None: + assert not hasattr(entrypoint, "_runner_instance_id") + + def test_create_spawner_passes_no_owner(self, mocker, monkeypatch) -> None: + mocker.patch.object(entrypoint, "SPAWNER_TYPE", "openshell") + build = mocker.patch("cloud_agents.spawner.factory.build_spawner") + + entrypoint._create_spawner() + + assert "owner_instance" not in build.call_args.kwargs + + +class TestSandboxLifetimeSettings: + """SANDBOX_MIN_LIFETIME_SECONDS / SANDBOX_EXPIRY_SKEW_SECONDS parsing.""" + + def test_defaults(self, monkeypatch) -> None: + monkeypatch.delenv("SANDBOX_MIN_LIFETIME_SECONDS", raising=False) + monkeypatch.delenv("SANDBOX_EXPIRY_SKEW_SECONDS", raising=False) + assert entrypoint._sandbox_min_lifetime_seconds() == 86400 + assert entrypoint._sandbox_expiry_skew_seconds() == 600 + + def test_configured(self, monkeypatch) -> None: + monkeypatch.setenv("SANDBOX_MIN_LIFETIME_SECONDS", "60") + monkeypatch.setenv("SANDBOX_EXPIRY_SKEW_SECONDS", "0") + assert entrypoint._sandbox_min_lifetime_seconds() == 60 + assert entrypoint._sandbox_expiry_skew_seconds() == 0 + + @pytest.mark.parametrize("bad", ["abc", "-5", "1.5"]) + def test_invalid_min_lifetime_fails_startup(self, monkeypatch, bad) -> None: + monkeypatch.setenv("SANDBOX_MIN_LIFETIME_SECONDS", bad) + with pytest.raises(ValueError, match="SANDBOX_MIN_LIFETIME_SECONDS"): + entrypoint._sandbox_min_lifetime_seconds() + + @pytest.mark.parametrize("bad", ["abc", "-1"]) + def test_invalid_skew_fails_startup(self, monkeypatch, bad) -> None: + monkeypatch.setenv("SANDBOX_EXPIRY_SKEW_SECONDS", bad) + with pytest.raises(ValueError, match="SANDBOX_EXPIRY_SKEW_SECONDS"): + entrypoint._sandbox_expiry_skew_seconds() + + def test_settings_passed_to_spawner(self, mocker, monkeypatch) -> None: + mocker.patch.object(entrypoint, "SPAWNER_TYPE", "openshell") + monkeypatch.setenv("SANDBOX_MIN_LIFETIME_SECONDS", "7200") + monkeypatch.setenv("SANDBOX_EXPIRY_SKEW_SECONDS", "45") + build = mocker.patch("cloud_agents.spawner.factory.build_spawner") + + entrypoint._create_spawner() + + assert build.call_args.kwargs["min_lifetime_seconds"] == 7200 + assert build.call_args.kwargs["expiry_skew_seconds"] == 45 + + +# --- Real OpenShellSpawner against a fake gateway --------------------------- + + +class _FakeRef: + def __init__(self, name: str, labels: dict[str, str]): + self.name = name + self.id = f"id-{name}" + self.labels = labels + + +class _FakeGateway: + """Minimal stand-in for openshell.SandboxClient's sandbox CRUD.""" + + def __init__(self, refs: list[_FakeRef] | None = None, create_delay: float = 0.0): + self.refs = {r.name: r for r in refs or []} + self.deleted: list[str] = [] + self.create_delay = create_delay + self.created = threading.Event() + self._n = 0 + + def list(self, *, workspace, label_selector=None, limit=100, offset=0): + wanted = dict(p.split("=", 1) for p in (label_selector or "").split(",") if p) + matches = [ + r for r in self.refs.values() if all(r.labels.get(k) == v for k, v in wanted.items()) + ] + return matches[offset : offset + limit] + + def delete(self, name, *, workspace): + self.deleted.append(name) + self.refs.pop(name, None) + + def create(self, *, workspace, spec, labels): + time.sleep(self.create_delay) + self._n += 1 + ref = _FakeRef(f"sb-{self._n}", dict(labels)) + self.refs[ref.name] = ref + self.created.set() + return ref + + def wait_ready(self, name, *, workspace, timeout_seconds): + return self.refs[name] + + def exec_stream(self, *args, **kwargs): + return iter([]) + + +class _RecordingClock: + """Real (advancing) wall clock that records each reading.""" + + def __init__(self) -> None: + self.readings: list[float] = [] + + def __call__(self) -> float: + value = time.time() + self.readings.append(value) + return value + + +def _real_spawner(mocker, gateway: _FakeGateway, **kwargs: Any): + from cloud_agents.spawner.openshell_spawner import OpenShellSpawner + + spawner = OpenShellSpawner(openshell_client=gateway, **kwargs) + mocker.patch.object(spawner, "_expose_service", return_value=("http://gw", "host")) + mocker.patch.object(spawner, "_wait_ready_with_host", return_value=True) + mocker.patch.object(OpenShellSpawner, "_build_network_policy") + return spawner + + +def _labels(agent: str, expires_at: str | None = None) -> dict[str, str]: + labels = {"spawned-by": "workflow-runner", AGENT_KEY: agent} + if expires_at is not None: + labels[EXPIRES_KEY] = expires_at + return labels + + +class TestExactDeletionRealSpawner: + """Reconcile deletes exactly the expired gateway ref, never other refs + that merely share its cloud-agents/agent-name label.""" + + @pytest.mark.asyncio + async def test_same_agent_name_only_expired_ref_deleted(self, mocker) -> None: + gateway = _FakeGateway( + [ + _FakeRef("sb-expired", _labels("ca-dup", PAST)), + _FakeRef("sb-live", _labels("ca-dup", FUTURE)), + ] + ) + spawner = _real_spawner(mocker, gateway) + + await reconcile_orphaned_sandboxes(spawner, now=NOW) + + assert gateway.deleted == ["sb-expired"] + + @pytest.mark.asyncio + async def test_expired_and_legacy_same_agent_only_expired_deleted(self, mocker) -> None: + gateway = _FakeGateway( + [ + _FakeRef("sb-expired", _labels("ca-dup", PAST)), + _FakeRef("sb-legacy", _labels("ca-dup")), + ] + ) + spawner = _real_spawner(mocker, gateway) + + await reconcile_orphaned_sandboxes(spawner, now=NOW) + + assert gateway.deleted == ["sb-expired"] + + @pytest.mark.asyncio + async def test_expired_and_unlabelled_legacy_only_expired_deleted(self, mocker) -> None: + gateway = _FakeGateway( + [ + _FakeRef("sb-expired", _labels("ca-a", PAST)), + _FakeRef("sb-legacy", {"spawned-by": "workflow-runner"}), + ] + ) + spawner = _real_spawner(mocker, gateway) + + await reconcile_orphaned_sandboxes(spawner, now=NOW) + + assert gateway.deleted == ["sb-expired"] + + +class TestReconcileWithoutExactDestroy: + @pytest.mark.asyncio + async def test_spawner_without_destroy_sandbox_is_skipped_and_logged(self, caplog) -> None: + """A spawner that lists labels but doesn't implement exact deletion is + skipped, never falling back to agent-name destroy().""" + from cloud_agents.spawner.base import AgentSpawner + + class ListOnlySpawner(AgentSpawner): + destroyed: list[str] = [] + + async def _do_spawn(self, *args, **kwargs): + return "" + + async def _do_destroy(self, agent_name): + self.destroyed.append(agent_name) + + async def _do_list_active(self, labels=None): + return [] + + async def _do_list_sandbox_labels(self, labels=None): + return [("sb-expired", {EXPIRES_KEY: PAST})] + + async def _do_read_file(self, agent_name, path): + raise FileNotFoundError(path) + + async def _do_write_file(self, agent_name, path, content): + pass + + spawner = ListOnlySpawner() + with caplog.at_level("WARNING"): + await reconcile_orphaned_sandboxes(spawner, now=NOW) + + assert spawner.destroyed == [] + assert "sb-expired" in caplog.text + + +class TestCancelledSpawnRealSpawner: + @pytest.mark.asyncio + async def test_cancel_after_create_deletes_exact_sandbox(self, mocker) -> None: + gateway = _FakeGateway() + spawner = _real_spawner(mocker, gateway) + + async def hang(*args, **kwargs): + await asyncio.sleep(3600) + + mocker.patch.object(spawner, "start_server", side_effect=hang) + task = asyncio.create_task(spawner.spawn("ca-agent", "img", env={}, lifetime_seconds=60)) + assert await asyncio.to_thread(gateway.created.wait, 5) + await asyncio.sleep(0.05) + task.cancel() + + with pytest.raises(asyncio.CancelledError): + await task + assert gateway.deleted == ["sb-1"] + assert spawner._active_count == 0 + assert spawner._sandbox_names == {} + + +class TestSpawnDeadlineRealSpawner: + """The spawn budget starts when expires-at is stamped and bounds create + plus every post-create phase, so a sandbox whose lifetime covers the + budget is never reaped before its spawn could have finished using it. + + Uses min_lifetime=0, skew=0 and lifetime_seconds == the (patched) + budget + cancel grace, so expires-at is exactly as early as the bound + allows. + """ + + DEADLINE = 1 + GRACE = 1 + STUBBORN = 2.5 # how long "uncooperative" code ignores cancellation + + @pytest.fixture(autouse=True) + def _short_deadline(self, mocker): + import cloud_agents.spawner.openshell_spawner as mod + from cloud_agents.spawner import lifetime + + mocker.patch.object(mod, "SANDBOX_SPAWN_DEADLINE_SECONDS", self.DEADLINE) + mocker.patch.object(lifetime, "SANDBOX_CANCEL_GRACE_SECONDS", self.GRACE) + + async def _spawn_expecting_timeout(self, spawner) -> float: + start = time.monotonic() + with pytest.raises(TimeoutError) as exc_info: + await asyncio.wait_for( + spawner.spawn( + "ca-agent", "img", env={}, lifetime_seconds=self.DEADLINE + self.GRACE + ), + timeout=10, + ) + assert "deadline" in str(exc_info.value) + return time.monotonic() - start + + async def _assert_not_reaped_before_budget_end(self, gateway, clock, name) -> None: + stamp = clock.readings[0] + expires_at = gateway.refs[name].labels[EXPIRES_KEY] + reader = _FakeGateway([gateway.refs[name]]) + from cloud_agents.spawner.openshell_spawner import OpenShellSpawner + + other = OpenShellSpawner(openshell_client=reader) + await reconcile_orphaned_sandboxes(other, now=stamp + self.DEADLINE + self.GRACE) + assert reader.deleted == [] + await reconcile_orphaned_sandboxes(other, now=int(expires_at) + 1) + assert reader.deleted == [name] + + @pytest.mark.asyncio + async def test_trickling_health_check_aborted_by_deadline(self, mocker) -> None: + gateway = _FakeGateway() + clock = _RecordingClock() + spawner = _real_spawner( + mocker, gateway, min_lifetime_seconds=0, expiry_skew_seconds=0, clock=clock + ) + + async def trickle(*args, **kwargs): + await asyncio.sleep(3600) + + mocker.patch.object(spawner, "_wait_ready_with_host", side_effect=trickle) + created = {} + real_create = gateway.create + + def create(**kwargs): + ref = real_create(**kwargs) + created["ref"] = _FakeRef(ref.name, dict(ref.labels)) + return ref + + gateway.create = create + + elapsed = await self._spawn_expecting_timeout(spawner) + + assert elapsed < self.DEADLINE + 1 + assert gateway.deleted == [created["ref"].name] # exact, known identity + gateway.refs[created["ref"].name] = created["ref"] + await self._assert_not_reaped_before_budget_end(gateway, clock, created["ref"].name) + + @pytest.mark.asyncio + async def test_slow_post_create_step_aborted_by_deadline(self, mocker) -> None: + gateway = _FakeGateway() + clock = _RecordingClock() + spawner = _real_spawner( + mocker, gateway, min_lifetime_seconds=0, expiry_skew_seconds=0, clock=clock + ) + + async def hang(*args, **kwargs): + await asyncio.sleep(3600) + + mocker.patch.object(spawner, "start_server", side_effect=hang) + + elapsed = await self._spawn_expecting_timeout(spawner) + + assert elapsed < self.DEADLINE + 1 + assert gateway.deleted == ["sb-1"] + + @pytest.mark.asyncio + async def test_slow_create_sandbox_bounded_and_left_to_expiry(self, mocker) -> None: + """CreateSandbox outlives the budget: spawn still returns by the + deadline. Cancelling the awaiting coroutine doesn't stop the blocking + RPC, so the sandbox may still appear afterwards -- with an expiry no + earlier than the budget end, so it's reaped only once expired. With + its identity unknown, no delete is guessed.""" + gateway = _FakeGateway(create_delay=self.DEADLINE + 1) + clock = _RecordingClock() + spawner = _real_spawner( + mocker, gateway, min_lifetime_seconds=0, expiry_skew_seconds=0, clock=clock + ) + + elapsed = await self._spawn_expecting_timeout(spawner) + + assert elapsed < self.DEADLINE + 1 + assert gateway.deleted == [] + assert await asyncio.to_thread(gateway.created.wait, 5) + await self._assert_not_reaped_before_budget_end(gateway, clock, "sb-1") + + @staticmethod + async def _stubborn_sleep(seconds: float) -> None: + end = time.monotonic() + seconds + while (remaining := end - time.monotonic()) > 0: + try: + await asyncio.sleep(remaining) + except asyncio.CancelledError: + pass + + @pytest.mark.asyncio + async def test_readiness_close_ignoring_cancellation_bounded_by_grace(self, mocker) -> None: + """The readiness check overruns the budget and its client close then + ignores cancellation: spawn still raises within budget + grace, and + deletes the exact sandbox it created.""" + gateway = _FakeGateway() + clock = _RecordingClock() + spawner = _real_spawner( + mocker, gateway, min_lifetime_seconds=0, expiry_skew_seconds=0, clock=clock + ) + + async def readiness_with_stuck_close(*args, **kwargs): + try: + await asyncio.sleep(3600) + except asyncio.CancelledError: + await self._stubborn_sleep(self.STUBBORN) # e.g. client __aexit__ + raise + + mocker.patch.object( + spawner, "_wait_ready_with_host", side_effect=readiness_with_stuck_close + ) + snapshot = {} + real_create = gateway.create + + def create(**kwargs): + ref = real_create(**kwargs) + snapshot["ref"] = _FakeRef(ref.name, dict(ref.labels)) + return ref + + gateway.create = create + + elapsed = await self._spawn_expecting_timeout(spawner) + + assert elapsed < self.DEADLINE + self.GRACE + 0.5 + assert gateway.deleted == ["sb-1"] + gateway.refs["sb-1"] = snapshot["ref"] + await self._assert_not_reaped_before_budget_end(gateway, clock, "sb-1") + await asyncio.sleep(self.STUBBORN) # let the abandoned close finish + + @pytest.mark.asyncio + async def test_stuck_failure_cleanup_bounded_and_logged(self, mocker, caplog) -> None: + """A failure-path cleanup that hangs (ignoring cancellation) is + abandoned and logged; the caller gets the original error promptly.""" + import cloud_agents.spawner.openshell_spawner as mod + + mocker.patch.object(mod, "SANDBOX_SPAWN_CLEANUP_TIMEOUT_SECONDS", 0.2, create=True) + gateway = _FakeGateway() + spawner = _real_spawner(mocker, gateway) + mocker.patch.object(spawner, "start_server", side_effect=RuntimeError("boom")) + + async def stuck_cleanup(*args, **kwargs): + await self._stubborn_sleep(self.STUBBORN) + + mocker.patch.object(spawner, "_cleanup_sandbox", side_effect=stuck_cleanup) + + start = time.monotonic() + with caplog.at_level("WARNING"), pytest.raises(RuntimeError, match="boom"): + await asyncio.wait_for( + spawner.spawn("ca-agent", "img", env={}, lifetime_seconds=60), timeout=10 + ) + + assert time.monotonic() - start < 0.2 + self.GRACE + 0.5 + assert "abandon" in caplog.text + await asyncio.sleep(self.STUBBORN) + + @pytest.mark.asyncio + async def test_own_timeout_error_not_reported_as_deadline(self, mocker) -> None: + """A TimeoutError raised by a spawn phase itself, well before the + budget expires, propagates as-is rather than as a deadline overrun.""" + gateway = _FakeGateway() + spawner = _real_spawner(mocker, gateway) + mocker.patch.object(spawner, "start_server", side_effect=TimeoutError("exec timed out")) + + with pytest.raises(TimeoutError) as exc_info: + await asyncio.wait_for( + spawner.spawn("ca-agent", "img", env={}, lifetime_seconds=60), timeout=10 + ) + + assert str(exc_info.value) == "exec timed out" + assert gateway.deleted == ["sb-1"] + + +class TestMcpSecretsInsideSpawnBudget: + """MCP secret files (#277) are written inside the spawn budget, so their + failures go through the bounded, exact-sandbox cleanup.""" + + MOUNTS = [("MCP_TOKEN", "token", "/run/mcp/token")] + + @pytest.mark.asyncio + async def test_failed_secret_write_deletes_exact_sandbox(self, mocker) -> None: + gateway = _FakeGateway() + spawner = _real_spawner(mocker, gateway) + mocker.patch.object(spawner, "_exec_mkdir", return_value=None) + mocker.patch.object(spawner, "_write_secret_file", side_effect=RuntimeError("write failed")) + + with pytest.raises(RuntimeError, match="write failed"): + await spawner.spawn( + "ca-agent", + "img", + env={"MCP_TOKEN": "s3cret"}, + lifetime_seconds=60, + mcp_secret_mounts=self.MOUNTS, + ) + + assert gateway.deleted == ["sb-1"] + assert spawner._active_count == 0 + + @pytest.mark.asyncio + async def test_hanging_secret_write_bounded_by_spawn_budget(self, mocker) -> None: + import cloud_agents.spawner.openshell_spawner as mod + + mocker.patch.object(mod, "SANDBOX_SPAWN_DEADLINE_SECONDS", 1) + gateway = _FakeGateway() + spawner = _real_spawner(mocker, gateway) + mocker.patch.object(spawner, "_exec_mkdir", return_value=None) + + async def hang(*args, **kwargs): + await asyncio.sleep(3600) + + mocker.patch.object(spawner, "_write_secret_file", side_effect=hang) + + start = time.monotonic() + with pytest.raises(TimeoutError, match="deadline"): + await asyncio.wait_for( + spawner.spawn( + "ca-agent", + "img", + env={"MCP_TOKEN": "s3cret"}, + lifetime_seconds=60, + mcp_secret_mounts=self.MOUNTS, + ), + timeout=10, + ) + + assert time.monotonic() - start < 2 + assert gateway.deleted == ["sb-1"] + + @pytest.mark.asyncio + async def test_secret_key_kept_out_of_spec_environment(self, mocker) -> None: + gateway = _FakeGateway() + spawner = _real_spawner(mocker, gateway) + mocker.patch.object(spawner, "_exec_mkdir", return_value=None) + mocker.patch.object(spawner, "_write_secret_file", return_value=None) + seen: dict[str, dict[str, str]] = {} + real_create = gateway.create + + def create(**kwargs): + environment = kwargs["spec"].environment + if isinstance(environment, MagicMock): + # test_openshell_spawner.py may have stubbed `openshell` for + # the whole session; read the map writes off the mock. + seen["env"] = {c.args[0]: c.args[1] for c in environment.__setitem__.call_args_list} + else: + seen["env"] = dict(environment) + return real_create(**kwargs) + + gateway.create = create + + await spawner.spawn( + "ca-agent", + "img", + env={"MCP_TOKEN": "s3cret", "PLAIN": "ok"}, + lifetime_seconds=60, + mcp_secret_mounts=self.MOUNTS, + ) + + assert "MCP_TOKEN" not in seen["env"] + assert seen["env"]["PLAIN"] == "ok" diff --git a/tests/unit/workflow/test_bounded_io.py b/tests/unit/workflow/test_bounded_io.py new file mode 100644 index 0000000..4f9bb4b --- /dev/null +++ b/tests/unit/workflow/test_bounded_io.py @@ -0,0 +1,319 @@ +"""Sandbox I/O stays inside its advertised budget even when cleanup stalls. + +Each phase runs as a task waited on for at most its deadline, then at most a +short cancel grace; a task still running after that is abandoned (never +awaited again) and the step doesn't go on to touch the sandbox. Parameterized +over the local (step_runner.run_step) and Temporal (run_sandbox_step) engines. +""" + +from __future__ import annotations + +import asyncio +import importlib +import os +import time +from typing import Any + +import pytest +from pytest_mock import MockerFixture + +GRACE = 0.1 +RUN_TIMEOUT = 0.2 +STUBBORN = 0.6 # how long "uncooperative" code ignores cancellation + +ENGINES = ["local", "temporal"] + + +def _module(engine: str): + return importlib.import_module( + "cloud_agents.workflow.core.step_runner" + if engine == "local" + else "cloud_agents.workflow.executor.temporal.activities" + ) + + +async def _stubborn_sleep(seconds: float) -> None: + """Sleep for `seconds`, ignoring cancellation meanwhile.""" + end = time.monotonic() + seconds + while (remaining := end - time.monotonic()) > 0: + try: + await asyncio.sleep(remaining) + except asyncio.CancelledError: + pass + + +class _FakeClientCM: + """httpx.AsyncClient stand-in whose __aexit__ can stall.""" + + def __init__(self, client: Any, aexit=None) -> None: + self.client = client + self.aexit = aexit + + async def __aenter__(self): + return self.client + + async def __aexit__(self, *exc): + if self.aexit is not None: + await self.aexit() + return False + + +@pytest.fixture(autouse=True) +def _short_grace(mocker): + from cloud_agents.spawner import lifetime + + mocker.patch.object(lifetime, "SANDBOX_CANCEL_GRACE_SECONDS", GRACE, create=True) + mocker.patch.dict(os.environ, {"OPENAI_API_KEY": "sk-test"}, clear=False) + + +def _spawner(mocker): + spawner = mocker.AsyncMock() + spawner.spawn.return_value = "http://pod-1:8080" + spawner.wait_ready.return_value = True + spawner.get_query_ssl_context = mocker.Mock(return_value=None) + return spawner + + +def _ok_response(mocker): + response = mocker.MagicMock(status_code=200) + response.json.return_value = {"success": True, "output": {}} + return response + + +def _step_input(run_timeout: float | None = RUN_TIMEOUT) -> dict[str, Any]: + step: dict[str, Any] = {"name": "s", "prompt": "p", "output_key": "o"} + if run_timeout is not None: + step["permissions"] = {"timeout_seconds": run_timeout} + return { + "step": step, + "workflow_id": "wf-1", + "provider": {"name": "openai", "model": "gpt-4o", "credentials_secret": "k"}, + "sandbox_image": "sandbox:latest", + "context": {}, + } + + +def _run(engine: str, mod, step_input, spawner, **kwargs): + if engine == "local": + return mod.run_step(step_input, spawner=spawner, attempt=1, **kwargs) + return mod.run_sandbox_step(step_input, spawner=spawner, **kwargs) + + +async def _timed(coro) -> tuple[float, Any, BaseException | None]: + start = time.monotonic() + try: + result, error = await asyncio.wait_for(coro, timeout=10), None + except Exception as exc: # noqa: BLE001 - the error is the assertion subject + result, error = None, exc + return time.monotonic() - start, result, error + + +class TestRunCallBounded: + @pytest.mark.asyncio + @pytest.mark.parametrize("engine", ENGINES) + async def test_post_times_out_then_close_stalls(self, mocker: MockerFixture, engine) -> None: + """(a) The POST overruns its deadline and the client close then ignores + cancellation: the step still ends within run timeout + grace, and no + transcript access happens afterwards.""" + mod = _module(engine) + get = mocker.AsyncMock() + + async def hang(*args, **kwargs): + await asyncio.sleep(3600) + + client = mocker.MagicMock(post=hang, get=get) + mocker.patch( + f"{mod.__name__}.httpx.AsyncClient", + side_effect=lambda **kw: _FakeClientCM(client, lambda: _stubborn_sleep(STUBBORN)), + ) + + elapsed, _, error = await _timed(_run(engine, mod, _step_input(), _spawner(mocker))) + + assert isinstance(error, (TimeoutError, RuntimeError)) + assert "timed out" in str(error) + assert elapsed < RUN_TIMEOUT + GRACE + 0.3 + get.assert_not_called() + await asyncio.sleep(STUBBORN) # let the abandoned close finish + + @pytest.mark.asyncio + @pytest.mark.parametrize("engine", ENGINES) + async def test_post_succeeds_then_close_stalls(self, mocker: MockerFixture, engine) -> None: + """The run deadline covers the client's __aexit__ too.""" + mod = _module(engine) + get = mocker.AsyncMock() + client = mocker.MagicMock(post=mocker.AsyncMock(return_value=_ok_response(mocker)), get=get) + + async def stall(): + await asyncio.sleep(3600) + + mocker.patch( + f"{mod.__name__}.httpx.AsyncClient", + side_effect=lambda **kw: _FakeClientCM(client, stall), + ) + + elapsed, _, error = await _timed(_run(engine, mod, _step_input(), _spawner(mocker))) + + assert error is not None and "timed out" in str(error) + assert elapsed < RUN_TIMEOUT + GRACE + 0.3 + get.assert_not_called() + + +class TestProgressCleanupBounded: + @pytest.mark.asyncio + @pytest.mark.parametrize("engine", ENGINES) + async def test_progress_task_ignoring_cancellation_is_abandoned( + self, mocker: MockerFixture, engine + ) -> None: + """(b) A progress stream that ignores cancellation is abandoned within + the cancel grace; the step still completes.""" + from cloud_agents.spawner.openshell_spawner import OpenShellSpawner + + mod = _module(engine) + spawner = OpenShellSpawner(openshell_client=mocker.AsyncMock()) + mocker.patch.object(spawner, "spawn", return_value="http://pod-1:8080") + mocker.patch.object(spawner, "wait_ready", return_value=True) + mocker.patch.object(spawner, "destroy", return_value=None) + pod = mod.compute_pod_name("wf-1", "s", 1) + spawner._sandbox_names[pod] = "sb-1" + spawner._sandbox_ids[pod] = "sb-1" + + state = {"cancelled": False} + + async def stubborn_progress(*args, **kwargs): + try: + await asyncio.sleep(3600) + except asyncio.CancelledError: + state["cancelled"] = True + await _stubborn_sleep(STUBBORN) + + loop_name = "_stream_progress" if engine == "local" else "_progress_streaming_loop" + mocker.patch.object(mod, loop_name, stubborn_progress) + + async def post(*args, **kwargs): + await asyncio.sleep(0.02) + return _ok_response(mocker) + + client = mocker.MagicMock( + post=post, get=mocker.AsyncMock(return_value=mocker.MagicMock(status_code=404)) + ) + mocker.patch( + f"{mod.__name__}.httpx.AsyncClient", side_effect=lambda **kw: _FakeClientCM(client) + ) + mocker.patch(f"{mod.__name__}.activity.heartbeat") if engine == "temporal" else None + kwargs = {"on_progress": lambda event: None} if engine == "local" else {} + + elapsed, result, error = await _timed( + _run(engine, mod, _step_input(run_timeout=None), spawner, **kwargs) + ) + + assert error is None, error + assert result["status"] == "completed" + assert state["cancelled"] is True + assert elapsed < STUBBORN + await asyncio.sleep(STUBBORN) + + +class TestTranscriptFetchBounded: + @pytest.mark.asyncio + @pytest.mark.parametrize("engine", ENGINES) + async def test_transcript_client_close_stalls(self, mocker: MockerFixture, engine) -> None: + """(c) The transcript client's __aexit__ ignores cancellation: the fetch + is abandoned within transcript timeout + grace and the step completes + with an empty transcript.""" + mod = _module(engine) + mocker.patch.object(mod, "SANDBOX_TRANSCRIPT_TIMEOUT_SECONDS", 0.1) + run_client = mocker.MagicMock(post=mocker.AsyncMock(return_value=_ok_response(mocker))) + events = mocker.MagicMock(status_code=200, text='{"type":"result","data":{}}\n') + transcript_client = mocker.MagicMock(get=mocker.AsyncMock(return_value=events)) + clients = iter( + [ + _FakeClientCM(run_client), + _FakeClientCM(transcript_client, lambda: _stubborn_sleep(STUBBORN)), + ] + ) + mocker.patch(f"{mod.__name__}.httpx.AsyncClient", side_effect=lambda **kw: next(clients)) + + elapsed, result, error = await _timed( + _run(engine, mod, _step_input(run_timeout=None), _spawner(mocker)) + ) + + assert error is None, error + assert result["status"] == "completed" + assert result["transcript"]["events"] == [] + assert elapsed < 0.1 + GRACE + 0.3 + await asyncio.sleep(STUBBORN) + + +class TestAwaitWithin: + """The helper itself: bounded wait, bounded cancel, abandon + log.""" + + @pytest.mark.asyncio + async def test_returns_result(self) -> None: + from cloud_agents.spawner.lifetime import await_within + + async def ok(): + return 42 + + assert await await_within(ok(), 1, what="x") == 42 + + @pytest.mark.asyncio + async def test_propagates_errors(self) -> None: + from cloud_agents.spawner.lifetime import await_within + + async def boom(): + raise ValueError("boom") + + with pytest.raises(ValueError, match="boom"): + await await_within(boom(), 1, what="x") + + @pytest.mark.asyncio + async def test_uncooperative_task_abandoned_and_logged(self, caplog) -> None: + from cloud_agents.spawner.lifetime import await_within + + start = time.monotonic() + with caplog.at_level("WARNING"), pytest.raises(TimeoutError, match="thing timed out"): + await await_within(_stubborn_sleep(STUBBORN), 0.05, what="thing") + + assert time.monotonic() - start < 0.05 + GRACE + 0.2 + assert "abandon" in caplog.text + await asyncio.sleep(STUBBORN) + + @pytest.mark.asyncio + async def test_caller_cancelled_during_grace(self, mocker, caplog) -> None: + """If the caller is cancelled again while waiting out the cancel grace, + CancelledError propagates, the abandonment is logged, and the work's + eventual exception is still consumed (no "never retrieved" report).""" + import gc + + from cloud_agents.spawner import lifetime + from cloud_agents.spawner.lifetime import await_within + + mocker.patch.object(lifetime, "SANDBOX_CANCEL_GRACE_SECONDS", 5) + loop = asyncio.get_running_loop() + reported: list[dict] = [] + previous = loop.get_exception_handler() + loop.set_exception_handler(lambda _loop, ctx: reported.append(ctx)) + + async def stubborn_then_fail(): + await _stubborn_sleep(0.4) + raise ValueError("late failure") + + before = asyncio.all_tasks() + caller = asyncio.create_task(await_within(stubborn_then_fail(), 0.05, what="thing")) + await asyncio.sleep(0.15) # past the deadline, inside the grace + (inner,) = asyncio.all_tasks() - before - {caller} + try: + with caplog.at_level("WARNING"): + caller.cancel() + with pytest.raises(asyncio.CancelledError): + await caller + while not inner.done(): + await asyncio.sleep(0.05) + del inner + gc.collect() + await asyncio.sleep(0) + finally: + loop.set_exception_handler(previous) + + assert not any("never retrieved" in str(c.get("message")) for c in reported), reported + assert "abandon" in caplog.text diff --git a/tests/unit/workflow/test_cli_session.py b/tests/unit/workflow/test_cli_session.py index 958a960..2487017 100644 --- a/tests/unit/workflow/test_cli_session.py +++ b/tests/unit/workflow/test_cli_session.py @@ -100,6 +100,28 @@ async def test_launch_calls_spawner_spawn(self) -> None: ) assert agent_name.startswith("cli-") + @pytest.mark.asyncio + @pytest.mark.parametrize("with_monitor", [True, False]) + async def test_launch_never_claims_a_lifetime(self, with_monitor: bool) -> None: + """The timeout monitor can stop or block, so nothing enforces + max_session_seconds: CLI sandboxes get no expiry, monitor or not.""" + spawner = AsyncMock() + spawner.spawn = AsyncMock(return_value="http://cli-agent:8080") + + launcher = CLISessionLauncher(max_session_seconds=7200) + if with_monitor: + launcher.start_timeout_monitor(spawner) + await launcher.launch( + spawner=spawner, + context_markdown="# ctx", + prompt="p", + image="quay.io/sandbox:latest", + workflow_id="wf-abc", + ) + await launcher.shutdown() + + assert spawner.spawn.call_args.kwargs.get("lifetime_seconds") is None + @pytest.mark.asyncio async def test_launch_returns_session_id(self) -> None: """launch() returns a unique session ID.""" diff --git a/tests/unit/workflow/test_sandbox_deadlines.py b/tests/unit/workflow/test_sandbox_deadlines.py new file mode 100644 index 0000000..0d8c5c8 --- /dev/null +++ b/tests/unit/workflow/test_sandbox_deadlines.py @@ -0,0 +1,349 @@ +"""Wall-clock bounds on sandbox HTTP calls, so a sandbox never outlives the +lifetime its expires-at label promises (cloud_agents.spawner.lifetime).""" + +from __future__ import annotations + +import asyncio +import importlib +import os +import time +from typing import Any + +import pytest +from pytest_mock import MockerFixture + +RUNNER_MODULES = [ + "cloud_agents.workflow.executor.temporal.activities", + "cloud_agents.workflow.core.step_runner", +] + + +def _patch_client(mocker: MockerFixture, module: str, client: Any): + client_cls = mocker.patch(f"{module}.httpx.AsyncClient") + client_cls.return_value.__aenter__ = mocker.AsyncMock(return_value=client) + client_cls.return_value.__aexit__ = mocker.AsyncMock(return_value=False) + return client_cls + + +async def _bounded(coro: Any, seconds: float = 5) -> Any: + """Await coro, failing the test (not hanging it) if it outlives seconds.""" + task = asyncio.ensure_future(coro) + done, _ = await asyncio.wait({task}, timeout=seconds) + if not done: + task.cancel() + pytest.fail(f"call still running after {seconds}s -- no wall-clock bound") + return task.result() + + +class TestTranscriptCollectionTimeout: + @pytest.mark.asyncio + @pytest.mark.parametrize("module", RUNNER_MODULES) + async def test_uses_short_transcript_timeout(self, mocker: MockerFixture, module: str) -> None: + """The events GET doesn't inherit the (step-sized) run timeout.""" + from cloud_agents.spawner.lifetime import SANDBOX_TRANSCRIPT_TIMEOUT_SECONDS + + mod = importlib.import_module(module) + response = mocker.MagicMock(status_code=404) + client = mocker.MagicMock(get=mocker.AsyncMock(return_value=response)) + client_cls = _patch_client(mocker, module, client) + + await mod._collect_transcript( + "http://pod:8080", "s", {"timeout": 200_000.0, "verify": False}, {} + ) + + kwargs = client_cls.call_args.kwargs + assert kwargs["timeout"] == SANDBOX_TRANSCRIPT_TIMEOUT_SECONDS + assert kwargs["verify"] is False + + @pytest.mark.asyncio + @pytest.mark.parametrize("module", RUNNER_MODULES) + async def test_hanging_events_endpoint_released_within_bound( + self, mocker: MockerFixture, module: str + ) -> None: + """A sandbox whose events endpoint never answers (or trickles bytes + under the per-read timeout) is given up on after the wall-clock + transcript bound, returning an empty transcript.""" + mod = importlib.import_module(module) + mocker.patch.object(mod, "SANDBOX_TRANSCRIPT_TIMEOUT_SECONDS", 0.05) + + async def hang(*args, **kwargs): + await asyncio.sleep(3600) + + client = mocker.MagicMock(get=hang) + _patch_client(mocker, module, client) + + start = time.monotonic() + transcript = await _bounded( + mod._collect_transcript("http://pod:8080", "s", {"timeout": 600}, {}) + ) + + assert time.monotonic() - start < 2 + assert transcript.events == [] + + +class TestStepRunnerPostDeadline: + @pytest.mark.asyncio + async def test_trickling_post_bounded_by_http_timeout(self, mocker: MockerFixture) -> None: + """httpx's timeout is per-read, so a sandbox trickling bytes could hold + the POST open forever; the local engine enforces http_timeout as an + overall deadline and still destroys the sandbox.""" + mocker.patch.dict(os.environ, {"OPENAI_API_KEY": "sk-test"}, clear=False) + from cloud_agents.workflow.core.step_runner import run_step + + spawner = mocker.AsyncMock() + spawner.spawn.return_value = "http://pod-1:8080" + spawner.wait_ready.return_value = True + spawner.get_query_ssl_context = mocker.Mock(return_value=None) + + async def trickle(*args, **kwargs): + await asyncio.sleep(3600) + + client = mocker.MagicMock(post=trickle) + _patch_client(mocker, "cloud_agents.workflow.core.step_runner", client) + + step_input = { + "step": { + "name": "slow", + "prompt": "p", + "output_key": "o", + "permissions": {"timeout_seconds": 0.05}, + }, + "workflow_id": "wf-1", + "provider": {"name": "openai", "model": "gpt-4o", "credentials_secret": "k"}, + "sandbox_image": "sandbox:latest", + "context": {}, + } + + start = time.monotonic() + with pytest.raises(TimeoutError): + await _bounded(run_step(step_input, spawner=spawner, attempt=1)) + + assert time.monotonic() - start < 2 + spawner.destroy.assert_called_once() + + @pytest.mark.asyncio + async def test_timeout_with_credential_gives_clear_redacted_error( + self, mocker: MockerFixture + ) -> None: + """With a provider credential set, errors go through secret redaction; + a timeout must still surface a non-empty message (str(TimeoutError()) + is empty) without leaking the credential, and be audited.""" + secret = "sk-live-very-secret-value" + mocker.patch.dict(os.environ, {"OPENAI_API_KEY": secret}, clear=False) + from cloud_agents.workflow.core import step_runner + + audit = mocker.patch.object(step_runner, "emit_audit") + spawner = mocker.AsyncMock() + spawner.spawn.return_value = "http://pod-1:8080" + spawner.wait_ready.return_value = True + spawner.get_query_ssl_context = mocker.Mock(return_value=None) + + async def trickle(*args, **kwargs): + await asyncio.sleep(3600) + + _patch_client( + mocker, "cloud_agents.workflow.core.step_runner", mocker.MagicMock(post=trickle) + ) + + step_input = { + "step": { + "name": "slow", + "prompt": "p", + "output_key": "o", + "permissions": {"timeout_seconds": 0.05}, + }, + "workflow_id": "wf-1", + "provider": { + "name": "openai", + "model": "gpt-4o", + "credentials_secret": "OPENAI_API_KEY", + }, + "sandbox_image": "sandbox:latest", + "context": {}, + } + + with pytest.raises(Exception) as exc_info: + await _bounded(step_runner.run_step(step_input, spawner=spawner, attempt=1)) + + message = str(exc_info.value) + assert "timed out after 0.05s" in message + assert secret not in message + spawner.destroy.assert_called_once() + timeout_events = [ + c.kwargs + for c in audit.call_args_list + if c.kwargs.get("event_type") == "sandbox_timeout" + ] + assert timeout_events and timeout_events[0]["details"]["reason"] == "timeout" + + +class TestTemporalPostDeadline: + @pytest.mark.asyncio + async def test_trickling_post_bounded_with_clear_redacted_error( + self, mocker: MockerFixture + ) -> None: + """The Temporal activity enforces http_timeout locally too, rather than + relying on heartbeat-delivered cancellation.""" + secret = "sk-live-very-secret-value" + mocker.patch.dict(os.environ, {"OPENAI_API_KEY": secret}, clear=False) + from cloud_agents.workflow.executor.temporal import activities + + audit = mocker.patch.object(activities, "emit_audit") + spawner = mocker.AsyncMock() + spawner.spawn.return_value = "http://pod-1:8080" + spawner.wait_ready.return_value = True + spawner.get_query_ssl_context = mocker.Mock(return_value=None) + + async def trickle(*args, **kwargs): + await asyncio.sleep(3600) + + _patch_client(mocker, activities.__name__, mocker.MagicMock(post=trickle)) + + with pytest.raises(Exception) as exc_info: + await _bounded( + activities.run_sandbox_step( + { + "step": { + "name": "slow", + "prompt": "p", + "output_key": "o", + "permissions": {"timeout_seconds": 0.05}, + }, + "workflow_id": "wf-1", + "provider": { + "name": "openai", + "model": "gpt-4o", + "credentials_secret": "OPENAI_API_KEY", + }, + "sandbox_image": "sandbox:latest", + "context": {}, + }, + spawner=spawner, + ) + ) + + message = str(exc_info.value) + assert "timed out after 0.05s" in message + assert secret not in message + spawner.destroy.assert_called_once() + assert any( + c.kwargs.get("event_type") == "sandbox_timeout" + and c.kwargs["details"]["reason"] == "timeout" + for c in audit.call_args_list + ) + + +class TestTranscriptSaveDeadline: + @pytest.mark.asyncio + @pytest.mark.parametrize("module", RUNNER_MODULES) + async def test_hanging_transcript_store_bounded( + self, mocker: MockerFixture, module: str + ) -> None: + """The transcript-store write runs before destroy, so it's bounded too + (best-effort: a timeout only logs).""" + mocker.patch.dict(os.environ, {"OPENAI_API_KEY": "sk-test"}, clear=False) + mod = importlib.import_module(module) + mocker.patch.object(mod, "SANDBOX_TRANSCRIPT_SAVE_TIMEOUT_SECONDS", 0.05) + + spawner = mocker.AsyncMock() + spawner.spawn.return_value = "http://pod-1:8080" + spawner.wait_ready.return_value = True + spawner.get_query_ssl_context = mocker.Mock(return_value=None) + + run_response = mocker.MagicMock(status_code=200) + run_response.json.return_value = {"success": True, "output": {}} + events = mocker.MagicMock(status_code=200, text='{"type":"result","data":{}}\n') + client = mocker.MagicMock( + post=mocker.AsyncMock(return_value=run_response), + get=mocker.AsyncMock(return_value=events), + ) + _patch_client(mocker, module, client) + + store = mocker.MagicMock() + + async def hang(*args, **kwargs): + await asyncio.sleep(3600) + + store.save = hang + step_input = { + "step": {"name": "s", "prompt": "p", "output_key": "o"}, + "workflow_id": "wf-1", + "provider": {"name": "openai", "model": "gpt-4o", "credentials_secret": "k"}, + "sandbox_image": "sandbox:latest", + "context": {}, + } + if module.endswith("step_runner"): + call = mod.run_step(step_input, spawner=spawner, attempt=1, transcript_store=store) + else: + call = mod.run_sandbox_step(step_input, spawner=spawner, transcript_store=store) + + result = await _bounded(call) + + assert result["status"] == "completed" + spawner.destroy.assert_called_once() + + +class TestHeartbeatCoversSpawn: + @staticmethod + def _step_input() -> dict[str, Any]: + return { + "step": {"name": "s", "prompt": "p", "output_key": "o"}, + "workflow_id": "wf-1", + "provider": {"name": "openai", "model": "gpt-4o", "credentials_secret": "k"}, + "sandbox_image": "sandbox:latest", + "context": {}, + } + + @pytest.mark.asyncio + @pytest.mark.parametrize("spawn_fails", [False, True]) + async def test_heartbeat_runs_during_spawn_and_is_cancelled( + self, mocker: MockerFixture, spawn_fails: bool + ) -> None: + """A long spawn must not trip the 180s heartbeat timeout, so heartbeats + start before spawn() and stop on every path.""" + mocker.patch.dict(os.environ, {"OPENAI_API_KEY": "sk-test"}, clear=False) + from cloud_agents.workflow.executor.temporal import activities + + state = {"running": False, "cancelled": False} + + async def fake_heartbeat_loop(*args, **kwargs): + state["running"] = True + try: + await asyncio.sleep(3600) + except asyncio.CancelledError: + state["cancelled"] = True + raise + + mocker.patch.object(activities, "_heartbeat_loop", fake_heartbeat_loop) + seen_during_spawn = {} + + async def spawn(*args, **kwargs): + await asyncio.sleep(0) + seen_during_spawn["running"] = state["running"] + if spawn_fails: + raise RuntimeError("spawn failed") + return "http://pod-1:8080" + + spawner = mocker.AsyncMock() + spawner.spawn.side_effect = spawn + spawner.wait_ready.return_value = True + spawner.get_query_ssl_context = mocker.Mock(return_value=None) + run_response = mocker.MagicMock(status_code=200) + run_response.json.return_value = {"success": True, "output": {}} + _patch_client( + mocker, + activities.__name__, + mocker.MagicMock( + post=mocker.AsyncMock(return_value=run_response), + get=mocker.AsyncMock(return_value=mocker.MagicMock(status_code=404)), + ), + ) + + if spawn_fails: + with pytest.raises(RuntimeError): + await _bounded(activities.run_sandbox_step(self._step_input(), spawner=spawner)) + else: + await _bounded(activities.run_sandbox_step(self._step_input(), spawner=spawner)) + + assert seen_during_spawn["running"] is True + assert state["cancelled"] is True diff --git a/tests/unit/workflow/test_step_runner.py b/tests/unit/workflow/test_step_runner.py index 7ca6800..df1c5dd 100644 --- a/tests/unit/workflow/test_step_runner.py +++ b/tests/unit/workflow/test_step_runner.py @@ -114,6 +114,27 @@ async def test_run_step_spawns_sandbox( assert call_kwargs["env"]["LIGHTSPEED_PROVIDER"] == "openai" assert call_kwargs["env"]["LIGHTSPEED_MODEL"] == "gpt-4o" + @pytest.mark.asyncio + async def test_run_step_passes_per_step_lifetime( + self, + mock_spawner: AsyncMock, + mock_http_success: None, + step_input: dict[str, Any], + mocker: MockerFixture, + ) -> None: + """Local engine sandboxes get the same per-step lifetime as Temporal.""" + mocker.patch.dict(os.environ, {"OPENAI_API_KEY": "sk-test"}, clear=False) + + from cloud_agents.spawner.lifetime import step_sandbox_lifetime_seconds + from cloud_agents.workflow.core.step_runner import run_step + + step_input["step"]["permissions"] = {"timeout_seconds": 150_000} + await run_step(step_input, spawner=mock_spawner, attempt=1) + + lifetime = mock_spawner.spawn.call_args[1]["lifetime_seconds"] + assert lifetime == step_sandbox_lifetime_seconds(step_input["step"]) + assert lifetime >= 150_000 + @pytest.mark.asyncio async def test_run_step_sets_shared_agent_event_log( self,