From 2180da49ad5d1f2d8e4f6729255f2f55d4b704cb Mon Sep 17 00:00:00 2001 From: James Wong <2421248+jameswnl@users.noreply.github.com> Date: Sat, 31 Oct 2026 21:52:42 -0400 Subject: [PATCH 01/11] Scope startup sandbox reconcile to the runner's own instance reconcile_orphaned_sandboxes() destroyed every sandbox labelled spawned-by=workflow-runner, so with more than one runner replica a single restarting pod tore down other replicas' live sandboxes. OpenShellSpawner now stamps a cloud-agents/owner-instance label from the new RUNNER_INSTANCE_ID env var (Helm and Kind manifests set it to the pod name via the downward API), and reconcile only destroys sandboxes carrying this instance's owner label. Sandboxes owned by other instances, or legacy ones with no owner label, are left alone and counted in a log line. With RUNNER_INSTANCE_ID unset, reconcile destroys nothing and logs a warning. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- deploy/helm/templates/deployment.yaml | 5 + deploy/kind/workflow-runner-2-replicas.yaml | 5 + deploy/kind/workflow-runner-openshell.yaml | 5 + deploy/kind/workflow-runner.yaml | 5 + docs/ARCHITECTURE.md | 2 +- docs/sandbox-contract.md | 12 +- src/cloud_agents/spawner/factory.py | 4 +- src/cloud_agents/spawner/openshell_spawner.py | 24 +++- .../workflow/executor/local/entrypoint.py | 3 +- .../workflow/executor/temporal/entrypoint.py | 49 +++++++- tests/unit/spawner/test_factory.py | 10 ++ tests/unit/spawner/test_openshell_spawner.py | 40 +++++++ .../workflow/temporal/test_cleanup_metrics.py | 6 +- .../temporal/test_startup_reconciliation.py | 106 +++++++++++++++--- 15 files changed, 243 insertions(+), 35 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 39377db0..13a32686 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 only destroys sandboxes whose `cloud-agents/owner-instance` label matches this replica's `RUNNER_INSTANCE_ID` (Helm: pod name); other replicas' and legacy unlabelled sandboxes are left alone, and an unset `RUNNER_INSTANCE_ID` destroys nothing. | | E2E guardrails | `openshell_spawner.py` | `e2e/test_guardrails.py::TestOpenShellGuardrails`, `TestOpenShellQueryTLS` | ## Database Migrations (Alembic) diff --git a/deploy/helm/templates/deployment.yaml b/deploy/helm/templates/deployment.yaml index 60d51f6c..bb498fad 100644 --- a/deploy/helm/templates/deployment.yaml +++ b/deploy/helm/templates/deployment.yaml @@ -29,6 +29,11 @@ spec: value: {{ .Values.temporal.namespace | quote }} - name: WORKFLOW_SPAWNER value: {{ .Values.spawner.type | quote }} + # Scopes startup orphan cleanup to this pod's own sandboxes + - name: RUNNER_INSTANCE_ID + valueFrom: + fieldRef: + fieldPath: metadata.name - name: OPENSHELL_GATEWAY_URL value: {{ .Values.spawner.gatewayUrl | quote }} - name: OPENSHELL_WORKSPACE diff --git a/deploy/kind/workflow-runner-2-replicas.yaml b/deploy/kind/workflow-runner-2-replicas.yaml index 09d03a80..67cdc4e3 100644 --- a/deploy/kind/workflow-runner-2-replicas.yaml +++ b/deploy/kind/workflow-runner-2-replicas.yaml @@ -46,6 +46,11 @@ spec: value: "default" - name: WORKFLOW_SPAWNER value: "openshell" + # Scopes startup orphan cleanup to this pod's own sandboxes + - name: RUNNER_INSTANCE_ID + valueFrom: + fieldRef: + fieldPath: metadata.name - name: OPENSHELL_GATEWAY_URL value: "CHANGEME.example.com:17670" # your OpenShell gateway address - name: AUTH_REQUIRED diff --git a/deploy/kind/workflow-runner-openshell.yaml b/deploy/kind/workflow-runner-openshell.yaml index 381962e8..b1cc313a 100644 --- a/deploy/kind/workflow-runner-openshell.yaml +++ b/deploy/kind/workflow-runner-openshell.yaml @@ -44,6 +44,11 @@ spec: value: "default" - name: WORKFLOW_SPAWNER value: "openshell" + # Scopes startup orphan cleanup to this pod's own sandboxes + - name: RUNNER_INSTANCE_ID + valueFrom: + fieldRef: + fieldPath: metadata.name - name: OPENSHELL_GATEWAY_URL value: "CHANGEME.example.com:17670" # your OpenShell gateway address - name: AUTH_REQUIRED diff --git a/deploy/kind/workflow-runner.yaml b/deploy/kind/workflow-runner.yaml index 7084ab8b..830d01ac 100644 --- a/deploy/kind/workflow-runner.yaml +++ b/deploy/kind/workflow-runner.yaml @@ -35,6 +35,11 @@ spec: value: "default" - name: WORKFLOW_SPAWNER value: "openshell" + # Scopes startup orphan cleanup to this pod's own sandboxes + - name: RUNNER_INSTANCE_ID + valueFrom: + fieldRef: + fieldPath: metadata.name - name: OPENSHELL_GATEWAY_URL value: "CHANGEME.example.com:17670" # your OpenShell gateway address - name: AUTH_REQUIRED diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 37ef01c1..077122fa 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 for leaked containers, scoped to the restarting replica's own sandboxes via the `cloud-agents/owner-instance` label (`RUNNER_INSTANCE_ID`). ### Dual Deployment diff --git a/docs/sandbox-contract.md b/docs/sandbox-contract.md index b6ecacee..351cc0a5 100644 --- a/docs/sandbox-contract.md +++ b/docs/sandbox-contract.md @@ -127,5 +127,13 @@ 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/owner-instance` | Runner replica's `RUNNER_INSTANCE_ID` (set only when configured) | + +Used for: label-based orphan cleanup after worker crashes. On startup a runner +destroys only sandboxes whose `cloud-agents/owner-instance` matches its own +`RUNNER_INSTANCE_ID` (the Helm chart sets it to the pod name). Sandboxes owned +by other replicas, or with no owner label (spawned before this label existed), +are left alone and only counted in a log line. With `RUNNER_INSTANCE_ID` unset, +startup cleanup destroys nothing. diff --git a/src/cloud_agents/spawner/factory.py b/src/cloud_agents/spawner/factory.py index bd91596b..575c6f73 100644 --- a/src/cloud_agents/spawner/factory.py +++ b/src/cloud_agents/spawner/factory.py @@ -32,7 +32,9 @@ # 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", "owner_instance"} +) def _filtered(params: dict[str, Any], known: frozenset[str]) -> dict[str, Any]: diff --git a/src/cloud_agents/spawner/openshell_spawner.py b/src/cloud_agents/spawner/openshell_spawner.py index ad811349..b1da181d 100644 --- a/src/cloud_agents/spawner/openshell_spawner.py +++ b/src/cloud_agents/spawner/openshell_spawner.py @@ -168,6 +168,13 @@ class OpenShellSpawner(AgentSpawner): # workflow/executor/temporal/entrypoint.py filters on. _SPAWNED_BY_LABEL: ClassVar[dict[str, str]] = {"spawned-by": "workflow-runner"} + # Identifies which runner replica spawned a sandbox (value: the + # owner_instance constructor arg, wired from RUNNER_INSTANCE_ID) so + # reconcile_orphaned_sandboxes() only destroys this replica's own orphans, + # never another live replica's sandboxes. Omitted when owner_instance is + # unset. Must match the key reconcile_orphaned_sandboxes() filters on. + _OWNER_INSTANCE_LABEL_KEY: ClassVar[str] = "cloud-agents/owner-instance" + # Baked into the sandbox image (lightspeed-agentic-sandbox's # Containerfile); copies the allowed_skills subset from _SKILLS_ROOT # into LIGHTSPEED_SKILLS_DIR so providers' directory-listing-based @@ -281,6 +288,7 @@ def __init__( bearer_token_provider: Callable[[], str] | None = None, extra_readable_paths: list[str] | None = None, extra_env: dict[str, str] | None = None, + owner_instance: str = "", **kwargs: Any, ) -> None: """Initialize the OpenShell spawner. @@ -326,8 +334,14 @@ 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. + owner_instance: Stable identity of this runner replica (e.g. its + pod name), attached to every sandbox as the + _OWNER_INSTANCE_LABEL_KEY label so startup reconciliation + can tell this replica's orphans apart from other replicas' + live sandboxes. Empty means no owner label is attached. """ super().__init__(**kwargs) + self._owner_instance = owner_instance self._client = openshell_client self._workspace = workspace self._endpoint = endpoint @@ -1018,15 +1032,17 @@ async def _do_spawn( ) raise - # 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). + # Merge caller labels with the fixed spawned-by label, the + # agent_name recovery label and the owner-instance label; all always + # win over caller-supplied labels of the same key so a caller can't + # accidentally suppress orphan discovery (issue #224). sandbox_labels = { **(labels or {}), **self._SPAWNED_BY_LABEL, self._AGENT_NAME_LABEL_KEY: agent_name, } + if self._owner_instance: + sandbox_labels[self._OWNER_INSTANCE_LABEL_KEY] = self._owner_instance spec = openshell_pb2.SandboxSpec( template=openshell_pb2.SandboxTemplate( diff --git a/src/cloud_agents/workflow/executor/local/entrypoint.py b/src/cloud_agents/workflow/executor/local/entrypoint.py index 3339d385..194902c8 100644 --- a/src/cloud_agents/workflow/executor/local/entrypoint.py +++ b/src/cloud_agents/workflow/executor/local/entrypoint.py @@ -23,6 +23,7 @@ from cloud_agents.workflow.executor.local.executor import LocalWorkflowRunner from cloud_agents.workflow.executor.temporal.entrypoint import ( CONTENT_POLICY_PATH, + RUNNER_INSTANCE_ID, _create_spawner, _get_auth_dependency, _load_content_policy, @@ -64,7 +65,7 @@ def build_local_app() -> FastAPI: @asynccontextmanager async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]: """Connect stores and clean up orphans on startup.""" - await reconcile_orphaned_sandboxes(spawner) + await reconcile_orphaned_sandboxes(spawner, RUNNER_INSTANCE_ID) if transcript_store: try: diff --git a/src/cloud_agents/workflow/executor/temporal/entrypoint.py b/src/cloud_agents/workflow/executor/temporal/entrypoint.py index c14124c1..8d55b490 100644 --- a/src/cloud_agents/workflow/executor/temporal/entrypoint.py +++ b/src/cloud_agents/workflow/executor/temporal/entrypoint.py @@ -73,6 +73,12 @@ def _build_tls_config(): SPAWNER_TYPE = os.environ.get("WORKFLOW_SPAWNER", "") +# Stable identity of this runner replica (the Helm chart sets it to the pod +# name). Stamped on every sandbox as an owner label and used to scope startup +# reconciliation to this replica's own orphans. Unset = reconcile destroys +# nothing (fail-safe for multi-replica deployments). +RUNNER_INSTANCE_ID = os.environ.get("RUNNER_INSTANCE_ID", "") + def _create_spawner(): """Create spawner based on environment config. @@ -100,6 +106,7 @@ 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", ""), + owner_instance=RUNNER_INSTANCE_ID, ) if SPAWNER_TYPE == "": logger.info("No spawner configured — sandbox activity will use stub mode") @@ -109,19 +116,49 @@ 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, owner_instance: str = "" +) -> None: + """Destroy this replica's orphaned sandboxes left from a previous crash. + + On startup, scans for sandboxes labelled "spawned-by=workflow-runner" + *and* "cloud-agents/owner-instance=" and destroys them. + This prevents resource leaks after unclean shutdowns without touching + sandboxes that other live runner replicas are still using. - On startup, scans for containers/Jobs with the "spawned-by=workflow-runner" - label and destroys them. This prevents resource leaks after unclean shutdowns. + Sandboxes carrying spawned-by but a different owner (another replica) or + no owner label at all (spawned before owner labelling existed) are left + alone and only counted in a log line: there is no way to tell from here + whether their owner is still alive. When owner_instance is empty nothing + is destroyed. Args: spawner: The spawner instance, or None if no spawner is configured. + owner_instance: This replica's RUNNER_INSTANCE_ID. Must match the + value the spawner stamps on sandboxes it creates. """ if spawner is None: return - orphans = await spawner.list_active({"spawned-by": "workflow-runner"}) + # Must match OpenShellSpawner._SPAWNED_BY_LABEL / _OWNER_INSTANCE_LABEL_KEY. + spawned_by = {"spawned-by": "workflow-runner"} + if owner_instance: + orphans = await spawner.list_active( + {**spawned_by, "cloud-agents/owner-instance": owner_instance} + ) + else: + logger.warning( + "RUNNER_INSTANCE_ID not set — skipping orphaned sandbox cleanup " + "(cannot tell this replica's sandboxes from other replicas')" + ) + orphans = [] + untouched = len(set(await spawner.list_active(spawned_by)) - set(orphans)) + if untouched: + logger.info( + "Leaving %d sandbox(es) owned by other runner instances or with " + "no owner label untouched", + untouched, + ) cleaned = 0 failed_names = [] for name in orphans: @@ -232,7 +269,7 @@ def build_temporal_app( @asynccontextmanager async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]: """Connect Temporal client and start worker on startup.""" - await reconcile_orphaned_sandboxes(spawner) + await reconcile_orphaned_sandboxes(spawner, RUNNER_INSTANCE_ID) # Connect transcript store (best-effort: failures are non-fatal) if transcript_store is not None: diff --git a/tests/unit/spawner/test_factory.py b/tests/unit/spawner/test_factory.py index f0bcc3f0..f01738d8 100644 --- a/tests/unit/spawner/test_factory.py +++ b/tests/unit/spawner/test_factory.py @@ -26,6 +26,16 @@ def test_builds_openshell_spawner_no_auth(self, mocker: MockerFixture) -> None: assert spawner._tls_ca == "" assert spawner._bearer_token == "" + def test_owner_instance_forwarded(self, mocker: MockerFixture) -> None: + """owner_instance reaches OpenShellSpawner (stamped as an owner label on spawn).""" + from cloud_agents.spawner.factory import build_spawner + + mocker.patch("openshell.SandboxClient") + + spawner = build_spawner("openshell", gateway_url="gw:17670", owner_instance="runner-a") + + assert spawner._owner_instance == "runner-a" + 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_openshell_spawner.py b/tests/unit/spawner/test_openshell_spawner.py index cb1da2a9..d47af798 100644 --- a/tests/unit/spawner/test_openshell_spawner.py +++ b/tests/unit/spawner/test_openshell_spawner.py @@ -472,6 +472,46 @@ async def mock_ready(*args, **kwargs): "cloud-agents/agent-name": "agent-1", } + @pytest.mark.asyncio + async def test_spawn_attaches_owner_instance_label(self, mocker: MockerFixture) -> None: + """owner_instance is stamped as cloud-agents/owner-instance so + reconcile_orphaned_sandboxes() only destroys this replica's sandboxes, + and it wins over a caller-supplied label of the same key.""" + 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, owner_instance="runner-a") + 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") + + await spawner.spawn( + "agent-1", "sandbox:latest", env={}, labels={"cloud-agents/owner-instance": "spoof"} + ) + + create_kwargs = mock_client.create.call_args.kwargs + assert create_kwargs["labels"] == { + "spawned-by": "workflow-runner", + "cloud-agents/agent-name": "agent-1", + "cloud-agents/owner-instance": "runner-a", + } + @pytest.mark.asyncio async def test_spawn_with_credential_does_not_expose_real_value( self, mocker: MockerFixture diff --git a/tests/unit/workflow/temporal/test_cleanup_metrics.py b/tests/unit/workflow/temporal/test_cleanup_metrics.py index c1a3d00a..b317f39f 100644 --- a/tests/unit/workflow/temporal/test_cleanup_metrics.py +++ b/tests/unit/workflow/temporal/test_cleanup_metrics.py @@ -108,7 +108,7 @@ async def test_orphan_cleanup_increments_counter(self, mocker: MockerFixture) -> before = _get_counter_value("ls_sandbox_orphans_cleaned") - await reconcile_orphaned_sandboxes(mock_spawner) + await reconcile_orphaned_sandboxes(mock_spawner, owner_instance="runner-a") after = _get_counter_value("ls_sandbox_orphans_cleaned") assert after >= before + 2 @@ -123,7 +123,7 @@ async def test_no_orphans_no_increment(self, mocker: MockerFixture) -> None: before = _get_counter_value("ls_sandbox_orphans_cleaned") - await reconcile_orphaned_sandboxes(mock_spawner) + await reconcile_orphaned_sandboxes(mock_spawner, owner_instance="runner-a") after = _get_counter_value("ls_sandbox_orphans_cleaned") assert after == before @@ -150,7 +150,7 @@ async def destroy_side_effect(name: str) -> None: before = _get_counter_value("ls_sandbox_orphans_cleaned") - await reconcile_orphaned_sandboxes(mock_spawner) + await reconcile_orphaned_sandboxes(mock_spawner, owner_instance="runner-a") after = _get_counter_value("ls_sandbox_orphans_cleaned") assert after >= before + 2 # 2 succeeded, 1 failed diff --git a/tests/unit/workflow/temporal/test_startup_reconciliation.py b/tests/unit/workflow/temporal/test_startup_reconciliation.py index 47debd65..8187ef2a 100644 --- a/tests/unit/workflow/temporal/test_startup_reconciliation.py +++ b/tests/unit/workflow/temporal/test_startup_reconciliation.py @@ -8,43 +8,102 @@ from cloud_agents.workflow.executor.temporal.entrypoint import reconcile_orphaned_sandboxes +OWNER_KEY = "cloud-agents/owner-instance" + + +def _fake_spawner(sandboxes: dict[str, str | None]) -> AsyncMock: + """Build a spawner whose list_active() honours label selectors. + + sandboxes maps agent name -> owner-instance label value (None = legacy + sandbox carrying only spawned-by=workflow-runner). + """ + spawner = AsyncMock() + + async def list_active(labels: dict[str, str] | None = None) -> list[str]: + labels = labels or {} + assert labels.get("spawned-by") == "workflow-runner" + if OWNER_KEY in labels: + return [name for name, owner in sandboxes.items() if owner == labels[OWNER_KEY]] + return list(sandboxes) + + spawner.list_active.side_effect = list_active + return spawner + class TestStartupReconciliation: """Tests for reconcile_orphaned_sandboxes.""" @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"] + """Startup reconciliation destroys this instance's orphaned sandboxes.""" + mock_spawner = _fake_spawner({"ca-orphan1": "runner-a", "ca-orphan2": "runner-a"}) - await reconcile_orphaned_sandboxes(mock_spawner) + await reconcile_orphaned_sandboxes(mock_spawner, owner_instance="runner-a") - mock_spawner.list_active.assert_called_once_with( - {"spawned-by": "workflow-runner"}, + mock_spawner.list_active.assert_any_call( + {"spawned-by": "workflow-runner", OWNER_KEY: "runner-a"}, ) assert mock_spawner.destroy.call_count == 2 mock_spawner.destroy.assert_any_call("ca-orphan1") mock_spawner.destroy.assert_any_call("ca-orphan2") + @pytest.mark.asyncio + async def test_other_instance_sandboxes_survive(self) -> None: + """A restarting replica must not destroy another live replica's sandboxes.""" + mock_spawner = _fake_spawner( + {"ca-mine": "runner-a", "ca-theirs1": "runner-b", "ca-theirs2": "runner-c"} + ) + + await reconcile_orphaned_sandboxes(mock_spawner, owner_instance="runner-a") + + mock_spawner.destroy.assert_called_once_with("ca-mine") + + @pytest.mark.asyncio + async def test_legacy_unowned_sandboxes_left_alone(self) -> None: + """Sandboxes with spawned-by but no owner-instance label are never destroyed. + + They predate owner labelling, so there is no way to tell whether a + live replica still uses them (e.g. a long-lived chat sandbox). + """ + mock_spawner = _fake_spawner({"ca-legacy": None, "ca-mine": "runner-a"}) + + await reconcile_orphaned_sandboxes(mock_spawner, owner_instance="runner-a") + + mock_spawner.destroy.assert_called_once_with("ca-mine") + + @pytest.mark.asyncio + async def test_unset_identity_destroys_nothing(self, caplog) -> None: + """Without an instance identity, reconcile fails safe: no destroys, a warning.""" + mock_spawner = _fake_spawner({"ca-legacy": None, "ca-other": "runner-b"}) + + with caplog.at_level("WARNING"): + await reconcile_orphaned_sandboxes(mock_spawner, owner_instance="") + + mock_spawner.destroy.assert_not_called() + assert "RUNNER_INSTANCE_ID" in caplog.text + + @pytest.mark.asyncio + async def test_unset_identity_is_default(self) -> None: + """Callers that pass no identity get the fail-safe behaviour.""" + mock_spawner = _fake_spawner({"ca-any": None}) + + await reconcile_orphaned_sandboxes(mock_spawner) + + mock_spawner.destroy.assert_not_called() + @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, owner_instance="runner-a") - mock_spawner.list_active.assert_called_once_with( - {"spawned-by": "workflow-runner"}, - ) mock_spawner.destroy.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 = _fake_spawner({"orphan1": "a", "orphan2": "a", "orphan3": "a"}) mock_spawner.destroy.side_effect = [ None, RuntimeError("destroy failed"), @@ -52,7 +111,7 @@ async def test_destroy_failure_logged_not_raised(self) -> None: ] # Should not raise - await reconcile_orphaned_sandboxes(mock_spawner) + await reconcile_orphaned_sandboxes(mock_spawner, owner_instance="a") assert mock_spawner.destroy.call_count == 3 @@ -60,4 +119,19 @@ async def test_destroy_failure_logged_not_raised(self) -> None: 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) + await reconcile_orphaned_sandboxes(None, owner_instance="runner-a") + + +class TestCreateSpawnerOwnerInstance: + """_create_spawner() threads RUNNER_INSTANCE_ID into the spawner.""" + + def test_runner_instance_id_passed_to_spawner(self, mocker) -> None: + from cloud_agents.workflow.executor.temporal import entrypoint + + mocker.patch.object(entrypoint, "SPAWNER_TYPE", "openshell") + mocker.patch.object(entrypoint, "RUNNER_INSTANCE_ID", "runner-a", create=True) + build = mocker.patch("cloud_agents.spawner.factory.build_spawner") + + entrypoint._create_spawner() + + assert build.call_args.kwargs["owner_instance"] == "runner-a" From 76da5cb5728081067ffe8e5ab84161930fb607d5 Mon Sep 17 00:00:00 2001 From: James Wong <2421248+jameswnl@users.noreply.github.com> Date: Sat, 31 Oct 2026 22:19:33 -0400 Subject: [PATCH 02/11] Reap expired sandboxes from any runner instance on startup Owner-scoped reconcile left sandboxes from replaced pods behind forever, since a new pod never reuses the old pod name. OpenShellSpawner now stamps a cloud-agents/expires-at label (spawn time + SANDBOX_MAX_LIFETIME_SECONDS, default 86400), and reconcile also destroys any spawned-by=workflow-runner sandbox whose expiry has passed, regardless of owner. Sandboxes without the label, or with a malformed one, are left alone and logged. Startup fails if the lifetime is below 3900s (a CLI session's default 3600s plus the 300s sandbox ready wait). The runner identity now falls back from RUNNER_INSTANCE_ID to HOSTNAME. An invalid explicit RUNNER_INSTANCE_ID fails startup; an invalid HOSTNAME only disables own-instance cleanup with a warning, and expired-sandbox cleanup still runs. Reconcile now makes a single gateway listing via a new AgentSpawner.list_active_labels() and partitions by label client-side. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- docs/ARCHITECTURE.md | 2 +- docs/sandbox-contract.md | 24 +- src/cloud_agents/spawner/base.py | 27 +++ src/cloud_agents/spawner/factory.py | 2 +- src/cloud_agents/spawner/openshell_spawner.py | 46 +++- .../workflow/executor/local/entrypoint.py | 7 +- .../workflow/executor/temporal/entrypoint.py | 160 ++++++++++---- tests/unit/spawner/test_base.py | 12 + tests/unit/spawner/test_factory.py | 10 +- tests/unit/spawner/test_openshell_spawner.py | 68 ++++++ .../workflow/temporal/test_cleanup_metrics.py | 13 +- .../temporal/test_startup_reconciliation.py | 208 +++++++++++++----- 13 files changed, 466 insertions(+), 115 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 13a32686..791c1b96 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. Reconcile only destroys sandboxes whose `cloud-agents/owner-instance` label matches this replica's `RUNNER_INSTANCE_ID` (Helm: pod name); other replicas' and legacy unlabelled sandboxes are left alone, and an unset `RUNNER_INSTANCE_ID` destroys nothing. | +| 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 sandboxes whose `cloud-agents/owner-instance` label matches this replica's identity (`RUNNER_INSTANCE_ID`, Helm: pod name, else `HOSTNAME`) plus any sandbox past its `cloud-agents/expires-at` label (spawn time + `SANDBOX_MAX_LIFETIME_SECONDS`, default 86400, startup fails below 3900); other replicas' unexpired sandboxes and legacy sandboxes without `expires-at` are left alone. | | 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 077122fa..93f2a973 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, scoped to the restarting replica's own sandboxes via the `cloud-agents/owner-instance` label (`RUNNER_INSTANCE_ID`). +- **Crash recovery** — content-hash pod naming for idempotent retries + startup orphan reconciliation for leaked containers, scoped to the restarting replica's own sandboxes via the `cloud-agents/owner-instance` label (`RUNNER_INSTANCE_ID`, else `HOSTNAME`) plus any sandbox past its `cloud-agents/expires-at` label (`SANDBOX_MAX_LIFETIME_SECONDS`). ### Dual Deployment diff --git a/docs/sandbox-contract.md b/docs/sandbox-contract.md index 351cc0a5..cc28b08c 100644 --- a/docs/sandbox-contract.md +++ b/docs/sandbox-contract.md @@ -129,11 +129,23 @@ Spawned sandbox pods carry these labels for lifecycle management: | `cloud-agents/attempt` | Retry attempt number | | `spawned-by` | `workflow-runner` (always set) | | `cloud-agents/agent-name` | Agent name (always set; the gateway assigns the sandbox name) | -| `cloud-agents/owner-instance` | Runner replica's `RUNNER_INSTANCE_ID` (set only when configured) | +| `cloud-agents/owner-instance` | Runner replica's identity: `RUNNER_INSTANCE_ID`, else `HOSTNAME` (set only when one is available) | +| `cloud-agents/expires-at` | Unix seconds: spawn time + `SANDBOX_MAX_LIFETIME_SECONDS` (default 86400) | Used for: label-based orphan cleanup after worker crashes. On startup a runner -destroys only sandboxes whose `cloud-agents/owner-instance` matches its own -`RUNNER_INSTANCE_ID` (the Helm chart sets it to the pod name). Sandboxes owned -by other replicas, or with no owner label (spawned before this label existed), -are left alone and only counted in a log line. With `RUNNER_INSTANCE_ID` unset, -startup cleanup destroys nothing. +makes one `spawned-by=workflow-runner` listing and destroys sandboxes whose +`cloud-agents/owner-instance` matches its own identity (the Helm chart sets +`RUNNER_INSTANCE_ID` to the pod name), plus any sandbox whose +`cloud-agents/expires-at` is in the past regardless of owner (e.g. left by a +replaced pod). Other replicas' unexpired sandboxes, sandboxes with no +`expires-at` label (spawned before it existed) and sandboxes with a malformed +`expires-at` are left alone and logged. With no identity, only expired +sandboxes are destroyed. + +An explicit `RUNNER_INSTANCE_ID` must be a valid label value or startup fails; +an invalid `HOSTNAME` fallback only disables own-instance cleanup with a +warning. `SANDBOX_MAX_LIFETIME_SECONDS` below 3900 (a CLI session's default +3600s plus the 300s sandbox ready wait) fails startup. A workflow step whose +`timeout_seconds` exceeds the lifetime isn't caught (the schema has no upper +bound) and its sandbox may be reaped by another replica's restart, so keep the +lifetime above your longest step timeout. diff --git a/src/cloud_agents/spawner/base.py b/src/cloud_agents/spawner/base.py index 9f8ecffe..e35f4bd5 100644 --- a/src/cloud_agents/spawner/base.py +++ b/src/cloud_agents/spawner/base.py @@ -259,6 +259,33 @@ async def _do_list_active( ) -> list[str]: """Implementation-specific listing of active agents.""" + async def list_active_labels( + self, + labels: dict[str, str] | None = None, + ) -> list[tuple[str, dict[str, str]]]: + """List active spawned agent names with each sandbox's labels. + + Args: + labels: Optional label selector to filter results. + + Returns: + (agent name, labels) pairs for active agents matching the given + labels, so callers can filter on label values a selector can't + express (e.g. reconcile_orphaned_sandboxes()' expiry check). + """ + return await self._do_list_active_labels(labels) + + async def _do_list_active_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 treats a sandbox with no owner/expiry labels + as legacy and never destroys it, so this default is fail-safe. + """ + return [(name, {}) for name in await self._do_list_active(labels)] + 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 575c6f73..2ff86154 100644 --- a/src/cloud_agents/spawner/factory.py +++ b/src/cloud_agents/spawner/factory.py @@ -33,7 +33,7 @@ # 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", "owner_instance"} + {"max_pods", "extra_readable_paths", "extra_env", "owner_instance", "max_lifetime_seconds"} ) diff --git a/src/cloud_agents/spawner/openshell_spawner.py b/src/cloud_agents/spawner/openshell_spawner.py index b1da181d..1b8ffdf8 100644 --- a/src/cloud_agents/spawner/openshell_spawner.py +++ b/src/cloud_agents/spawner/openshell_spawner.py @@ -19,6 +19,7 @@ import logging import os import ssl +import time from collections.abc import Callable from typing import TYPE_CHECKING, Any, AsyncIterator, ClassVar @@ -175,6 +176,13 @@ class OpenShellSpawner(AgentSpawner): # unset. Must match the key reconcile_orphaned_sandboxes() filters on. _OWNER_INSTANCE_LABEL_KEY: ClassVar[str] = "cloud-agents/owner-instance" + # Unix seconds after which the sandbox has outlived any legitimate use + # (spawn time + max_lifetime_seconds). Lets any replica's + # reconcile_orphaned_sandboxes() reap sandboxes left by a replaced pod, + # whose owner-instance value will never come back. Omitted when + # max_lifetime_seconds is unset. Must match the key reconcile filters on. + _EXPIRES_AT_LABEL_KEY: ClassVar[str] = "cloud-agents/expires-at" + # Baked into the sandbox image (lightspeed-agentic-sandbox's # Containerfile); copies the allowed_skills subset from _SKILLS_ROOT # into LIGHTSPEED_SKILLS_DIR so providers' directory-listing-based @@ -289,6 +297,8 @@ def __init__( extra_readable_paths: list[str] | None = None, extra_env: dict[str, str] | None = None, owner_instance: str = "", + max_lifetime_seconds: int | None = None, + clock: Callable[[], float] = time.time, **kwargs: Any, ) -> None: """Initialize the OpenShell spawner. @@ -339,9 +349,18 @@ def __init__( _OWNER_INSTANCE_LABEL_KEY label so startup reconciliation can tell this replica's orphans apart from other replicas' live sandboxes. Empty means no owner label is attached. + max_lifetime_seconds: Longest legitimate life of a sandbox this + spawner creates. Attached to every sandbox as the + _EXPIRES_AT_LABEL_KEY label (spawn time + this value) so + startup reconciliation on any replica can reap it once + expired. None means no expiry label is attached (the sandbox + is then never reaped by another replica). + clock: Returns the current unix time; injectable for tests. """ super().__init__(**kwargs) self._owner_instance = owner_instance + self._max_lifetime_seconds = max_lifetime_seconds + self._clock = clock self._client = openshell_client self._workspace = workspace self._endpoint = endpoint @@ -1033,9 +1052,9 @@ async def _do_spawn( raise # Merge caller labels with the fixed spawned-by label, the - # agent_name recovery label and the owner-instance label; all always - # win over caller-supplied labels of the same key so a caller can't - # accidentally suppress orphan discovery (issue #224). + # agent_name recovery label and the owner-instance/expires-at labels; + # all always win over caller-supplied labels of the same key so a + # caller can't accidentally suppress orphan discovery (issue #224). sandbox_labels = { **(labels or {}), **self._SPAWNED_BY_LABEL, @@ -1043,6 +1062,10 @@ async def _do_spawn( } if self._owner_instance: sandbox_labels[self._OWNER_INSTANCE_LABEL_KEY] = self._owner_instance + if self._max_lifetime_seconds is not None: + sandbox_labels[self._EXPIRES_AT_LABEL_KEY] = str( + int(self._clock()) + self._max_lifetime_seconds + ) spec = openshell_pb2.SandboxSpec( template=openshell_pb2.SandboxTemplate( @@ -2032,6 +2055,18 @@ async def _do_list_active( of being silently dropped -- destroy() falls back to treating such a name literally, so this remains cleanable. """ + return [name for name, _ in await self._do_list_active_labels(labels)] + + async def _do_list_active_labels( + self, + labels: dict[str, str] | None = None, + ) -> list[tuple[str, dict[str, str]]]: + """List active sandboxes as (agent name, labels) from one gateway call. + + Same query and name recovery as _do_list_active(); also returns each + sandbox's labels so reconcile_orphaned_sandboxes() can partition by + owner-instance/expires-at client-side. + """ label_selector = ",".join(f"{key}={value}" for key, value in (labels or {}).items()) refs = await asyncio.to_thread( self._client.list, @@ -2043,4 +2078,7 @@ async def _do_list_active( # ever legitimately exceeds this. limit=1000, ) - return [ref.labels.get(self._AGENT_NAME_LABEL_KEY) or ref.name for ref in refs] + return [ + (ref.labels.get(self._AGENT_NAME_LABEL_KEY) or ref.name, dict(ref.labels)) + for ref in refs + ] diff --git a/src/cloud_agents/workflow/executor/local/entrypoint.py b/src/cloud_agents/workflow/executor/local/entrypoint.py index 194902c8..56f8410f 100644 --- a/src/cloud_agents/workflow/executor/local/entrypoint.py +++ b/src/cloud_agents/workflow/executor/local/entrypoint.py @@ -23,10 +23,10 @@ from cloud_agents.workflow.executor.local.executor import LocalWorkflowRunner from cloud_agents.workflow.executor.temporal.entrypoint import ( CONTENT_POLICY_PATH, - RUNNER_INSTANCE_ID, _create_spawner, _get_auth_dependency, _load_content_policy, + _runner_instance_id, reconcile_orphaned_sandboxes, ) @@ -42,7 +42,8 @@ def build_local_app() -> FastAPI: configure_logging() init_tracing("workflow-runner") - spawner = _create_spawner() + owner_instance = _runner_instance_id() + spawner = _create_spawner(owner_instance) transcript_store = TranscriptStore.from_env() run_state_store = RunStateStore.from_env() @@ -65,7 +66,7 @@ def build_local_app() -> FastAPI: @asynccontextmanager async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]: """Connect stores and clean up orphans on startup.""" - await reconcile_orphaned_sandboxes(spawner, RUNNER_INSTANCE_ID) + await reconcile_orphaned_sandboxes(spawner, owner_instance) if transcript_store: try: diff --git a/src/cloud_agents/workflow/executor/temporal/entrypoint.py b/src/cloud_agents/workflow/executor/temporal/entrypoint.py index 8d55b490..48d04c4c 100644 --- a/src/cloud_agents/workflow/executor/temporal/entrypoint.py +++ b/src/cloud_agents/workflow/executor/temporal/entrypoint.py @@ -10,6 +10,8 @@ import logging import os +import re +import time from collections.abc import AsyncGenerator from contextlib import asynccontextmanager from typing import TYPE_CHECKING @@ -73,14 +75,72 @@ def _build_tls_config(): SPAWNER_TYPE = os.environ.get("WORKFLOW_SPAWNER", "") -# Stable identity of this runner replica (the Helm chart sets it to the pod -# name). Stamped on every sandbox as an owner label and used to scope startup -# reconciliation to this replica's own orphans. Unset = reconcile destroys -# nothing (fail-safe for multi-replica deployments). -RUNNER_INSTANCE_ID = os.environ.get("RUNNER_INSTANCE_ID", "") +# Kubernetes label value syntax; owner-instance is stamped as a sandbox label. +_LABEL_VALUE_RE = re.compile(r"^(?:[A-Za-z0-9](?:[-A-Za-z0-9_.]{0,61}[A-Za-z0-9])?)?$") +DEFAULT_SANDBOX_MAX_LIFETIME_SECONDS = 86400 +# Floor for SANDBOX_MAX_LIFETIME_SECONDS: the longest sandbox life this runner +# creates with default settings -- a CLI session's DEFAULT_MAX_SESSION_SECONDS +# (3600; agent steps default to timeout_seconds=600) plus OpenShellSpawner's +# 300s gateway wait_ready. Per-workflow step timeout_seconds has no upper +# bound in the schema, so a step configured longer than the lifetime can't be +# caught here and may be reaped by another replica's startup reconcile. +_MIN_SANDBOX_MAX_LIFETIME_SECONDS = 3600 + 300 -def _create_spawner(): + +def _runner_instance_id() -> str: + """Resolve this runner replica's stable identity for sandbox ownership. + + RUNNER_INSTANCE_ID (the Helm chart sets it to the pod name), else + HOSTNAME, else "". The value is stamped on every sandbox as an owner label + and scopes startup reconciliation to this replica's own orphans. + + Raises: + ValueError: If RUNNER_INSTANCE_ID is set but isn't a legal label value. + An unusable HOSTNAME fallback only logs a warning and returns "". + """ + explicit = os.environ.get("RUNNER_INSTANCE_ID", "") + if explicit: + if not _LABEL_VALUE_RE.match(explicit): + raise ValueError( + f"RUNNER_INSTANCE_ID={explicit!r} is not a valid label value " + "(max 63 chars of [A-Za-z0-9-_.], alphanumeric at both ends)" + ) + return explicit + hostname = os.environ.get("HOSTNAME", "") + if hostname and not _LABEL_VALUE_RE.match(hostname): + logger.warning( + "HOSTNAME=%r is not a valid label value — set RUNNER_INSTANCE_ID; " + "own-instance sandbox cleanup disabled", + hostname, + ) + return "" + return hostname + + +def _sandbox_max_lifetime_seconds() -> int: + """Parse and validate SANDBOX_MAX_LIFETIME_SECONDS (default 86400). + + Raises: + ValueError: If not an integer or below _MIN_SANDBOX_MAX_LIFETIME_SECONDS + -- a shorter lifetime would let reconcile reap live sandboxes. + """ + raw = os.environ.get("SANDBOX_MAX_LIFETIME_SECONDS", "") + if not raw: + return DEFAULT_SANDBOX_MAX_LIFETIME_SECONDS + try: + value = int(raw) + except ValueError: + raise ValueError(f"SANDBOX_MAX_LIFETIME_SECONDS={raw!r} is not an integer") from None + if value < _MIN_SANDBOX_MAX_LIFETIME_SECONDS: + raise ValueError( + f"SANDBOX_MAX_LIFETIME_SECONDS={value} is below the minimum " + f"{_MIN_SANDBOX_MAX_LIFETIME_SECONDS} (longest default sandbox life)" + ) + return value + + +def _create_spawner(owner_instance: str = ""): """Create spawner based on environment config. Thin env-var-reading wrapper around cloud_agents.spawner.factory.build_spawner @@ -92,7 +152,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_MAX_LIFETIME_SECONDS. """ if SPAWNER_TYPE == "openshell": from cloud_agents.spawner.factory import build_spawner @@ -106,7 +167,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", ""), - owner_instance=RUNNER_INSTANCE_ID, + owner_instance=owner_instance, + max_lifetime_seconds=_sandbox_max_lifetime_seconds(), ) if SPAWNER_TYPE == "": logger.info("No spawner configured — sandbox activity will use stub mode") @@ -117,47 +179,66 @@ def _create_spawner(): async def reconcile_orphaned_sandboxes( - spawner: AgentSpawner | None, owner_instance: str = "" + spawner: AgentSpawner | None, owner_instance: str = "", now: float | None = None ) -> None: - """Destroy this replica's orphaned sandboxes left from a previous crash. + """Destroy orphaned sandboxes left from a previous crash. - On startup, scans for sandboxes labelled "spawned-by=workflow-runner" - *and* "cloud-agents/owner-instance=" and destroys them. - This prevents resource leaks after unclean shutdowns without touching - sandboxes that other live runner replicas are still using. + On startup, lists sandboxes labelled "spawned-by=workflow-runner" once and + destroys those that either carry this replica's + "cloud-agents/owner-instance=" label, or whose + "cloud-agents/expires-at" is in the past regardless of owner (e.g. left + by a replaced pod whose name never comes back). This prevents resource + leaks after unclean shutdowns without touching sandboxes that other live + runner replicas are still using. - Sandboxes carrying spawned-by but a different owner (another replica) or - no owner label at all (spawned before owner labelling existed) are left - alone and only counted in a log line: there is no way to tell from here - whether their owner is still alive. When owner_instance is empty nothing - is destroyed. + Other replicas' unexpired sandboxes, sandboxes with no expires-at label + (spawned before expiry labelling existed) and sandboxes with a malformed + expires-at are left alone and logged. When owner_instance is empty only + expired sandboxes are destroyed. Args: spawner: The spawner instance, or None if no spawner is configured. - owner_instance: This replica's RUNNER_INSTANCE_ID. Must match the - value the spawner stamps on sandboxes it creates. + owner_instance: This replica's identity (see _runner_instance_id()). + Must match the value the spawner stamps on sandboxes it creates. + now: Current unix time; defaults to time.time(). Injectable for tests. """ if spawner is None: return - - # Must match OpenShellSpawner._SPAWNED_BY_LABEL / _OWNER_INSTANCE_LABEL_KEY. - spawned_by = {"spawned-by": "workflow-runner"} - if owner_instance: - orphans = await spawner.list_active( - {**spawned_by, "cloud-agents/owner-instance": owner_instance} - ) - else: + if not owner_instance: logger.warning( - "RUNNER_INSTANCE_ID not set — skipping orphaned sandbox cleanup " - "(cannot tell this replica's sandboxes from other replicas')" + "RUNNER_INSTANCE_ID/HOSTNAME not set — skipping own-instance orphan " + "cleanup (only expired sandboxes will be destroyed)" ) - orphans = [] - untouched = len(set(await spawner.list_active(spawned_by)) - set(orphans)) - if untouched: + now = time.time() if now is None else now + + # Label keys must match OpenShellSpawner._SPAWNED_BY_LABEL, + # _OWNER_INSTANCE_LABEL_KEY and _EXPIRES_AT_LABEL_KEY. + orphans = [] + no_expiry = 0 + for name, labels in await spawner.list_active_labels({"spawned-by": "workflow-runner"}): + if owner_instance and labels.get("cloud-agents/owner-instance") == owner_instance: + orphans.append(name) + continue + expires_at = labels.get("cloud-agents/expires-at") + 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) owned by other runner instances or with " - "no owner label untouched", - untouched, + "Leaving %d sandbox(es) with no expires-at label untouched " + "(legacy, or owned by another runner instance)", + no_expiry, ) cleaned = 0 failed_names = [] @@ -257,7 +338,8 @@ def build_temporal_app( configure_logging() init_tracing("workflow-runner") - spawner = _create_spawner() + owner_instance = _runner_instance_id() + spawner = _create_spawner(owner_instance) transcript_store = TranscriptStore.from_env() if transcript_store is not None: logger.info("Transcript store configured (TRANSCRIPT_DB_URL set)") @@ -269,7 +351,7 @@ def build_temporal_app( @asynccontextmanager async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]: """Connect Temporal client and start worker on startup.""" - await reconcile_orphaned_sandboxes(spawner, RUNNER_INSTANCE_ID) + await reconcile_orphaned_sandboxes(spawner, owner_instance) # Connect transcript store (best-effort: failures are non-fatal) if transcript_store is not None: diff --git a/tests/unit/spawner/test_base.py b/tests/unit/spawner/test_base.py index 60107f63..fc7ef1ce 100644 --- a/tests/unit/spawner/test_base.py +++ b/tests/unit/spawner/test_base.py @@ -435,3 +435,15 @@ 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 TestListActiveLabelsDefault: + """Spawners without label support report no labels, so reconcile treats + their sandboxes as legacy 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_active_labels({"spawned-by": "workflow-runner"}) == [("a1", {})] diff --git a/tests/unit/spawner/test_factory.py b/tests/unit/spawner/test_factory.py index f01738d8..70724eee 100644 --- a/tests/unit/spawner/test_factory.py +++ b/tests/unit/spawner/test_factory.py @@ -27,14 +27,20 @@ def test_builds_openshell_spawner_no_auth(self, mocker: MockerFixture) -> None: assert spawner._bearer_token == "" def test_owner_instance_forwarded(self, mocker: MockerFixture) -> None: - """owner_instance reaches OpenShellSpawner (stamped as an owner label on spawn).""" + """owner_instance/max_lifetime_seconds 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", owner_instance="runner-a") + spawner = build_spawner( + "openshell", + gateway_url="gw:17670", + owner_instance="runner-a", + max_lifetime_seconds=7200, + ) assert spawner._owner_instance == "runner-a" + assert spawner._max_lifetime_seconds == 7200 def test_strips_http_scheme_from_gateway_url(self, mocker: MockerFixture) -> None: """http(s):// prefix is stripped before building the gRPC endpoint.""" diff --git a/tests/unit/spawner/test_openshell_spawner.py b/tests/unit/spawner/test_openshell_spawner.py index d47af798..43540147 100644 --- a/tests/unit/spawner/test_openshell_spawner.py +++ b/tests/unit/spawner/test_openshell_spawner.py @@ -512,6 +512,47 @@ async def mock_ready(*args, **kwargs): "cloud-agents/owner-instance": "runner-a", } + @pytest.mark.asyncio + async def test_spawn_attaches_expires_at_label(self, mocker: MockerFixture) -> None: + """max_lifetime_seconds is stamped as cloud-agents/expires-at (unix + seconds of spawn time + lifetime) so any replica's reconcile can reap + the sandbox once it is past its maximum legitimate life.""" + 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, + max_lifetime_seconds=7200, + clock=lambda: 1_700_000_000.9, + ) + 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") + + await spawner.spawn( + "agent-1", "sandbox:latest", env={}, labels={"cloud-agents/expires-at": "9999999999"} + ) + + labels = mock_client.create.call_args.kwargs["labels"] + assert labels["cloud-agents/expires-at"] == "1700007200" + assert "cloud-agents/owner-instance" not in labels + @pytest.mark.asyncio async def test_spawn_with_credential_does_not_expose_real_value( self, mocker: MockerFixture @@ -1200,6 +1241,33 @@ async def test_list_active_queries_gateway_not_local_state(self, mocker: MockerF limit=1000, ) + @pytest.mark.asyncio + async def test_list_active_labels_returns_names_with_labels( + self, mocker: MockerFixture + ) -> None: + """One ListSandboxes call yields each agent name with its labels, so + reconcile can partition by owner/expiry client-side.""" + 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_active_labels({"spawned-by": "workflow-runner"}) + + assert result == [ + ("agent-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, + ) + @pytest.mark.asyncio async def test_list_active_without_labels_sends_no_selector( self, mocker: MockerFixture diff --git a/tests/unit/workflow/temporal/test_cleanup_metrics.py b/tests/unit/workflow/temporal/test_cleanup_metrics.py index b317f39f..badb4d30 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_active_labels.return_value = [ + ("orphan-1", {"cloud-agents/owner-instance": "runner-a"}), + ("orphan-2", {"cloud-agents/owner-instance": "runner-a"}), + ] 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_active_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_active_labels.return_value = [ + ("orphan-ok", {"cloud-agents/owner-instance": "runner-a"}), + ("orphan-fail", {"cloud-agents/owner-instance": "runner-a"}), + ("orphan-ok2", {"cloud-agents/owner-instance": "runner-a"}), + ] call_count = 0 diff --git a/tests/unit/workflow/temporal/test_startup_reconciliation.py b/tests/unit/workflow/temporal/test_startup_reconciliation.py index 8187ef2a..0bdf246c 100644 --- a/tests/unit/workflow/temporal/test_startup_reconciliation.py +++ b/tests/unit/workflow/temporal/test_startup_reconciliation.py @@ -6,112 +6,146 @@ import pytest +from cloud_agents.workflow.executor.temporal import entrypoint from cloud_agents.workflow.executor.temporal.entrypoint import reconcile_orphaned_sandboxes OWNER_KEY = "cloud-agents/owner-instance" +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, str | None]) -> AsyncMock: - """Build a spawner whose list_active() honours label selectors. +def _fake_spawner(sandboxes: dict[str, dict[str, str]]) -> AsyncMock: + """Build a spawner whose list_active_labels() returns sandboxes as-is. - sandboxes maps agent name -> owner-instance label value (None = legacy - sandbox carrying only spawned-by=workflow-runner). + sandboxes maps agent name -> labels beyond spawned-by (an empty dict is a + legacy sandbox carrying only spawned-by=workflow-runner). """ spawner = AsyncMock() - async def list_active(labels: dict[str, str] | None = None) -> list[str]: - labels = labels or {} - assert labels.get("spawned-by") == "workflow-runner" - if OWNER_KEY in labels: - return [name for name, owner in sandboxes.items() if owner == labels[OWNER_KEY]] - return list(sandboxes) + async def list_active_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_active.side_effect = list_active + spawner.list_active_labels.side_effect = list_active_labels return spawner +def _destroyed(spawner: AsyncMock) -> set[str]: + return {c.args[0] for c in spawner.destroy.call_args_list} + + class TestStartupReconciliation: """Tests for reconcile_orphaned_sandboxes.""" @pytest.mark.asyncio async def test_orphaned_containers_destroyed_on_startup(self) -> None: - """Startup reconciliation destroys this instance's orphaned sandboxes.""" - mock_spawner = _fake_spawner({"ca-orphan1": "runner-a", "ca-orphan2": "runner-a"}) + """Startup reconciliation destroys this instance's orphaned sandboxes, + expired or not, with a single gateway listing.""" + mock_spawner = _fake_spawner( + { + "ca-orphan1": {OWNER_KEY: "runner-a", EXPIRES_KEY: FUTURE}, + "ca-orphan2": {OWNER_KEY: "runner-a"}, + } + ) - await reconcile_orphaned_sandboxes(mock_spawner, owner_instance="runner-a") + await reconcile_orphaned_sandboxes(mock_spawner, owner_instance="runner-a", now=NOW) - mock_spawner.list_active.assert_any_call( - {"spawned-by": "workflow-runner", OWNER_KEY: "runner-a"}, - ) - assert mock_spawner.destroy.call_count == 2 - mock_spawner.destroy.assert_any_call("ca-orphan1") - mock_spawner.destroy.assert_any_call("ca-orphan2") + mock_spawner.list_active_labels.assert_called_once() + mock_spawner.list_active.assert_not_called() + assert _destroyed(mock_spawner) == {"ca-orphan1", "ca-orphan2"} @pytest.mark.asyncio - async def test_other_instance_sandboxes_survive(self) -> None: + async def test_other_instance_unexpired_sandboxes_survive(self) -> None: """A restarting replica must not destroy another live replica's sandboxes.""" mock_spawner = _fake_spawner( - {"ca-mine": "runner-a", "ca-theirs1": "runner-b", "ca-theirs2": "runner-c"} + { + "ca-mine": {OWNER_KEY: "runner-a", EXPIRES_KEY: FUTURE}, + "ca-theirs": {OWNER_KEY: "runner-b", EXPIRES_KEY: FUTURE}, + } ) - await reconcile_orphaned_sandboxes(mock_spawner, owner_instance="runner-a") + await reconcile_orphaned_sandboxes(mock_spawner, owner_instance="runner-a", now=NOW) - mock_spawner.destroy.assert_called_once_with("ca-mine") + assert _destroyed(mock_spawner) == {"ca-mine"} @pytest.mark.asyncio - async def test_legacy_unowned_sandboxes_left_alone(self) -> None: - """Sandboxes with spawned-by but no owner-instance label are never destroyed. + async def test_other_instance_expired_sandbox_destroyed(self) -> None: + """Sandboxes past expires-at are reaped regardless of owner (e.g. left + by a replaced pod whose name will never come back).""" + mock_spawner = _fake_spawner({"ca-stale": {OWNER_KEY: "runner-gone", EXPIRES_KEY: PAST}}) - They predate owner labelling, so there is no way to tell whether a - live replica still uses them (e.g. a long-lived chat sandbox). - """ - mock_spawner = _fake_spawner({"ca-legacy": None, "ca-mine": "runner-a"}) + await reconcile_orphaned_sandboxes(mock_spawner, owner_instance="runner-a", now=NOW) - await reconcile_orphaned_sandboxes(mock_spawner, owner_instance="runner-a") - - mock_spawner.destroy.assert_called_once_with("ca-mine") + assert _destroyed(mock_spawner) == {"ca-stale"} @pytest.mark.asyncio - async def test_unset_identity_destroys_nothing(self, caplog) -> None: - """Without an instance identity, reconcile fails safe: no destroys, a warning.""" - mock_spawner = _fake_spawner({"ca-legacy": None, "ca-other": "runner-b"}) + async def test_malformed_expires_at_kept_and_logged(self, caplog) -> None: + mock_spawner = _fake_spawner({"ca-weird": {OWNER_KEY: "runner-b", EXPIRES_KEY: "soon"}}) with caplog.at_level("WARNING"): - await reconcile_orphaned_sandboxes(mock_spawner, owner_instance="") + await reconcile_orphaned_sandboxes(mock_spawner, owner_instance="runner-a", now=NOW) + + mock_spawner.destroy.assert_not_called() + assert "ca-weird" in caplog.text + + @pytest.mark.asyncio + async def test_legacy_sandboxes_left_alone_and_logged(self, caplog) -> None: + """Sandboxes without expires-at (legacy, or another owner without a + configured lifetime) are never destroyed by another instance.""" + mock_spawner = _fake_spawner({"ca-legacy": {}, "ca-noexpiry": {OWNER_KEY: "runner-b"}}) + + with caplog.at_level("INFO"): + await reconcile_orphaned_sandboxes(mock_spawner, owner_instance="runner-a", now=NOW) mock_spawner.destroy.assert_not_called() + assert "2 sandbox(es)" in caplog.text + + @pytest.mark.asyncio + async def test_unset_identity_still_reaps_expired(self, caplog) -> None: + """Without an identity, own-instance cleanup is skipped with a warning, + but expired sandboxes are still destroyed.""" + mock_spawner = _fake_spawner( + { + "ca-expired": {OWNER_KEY: "runner-b", EXPIRES_KEY: PAST}, + "ca-live": {OWNER_KEY: "runner-b", EXPIRES_KEY: FUTURE}, + "ca-legacy": {}, + } + ) + + with caplog.at_level("WARNING"): + await reconcile_orphaned_sandboxes(mock_spawner, owner_instance="", now=NOW) + + assert _destroyed(mock_spawner) == {"ca-expired"} assert "RUNNER_INSTANCE_ID" in caplog.text @pytest.mark.asyncio async def test_unset_identity_is_default(self) -> None: - """Callers that pass no identity get the fail-safe behaviour.""" - mock_spawner = _fake_spawner({"ca-any": None}) + mock_spawner = _fake_spawner({"ca-any": {OWNER_KEY: ""}}) - await reconcile_orphaned_sandboxes(mock_spawner) + await reconcile_orphaned_sandboxes(mock_spawner, now=NOW) mock_spawner.destroy.assert_not_called() @pytest.mark.asyncio async def test_no_orphans_no_destroy(self) -> None: - """Startup with no orphans calls no destroy.""" mock_spawner = _fake_spawner({}) - await reconcile_orphaned_sandboxes(mock_spawner, owner_instance="runner-a") + await reconcile_orphaned_sandboxes(mock_spawner, owner_instance="runner-a", now=NOW) mock_spawner.destroy.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 = _fake_spawner({"orphan1": "a", "orphan2": "a", "orphan3": "a"}) - mock_spawner.destroy.side_effect = [ - None, - RuntimeError("destroy failed"), - None, - ] + mock_spawner = _fake_spawner({n: {OWNER_KEY: "a"} for n in ("o1", "o2", "o3")}) + mock_spawner.destroy.side_effect = [None, RuntimeError("destroy failed"), None] # Should not raise - await reconcile_orphaned_sandboxes(mock_spawner, owner_instance="a") + await reconcile_orphaned_sandboxes(mock_spawner, owner_instance="a", now=NOW) assert mock_spawner.destroy.call_count == 3 @@ -122,16 +156,80 @@ async def test_none_spawner_is_noop(self) -> None: await reconcile_orphaned_sandboxes(None, owner_instance="runner-a") -class TestCreateSpawnerOwnerInstance: - """_create_spawner() threads RUNNER_INSTANCE_ID into the spawner.""" +class TestRunnerInstanceId: + """_runner_instance_id(): RUNNER_INSTANCE_ID, else HOSTNAME, else "".""" + + def test_explicit_env_wins(self, monkeypatch) -> None: + monkeypatch.setenv("RUNNER_INSTANCE_ID", "workflow-runner-7d9f-abc12") + monkeypatch.setenv("HOSTNAME", "other") + assert entrypoint._runner_instance_id() == "workflow-runner-7d9f-abc12" + + def test_falls_back_to_hostname(self, monkeypatch) -> None: + monkeypatch.delenv("RUNNER_INSTANCE_ID", raising=False) + monkeypatch.setenv("HOSTNAME", "runner-host") + assert entrypoint._runner_instance_id() == "runner-host" + + def test_unset_returns_empty(self, monkeypatch) -> None: + monkeypatch.delenv("RUNNER_INSTANCE_ID", raising=False) + monkeypatch.delenv("HOSTNAME", raising=False) + assert entrypoint._runner_instance_id() == "" + + @pytest.mark.parametrize("bad", ["has space", "a" * 64, "-leading", "trailing.", "x/y"]) + def test_invalid_explicit_id_fails_startup(self, monkeypatch, bad) -> None: + monkeypatch.setenv("RUNNER_INSTANCE_ID", bad) + with pytest.raises(ValueError, match="RUNNER_INSTANCE_ID"): + entrypoint._runner_instance_id() + + def test_invalid_hostname_skipped_with_warning(self, monkeypatch, caplog) -> None: + """A HOSTNAME fallback that isn't a legal label value (e.g. a long + FQDN on a dev machine) disables own-instance cleanup instead of + failing startup.""" + monkeypatch.delenv("RUNNER_INSTANCE_ID", raising=False) + monkeypatch.setenv("HOSTNAME", "h" * 64) + with caplog.at_level("WARNING"): + assert entrypoint._runner_instance_id() == "" + assert "HOSTNAME" in caplog.text + + +class TestSandboxMaxLifetime: + """_sandbox_max_lifetime_seconds() parses and validates SANDBOX_MAX_LIFETIME_SECONDS.""" + + def test_default(self, monkeypatch) -> None: + monkeypatch.delenv("SANDBOX_MAX_LIFETIME_SECONDS", raising=False) + assert entrypoint._sandbox_max_lifetime_seconds() == 86400 - def test_runner_instance_id_passed_to_spawner(self, mocker) -> None: - from cloud_agents.workflow.executor.temporal import entrypoint + def test_configured(self, monkeypatch) -> None: + monkeypatch.setenv("SANDBOX_MAX_LIFETIME_SECONDS", "7200") + assert entrypoint._sandbox_max_lifetime_seconds() == 7200 + @pytest.mark.parametrize("bad", ["abc", "3899", "0", "-5"]) + def test_invalid_or_below_floor_fails_startup(self, monkeypatch, bad) -> None: + monkeypatch.setenv("SANDBOX_MAX_LIFETIME_SECONDS", bad) + with pytest.raises(ValueError, match="SANDBOX_MAX_LIFETIME_SECONDS"): + entrypoint._sandbox_max_lifetime_seconds() + + def test_floor_value_accepted(self, monkeypatch) -> None: + monkeypatch.setenv("SANDBOX_MAX_LIFETIME_SECONDS", "3900") + assert entrypoint._sandbox_max_lifetime_seconds() == 3900 + + +class TestCreateSpawnerWiring: + """_create_spawner() threads identity and lifetime into the spawner.""" + + def test_owner_and_lifetime_passed_to_spawner(self, mocker, monkeypatch) -> None: mocker.patch.object(entrypoint, "SPAWNER_TYPE", "openshell") - mocker.patch.object(entrypoint, "RUNNER_INSTANCE_ID", "runner-a", create=True) + monkeypatch.setenv("SANDBOX_MAX_LIFETIME_SECONDS", "7200") build = mocker.patch("cloud_agents.spawner.factory.build_spawner") - entrypoint._create_spawner() + entrypoint._create_spawner(owner_instance="runner-a") assert build.call_args.kwargs["owner_instance"] == "runner-a" + assert build.call_args.kwargs["max_lifetime_seconds"] == 7200 + + def test_lifetime_below_floor_fails_startup(self, mocker, monkeypatch) -> None: + mocker.patch.object(entrypoint, "SPAWNER_TYPE", "openshell") + monkeypatch.setenv("SANDBOX_MAX_LIFETIME_SECONDS", "60") + mocker.patch("cloud_agents.spawner.factory.build_spawner") + + with pytest.raises(ValueError, match="SANDBOX_MAX_LIFETIME_SECONDS"): + entrypoint._create_spawner(owner_instance="runner-a") From 72b730aafa8f499b37dc77efed544c376d526780 Mon Sep 17 00:00:00 2001 From: James Wong <2421248+jameswnl@users.noreply.github.com> Date: Sat, 31 Oct 2026 22:36:36 -0400 Subject: [PATCH 03/11] Bound each sandbox's expiry by its own lifetime A single global SANDBOX_MAX_LIFETIME_SECONDS could not cover steps whose unbounded timeout_seconds exceeded it, so another replica's restart could reap a still-running long step's sandbox. Spawn now takes a per-sandbox lifetime_seconds and stamps expires-at = clock + max(lifetime, SANDBOX_MIN_LIFETIME_SECONDS) + SANDBOX_EXPIRY_SKEW_SECONDS (defaults 86400 and 600). Workflow steps pass max(step timeout, permissions timeout) plus the 300s gateway and 60s HTTP ready waits, the 180s activity heartbeat timeout and 120s destroy grace; CLI sessions pass max_session_seconds plus the monitor interval, ready waits and grace. Spawns without a lifetime get no expiry. The startup floor check is gone because safety no longer depends on the global value. Caller-supplied owner-instance/expires-at labels are always dropped, label keys and timing constants live in cloud_agents.spawner.lifetime and are used by the spawner, reconcile and the Temporal workflow, and the HOSTNAME identity fallback warns that runners sharing a host network must set RUNNER_INSTANCE_ID. Docs cover mixed-version rollouts, one-time legacy cleanup and bare-process dev runs; the Podman compose files set RUNNER_INSTANCE_ID. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- deploy/podman/docker-compose.local.yaml | 2 + deploy/podman/docker-compose.yaml | 2 + docs/ARCHITECTURE.md | 2 +- docs/sandbox-contract.md | 65 +++++++-- src/cloud_agents/spawner/base.py | 7 + src/cloud_agents/spawner/factory.py | 9 +- src/cloud_agents/spawner/lifetime.py | 81 +++++++++++ src/cloud_agents/spawner/openshell_spawner.py | 75 ++++++---- src/cloud_agents/workflow/cli_session.py | 4 + src/cloud_agents/workflow/core/step_runner.py | 7 +- .../workflow/executor/temporal/activities.py | 7 +- .../workflow/executor/temporal/entrypoint.py | 74 ++++++---- .../workflow/executor/temporal/workflow.py | 8 +- tests/unit/spawner/test_base.py | 8 + tests/unit/spawner/test_factory.py | 8 +- tests/unit/spawner/test_lifetime.py | 47 ++++++ tests/unit/spawner/test_openshell_spawner.py | 80 ++++++++-- .../unit/workflow/temporal/test_activities.py | 40 +++++ .../temporal/test_startup_reconciliation.py | 137 +++++++++++++++--- tests/unit/workflow/test_cli_session.py | 21 +++ tests/unit/workflow/test_step_runner.py | 21 +++ 22 files changed, 591 insertions(+), 116 deletions(-) create mode 100644 src/cloud_agents/spawner/lifetime.py create mode 100644 tests/unit/spawner/test_lifetime.py diff --git a/CLAUDE.md b/CLAUDE.md index 791c1b96..3bc0a3f6 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. Reconcile destroys sandboxes whose `cloud-agents/owner-instance` label matches this replica's identity (`RUNNER_INSTANCE_ID`, Helm: pod name, else `HOSTNAME`) plus any sandbox past its `cloud-agents/expires-at` label (spawn time + `SANDBOX_MAX_LIFETIME_SECONDS`, default 86400, startup fails below 3900); other replicas' unexpired sandboxes and legacy sandboxes without `expires-at` are left alone. | +| 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 sandboxes whose `cloud-agents/owner-instance` label matches this replica's identity (`RUNNER_INSTANCE_ID`, Helm: pod name, else `HOSTNAME`) plus any sandbox past its `cloud-agents/expires-at` label (spawn time + max(per-sandbox lifetime from `spawner/lifetime.py`, `SANDBOX_MIN_LIFETIME_SECONDS`) + `SANDBOX_EXPIRY_SKEW_SECONDS`; spawns without a lifetime get no expiry); other replicas' unexpired sandboxes and legacy sandboxes without `expires-at` are left alone. Old and new runner versions must not run side by side for long (old runners destroy every `spawned-by` sandbox) -- see `docs/sandbox-contract.md#labels`. | | E2E guardrails | `openshell_spawner.py` | `e2e/test_guardrails.py::TestOpenShellGuardrails`, `TestOpenShellQueryTLS` | ## Database Migrations (Alembic) diff --git a/deploy/podman/docker-compose.local.yaml b/deploy/podman/docker-compose.local.yaml index 78ded4c4..b44e7d14 100644 --- a/deploy/podman/docker-compose.local.yaml +++ b/deploy/podman/docker-compose.local.yaml @@ -40,6 +40,8 @@ services: environment: WORKFLOW_ENGINE: local WORKFLOW_SPAWNER: openshell + # Stable per-runner identity for scoping startup orphan cleanup + RUNNER_INSTANCE_ID: workflow-runner OPENSHELL_GATEWAY_URL: ${OPENSHELL_GATEWAY_URL:?set to your separately-deployed OpenShell gateway address} AUTH_REQUIRED: "false" RUN_STATE_DB_URL: postgresql://workflow:workflow-pass@postgres:5432/cloud_agents diff --git a/deploy/podman/docker-compose.yaml b/deploy/podman/docker-compose.yaml index fc9b4ddc..8fbcf781 100644 --- a/deploy/podman/docker-compose.yaml +++ b/deploy/podman/docker-compose.yaml @@ -65,6 +65,8 @@ services: TEMPORAL_URL: temporal-server:7233 TEMPORAL_NAMESPACE: default WORKFLOW_SPAWNER: openshell + # Stable per-runner identity for scoping startup orphan cleanup + RUNNER_INSTANCE_ID: workflow-runner OPENSHELL_GATEWAY_URL: ${OPENSHELL_GATEWAY_URL:?set to your separately-deployed OpenShell gateway address} AUTH_REQUIRED: "false" OPENAI_API_KEY: ${OPENAI_API_KEY:-} diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 93f2a973..19e5e220 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, scoped to the restarting replica's own sandboxes via the `cloud-agents/owner-instance` label (`RUNNER_INSTANCE_ID`, else `HOSTNAME`) plus any sandbox past its `cloud-agents/expires-at` label (`SANDBOX_MAX_LIFETIME_SECONDS`). +- **Crash recovery** — content-hash pod naming for idempotent retries + startup orphan reconciliation for leaked containers, scoped to the restarting replica's own sandboxes via the `cloud-agents/owner-instance` label (`RUNNER_INSTANCE_ID`, else `HOSTNAME`) plus any sandbox past its per-sandbox `cloud-agents/expires-at` label (see [sandbox-contract.md](sandbox-contract.md#labels), including the upgrade/rollback caveat and one-time legacy cleanup). ### Dual Deployment diff --git a/docs/sandbox-contract.md b/docs/sandbox-contract.md index cc28b08c..f15371d6 100644 --- a/docs/sandbox-contract.md +++ b/docs/sandbox-contract.md @@ -130,7 +130,7 @@ Spawned sandbox pods carry these labels for lifecycle management: | `spawned-by` | `workflow-runner` (always set) | | `cloud-agents/agent-name` | Agent name (always set; the gateway assigns the sandbox name) | | `cloud-agents/owner-instance` | Runner replica's identity: `RUNNER_INSTANCE_ID`, else `HOSTNAME` (set only when one is available) | -| `cloud-agents/expires-at` | Unix seconds: spawn time + `SANDBOX_MAX_LIFETIME_SECONDS` (default 86400) | +| `cloud-agents/expires-at` | Unix seconds: 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 makes one `spawned-by=workflow-runner` listing and destroys sandboxes whose @@ -138,14 +138,55 @@ makes one `spawned-by=workflow-runner` listing and destroys sandboxes whose `RUNNER_INSTANCE_ID` to the pod name), plus any sandbox whose `cloud-agents/expires-at` is in the past regardless of owner (e.g. left by a replaced pod). Other replicas' unexpired sandboxes, sandboxes with no -`expires-at` label (spawned before it existed) and sandboxes with a malformed -`expires-at` are left alone and logged. With no identity, only expired -sandboxes are destroyed. - -An explicit `RUNNER_INSTANCE_ID` must be a valid label value or startup fails; -an invalid `HOSTNAME` fallback only disables own-instance cleanup with a -warning. `SANDBOX_MAX_LIFETIME_SECONDS` below 3900 (a CLI session's default -3600s plus the 300s sandbox ready wait) fails startup. A workflow step whose -`timeout_seconds` exceeds the lifetime isn't caught (the schema has no upper -bound) and its sandbox may be reaped by another replica's restart, so keep the -lifetime above your longest step timeout. +`expires-at` label and sandboxes with a malformed `expires-at` are left alone +and logged. With no identity, only expired sandboxes are destroyed. +Caller-supplied `owner-instance` / `expires-at` labels are always dropped. + +**Per-sandbox lifetime** (`cloud_agents/spawner/lifetime.py`). `expires-at` +must never be earlier than the sandbox's latest legitimate end, so each spawn +call site passes its own lifetime: + +- Workflow steps (Temporal activity and local engine): max(step + `timeout_seconds`, `permissions.timeout_seconds`; each defaulting to 600) + + 300s gateway ready wait + 60s HTTP ready wait + 180s activity heartbeat + timeout (a timed-out activity only learns of cancellation via a heartbeat) + + 120s destroy grace. Each retry attempt spawns a new sandbox (the attempt + number is part of the `ca-` name; the activity itself runs with + `maximum_attempts=1`), so the lifetime is per attempt. +- CLI sessions: `max_session_seconds` + the timeout monitor's check interval + + 300s + 60s + 120s. +- A spawn with no lifetime gets no `expires-at`, so only its owner can reap it. + +`SANDBOX_MIN_LIFETIME_SECONDS` (default 86400) is a floor, not a cap: it only +delays how soon another replica may reap an orphan. `SANDBOX_EXPIRY_SKEW_SECONDS` +(default 600) covers clock skew between replicas. Both must be non-negative +integers or startup fails. + +**Identity.** An explicit `RUNNER_INSTANCE_ID` must be a valid label value or +startup fails. The `HOSTNAME` fallback logs a warning: runners sharing a host +network (same hostname) must each set a distinct `RUNNER_INSTANCE_ID`. An +invalid `HOSTNAME` only disables own-instance cleanup. Bare-process dev runs +with neither variable set skip own-instance cleanup (expired sandboxes are +still reaped); the Podman compose files set `RUNNER_INSTANCE_ID`. + +**Upgrades and rollbacks.** Runners from before owner scoping destroy *every* +`spawned-by=workflow-runner` sandbox on startup, including new runners' live +ones. Don't run old and new runner versions side by side for long: finish the +rollout promptly, or use a `Recreate` deployment strategy. A rollback carries +the same risk in reverse. + +**Legacy sandboxes.** Sandboxes spawned by older runners carry neither +`owner-instance` nor `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`): + +```python +from openshell import SandboxClient + +client = SandboxClient(endpoint="") +for ref in client.list(workspace="default", label_selector="spawned-by=workflow-runner", limit=1000): + if "cloud-agents/owner-instance" not in ref.labels and "cloud-agents/expires-at" not in ref.labels: + print("deleting", ref.name) + client.delete(ref.name, workspace="default") +``` diff --git a/src/cloud_agents/spawner/base.py b/src/cloud_agents/spawner/base.py index e35f4bd5..eca728ee 100644 --- a/src/cloud_agents/spawner/base.py +++ b/src/cloud_agents/spawner/base.py @@ -126,6 +126,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. @@ -166,6 +167,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. @@ -195,6 +201,7 @@ 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: diff --git a/src/cloud_agents/spawner/factory.py b/src/cloud_agents/spawner/factory.py index 2ff86154..96816fad 100644 --- a/src/cloud_agents/spawner/factory.py +++ b/src/cloud_agents/spawner/factory.py @@ -33,7 +33,14 @@ # 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", "owner_instance", "max_lifetime_seconds"} + { + "max_pods", + "extra_readable_paths", + "extra_env", + "owner_instance", + "min_lifetime_seconds", + "expiry_skew_seconds", + } ) diff --git a/src/cloud_agents/spawner/lifetime.py b/src/cloud_agents/spawner/lifetime.py new file mode 100644 index 00000000..a2cc42bf --- /dev/null +++ b/src/cloud_agents/spawner/lifetime.py @@ -0,0 +1,81 @@ +"""Sandbox ownership labels and lifetime bounds for orphan reconciliation. + +Shared by OpenShellSpawner (which stamps the labels at spawn time) and +reconcile_orphaned_sandboxes() (which filters on them at startup), and by 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 end, or another replica's startup reconcile could destroy +it while still in use. Each spawn call site therefore passes a per-sandbox +lifetime_seconds covering everything that can keep the sandbox alive. +""" + +from __future__ import annotations + +import math +from typing import Any + +# 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"} +# Runner replica that spawned the sandbox; reconcile destroys its own. +OWNER_INSTANCE_LABEL_KEY = "cloud-agents/owner-instance" +# Unix seconds after which any replica's reconcile may destroy the sandbox. +EXPIRES_AT_LABEL_KEY = "cloud-agents/expires-at" +# Set only by the spawner from its own config; dropped from caller labels. +RESERVED_LABEL_KEYS = frozenset({OWNER_INSTANCE_LABEL_KEY, EXPIRES_AT_LABEL_KEY}) + +# Step timeout when neither the step nor its definition sets one; becomes the +# run_sandbox_step activity's start_to_close_timeout (temporal/workflow.py) +# and the default sandbox HTTP timeout (permissions.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 +# run_sandbox_step's heartbeat_timeout (temporal/workflow.py): cancellation +# after start_to_close_timeout reaches the activity only via a heartbeat. +SANDBOX_ACTIVITY_HEARTBEAT_TIMEOUT_SECONDS = 180 +# Time for the finally-block destroy() to run after the step ends. +SANDBOX_DESTROY_GRACE_SECONDS = 120 + + +def step_sandbox_lifetime_seconds(step: dict[str, Any]) -> int: + """Latest legitimate life of one workflow step attempt's sandbox. + + The step's run time is bounded by the larger of its timeout_seconds + (Temporal start_to_close_timeout) and permissions.timeout_seconds (the + sandbox HTTP call timeout, the only bound on the local engine), plus the + spawn readiness waits, the heartbeat delay before a timed-out activity + sees cancellation, and destroy grace. Each retry attempt spawns a fresh + sandbox (attempt is part of compute_pod_name()), so this is per attempt. + """ + permissions = step.get("permissions") or {} + run_seconds = max( + step.get("timeout_seconds") or DEFAULT_STEP_TIMEOUT_SECONDS, + permissions.get("timeout_seconds") or DEFAULT_STEP_TIMEOUT_SECONDS, + ) + return ( + math.ceil(run_seconds) + + SANDBOX_GATEWAY_READY_TIMEOUT_SECONDS + + SANDBOX_HTTP_READY_TIMEOUT_SECONDS + + SANDBOX_ACTIVITY_HEARTBEAT_TIMEOUT_SECONDS + + SANDBOX_DESTROY_GRACE_SECONDS + ) + + +def cli_session_lifetime_seconds(max_session_seconds: int, check_interval: float) -> int: + """Latest legitimate life of a CLI session sandbox. + + CLISessionLauncher's timeout monitor destroys a session within one check + interval after max_session_seconds; add the spawn readiness waits and + destroy grace. + """ + return ( + max_session_seconds + + math.ceil(check_interval) + + SANDBOX_GATEWAY_READY_TIMEOUT_SECONDS + + SANDBOX_HTTP_READY_TIMEOUT_SECONDS + + SANDBOX_DESTROY_GRACE_SECONDS + ) diff --git a/src/cloud_agents/spawner/openshell_spawner.py b/src/cloud_agents/spawner/openshell_spawner.py index 1b8ffdf8..e1f1206d 100644 --- a/src/cloud_agents/spawner/openshell_spawner.py +++ b/src/cloud_agents/spawner/openshell_spawner.py @@ -26,6 +26,14 @@ import httpx from cloud_agents.spawner.base import AgentSpawner +from cloud_agents.spawner.lifetime import ( + EXPIRES_AT_LABEL_KEY, + OWNER_INSTANCE_LABEL_KEY, + RESERVED_LABEL_KEYS, + SANDBOX_GATEWAY_READY_TIMEOUT_SECONDS, + SANDBOX_HTTP_READY_TIMEOUT_SECONDS, + SPAWNED_BY_LABEL, +) if TYPE_CHECKING: from cloud_agents.spawner.base import SpawnConfig @@ -165,23 +173,22 @@ class OpenShellSpawner(AgentSpawner): # 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 # Identifies which runner replica spawned a sandbox (value: the # owner_instance constructor arg, wired from RUNNER_INSTANCE_ID) so # reconcile_orphaned_sandboxes() only destroys this replica's own orphans, # never another live replica's sandboxes. Omitted when owner_instance is - # unset. Must match the key reconcile_orphaned_sandboxes() filters on. - _OWNER_INSTANCE_LABEL_KEY: ClassVar[str] = "cloud-agents/owner-instance" + # unset. + _OWNER_INSTANCE_LABEL_KEY: ClassVar[str] = OWNER_INSTANCE_LABEL_KEY # Unix seconds after which the sandbox has outlived any legitimate use - # (spawn time + max_lifetime_seconds). Lets any replica's - # reconcile_orphaned_sandboxes() reap sandboxes left by a replaced pod, - # whose owner-instance value will never come back. Omitted when - # max_lifetime_seconds is unset. Must match the key reconcile filters on. - _EXPIRES_AT_LABEL_KEY: ClassVar[str] = "cloud-agents/expires-at" + # (spawn time + max(lifetime_seconds, min_lifetime_seconds) + skew). Lets + # any replica's reconcile_orphaned_sandboxes() reap sandboxes left by a + # replaced pod, whose owner-instance value will never come back. 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 @@ -297,7 +304,8 @@ def __init__( extra_readable_paths: list[str] | None = None, extra_env: dict[str, str] | None = None, owner_instance: str = "", - max_lifetime_seconds: int | None = None, + min_lifetime_seconds: int = 0, + expiry_skew_seconds: int = 600, clock: Callable[[], float] = time.time, **kwargs: Any, ) -> None: @@ -349,17 +357,19 @@ def __init__( _OWNER_INSTANCE_LABEL_KEY label so startup reconciliation can tell this replica's orphans apart from other replicas' live sandboxes. Empty means no owner label is attached. - max_lifetime_seconds: Longest legitimate life of a sandbox this - spawner creates. Attached to every sandbox as the - _EXPIRES_AT_LABEL_KEY label (spawn time + this value) so - startup reconciliation on any replica can reap it once - expired. None means no expiry label is attached (the sandbox - is then never reaped by another replica). + 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. + 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) self._owner_instance = owner_instance - self._max_lifetime_seconds = max_lifetime_seconds + self._min_lifetime_seconds = min_lifetime_seconds + self._expiry_skew_seconds = expiry_skew_seconds self._clock = clock self._client = openshell_client self._workspace = workspace @@ -914,6 +924,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 @@ -1051,20 +1062,30 @@ async def _do_spawn( ) raise - # Merge caller labels with the fixed spawned-by label, the - # agent_name recovery label and the owner-instance/expires-at labels; - # all always win over caller-supplied labels of the same key so a - # caller can't accidentally suppress orphan discovery (issue #224). + # 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). Caller-supplied owner-instance / + # expires-at are always dropped: only this spawner's own config may + # mark a sandbox as owned by, or expired for, a runner 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, } if self._owner_instance: sandbox_labels[self._OWNER_INSTANCE_LABEL_KEY] = self._owner_instance - if self._max_lifetime_seconds is not None: + if lifetime_seconds is None: + logger.debug( + "No lifetime_seconds for agent '%s' — no expires-at label; only its " + "owner instance's startup reconcile can reap it", + agent_name, + ) + else: sandbox_labels[self._EXPIRES_AT_LABEL_KEY] = str( - int(self._clock()) + self._max_lifetime_seconds + int(self._clock()) + + max(lifetime_seconds, self._min_lifetime_seconds) + + self._expiry_skew_seconds ) spec = openshell_pb2.SandboxSpec( @@ -1108,7 +1129,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 @@ -1156,7 +1177,7 @@ 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") diff --git a/src/cloud_agents/workflow/cli_session.py b/src/cloud_agents/workflow/cli_session.py index 46cdb4f6..3be0ecca 100644 --- a/src/cloud_agents/workflow/cli_session.py +++ b/src/cloud_agents/workflow/cli_session.py @@ -21,6 +21,7 @@ from pydantic import BaseModel from cloud_agents.runtime.audit import emit_audit +from cloud_agents.spawner.lifetime import cli_session_lifetime_seconds if TYPE_CHECKING: from cloud_agents.spawner.base import AgentSpawner @@ -169,6 +170,9 @@ async def launch( service_account=service_account, credential_secret_name=credential_secret_name, mcp_secret_mounts=mcp_secret_mounts, + lifetime_seconds=cli_session_lifetime_seconds( + self.max_session_seconds, self._check_interval + ), ) info = CLISessionInfo( diff --git a/src/cloud_agents/workflow/core/step_runner.py b/src/cloud_agents/workflow/core/step_runner.py index 636870e3..e42eece3 100644 --- a/src/cloud_agents/workflow/core/step_runner.py +++ b/src/cloud_agents/workflow/core/step_runner.py @@ -25,6 +25,10 @@ from cloud_agents.runtime.tracing import get_tracer, inject_traceparent from cloud_agents.runtime.audit import emit_audit from cloud_agents.runtime.circuit_breaker import ProviderCircuitBreaker +from cloud_agents.spawner.lifetime import ( + DEFAULT_STEP_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 @@ -307,7 +311,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 = float(permissions.get("timeout_seconds", DEFAULT_STEP_TIMEOUT_SECONDS)) if spawner is None: logger.info("No spawner configured — returning stub result for '%s'", step_name) @@ -362,6 +366,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, diff --git a/src/cloud_agents/workflow/executor/temporal/activities.py b/src/cloud_agents/workflow/executor/temporal/activities.py index 60860308..9f3419e8 100644 --- a/src/cloud_agents/workflow/executor/temporal/activities.py +++ b/src/cloud_agents/workflow/executor/temporal/activities.py @@ -23,6 +23,10 @@ from cloud_agents.runtime.tracing import get_tracer from cloud_agents.runtime.audit import emit_audit from cloud_agents.runtime.circuit_breaker import ProviderCircuitBreaker +from cloud_agents.spawner.lifetime import ( + DEFAULT_STEP_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 @@ -527,7 +531,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 = float(permissions.get("timeout_seconds", DEFAULT_STEP_TIMEOUT_SECONDS)) if spawner is None: logger.info("No spawner configured — returning stub result for '%s'", step_name) @@ -580,6 +584,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, diff --git a/src/cloud_agents/workflow/executor/temporal/entrypoint.py b/src/cloud_agents/workflow/executor/temporal/entrypoint.py index 48d04c4c..aba30dfc 100644 --- a/src/cloud_agents/workflow/executor/temporal/entrypoint.py +++ b/src/cloud_agents/workflow/executor/temporal/entrypoint.py @@ -21,6 +21,11 @@ from temporalio.worker import Worker from cloud_agents.runtime.tracing import init_tracing +from cloud_agents.spawner.lifetime import ( + EXPIRES_AT_LABEL_KEY, + OWNER_INSTANCE_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 @@ -78,14 +83,13 @@ def _build_tls_config(): # Kubernetes label value syntax; owner-instance is stamped as a sandbox label. _LABEL_VALUE_RE = re.compile(r"^(?:[A-Za-z0-9](?:[-A-Za-z0-9_.]{0,61}[A-Za-z0-9])?)?$") -DEFAULT_SANDBOX_MAX_LIFETIME_SECONDS = 86400 -# Floor for SANDBOX_MAX_LIFETIME_SECONDS: the longest sandbox life this runner -# creates with default settings -- a CLI session's DEFAULT_MAX_SESSION_SECONDS -# (3600; agent steps default to timeout_seconds=600) plus OpenShellSpawner's -# 300s gateway wait_ready. Per-workflow step timeout_seconds has no upper -# bound in the schema, so a step configured longer than the lifetime can't be -# caught here and may be reaped by another replica's startup reconcile. -_MIN_SANDBOX_MAX_LIFETIME_SECONDS = 3600 + 300 +# Floor for every sandbox's expires-at label, on top of its own per-sandbox +# lifetime (cloud_agents.spawner.lifetime). Safety comes from the per-sandbox +# lifetime, so any non-negative value is safe; the floor only delays how soon +# another replica may reap an orphan. +DEFAULT_SANDBOX_MIN_LIFETIME_SECONDS = 86400 +# Added to every expires-at for clock skew between replicas. +DEFAULT_SANDBOX_EXPIRY_SKEW_SECONDS = 600 def _runner_instance_id() -> str: @@ -115,31 +119,42 @@ def _runner_instance_id() -> str: hostname, ) return "" + if hostname: + logger.warning( + "RUNNER_INSTANCE_ID not set — using HOSTNAME=%r as runner identity. " + "Runners sharing a host network (same hostname) must each set a " + "distinct RUNNER_INSTANCE_ID, or they will reap each other's sandboxes", + hostname, + ) return hostname -def _sandbox_max_lifetime_seconds() -> int: - """Parse and validate SANDBOX_MAX_LIFETIME_SECONDS (default 86400). - - Raises: - ValueError: If not an integer or below _MIN_SANDBOX_MAX_LIFETIME_SECONDS - -- a shorter lifetime would let reconcile reap live sandboxes. - """ - raw = os.environ.get("SANDBOX_MAX_LIFETIME_SECONDS", "") +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_SANDBOX_MAX_LIFETIME_SECONDS + return default try: value = int(raw) except ValueError: - raise ValueError(f"SANDBOX_MAX_LIFETIME_SECONDS={raw!r} is not an integer") from None - if value < _MIN_SANDBOX_MAX_LIFETIME_SECONDS: - raise ValueError( - f"SANDBOX_MAX_LIFETIME_SECONDS={value} is below the minimum " - f"{_MIN_SANDBOX_MAX_LIFETIME_SECONDS} (longest default sandbox life)" - ) + 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(owner_instance: str = ""): """Create spawner based on environment config. @@ -153,7 +168,7 @@ def _create_spawner(owner_instance: str = ""): 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. Also raised for - an invalid SANDBOX_MAX_LIFETIME_SECONDS. + an invalid SANDBOX_MIN_LIFETIME_SECONDS / SANDBOX_EXPIRY_SKEW_SECONDS. """ if SPAWNER_TYPE == "openshell": from cloud_agents.spawner.factory import build_spawner @@ -168,7 +183,8 @@ def _create_spawner(owner_instance: str = ""): tls_key=os.environ.get("OPENSHELL_TLS_KEY", ""), bearer_token=os.environ.get("OPENSHELL_BEARER_TOKEN", ""), owner_instance=owner_instance, - max_lifetime_seconds=_sandbox_max_lifetime_seconds(), + 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") @@ -211,15 +227,13 @@ async def reconcile_orphaned_sandboxes( ) now = time.time() if now is None else now - # Label keys must match OpenShellSpawner._SPAWNED_BY_LABEL, - # _OWNER_INSTANCE_LABEL_KEY and _EXPIRES_AT_LABEL_KEY. orphans = [] no_expiry = 0 - for name, labels in await spawner.list_active_labels({"spawned-by": "workflow-runner"}): - if owner_instance and labels.get("cloud-agents/owner-instance") == owner_instance: + for name, labels in await spawner.list_active_labels(SPAWNED_BY_LABEL): + if owner_instance and labels.get(OWNER_INSTANCE_LABEL_KEY) == owner_instance: orphans.append(name) continue - expires_at = labels.get("cloud-agents/expires-at") + expires_at = labels.get(EXPIRES_AT_LABEL_KEY) if expires_at is None: no_expiry += 1 continue diff --git a/src/cloud_agents/workflow/executor/temporal/workflow.py b/src/cloud_agents/workflow/executor/temporal/workflow.py index 30751a04..763d1ba2 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 fc7ef1ce..0ac8dffa 100644 --- a/tests/unit/spawner/test_base.py +++ b/tests/unit/spawner/test_base.py @@ -447,3 +447,11 @@ async def test_default_returns_empty_labels(self) -> None: await spawner.spawn("a1", "img", env={}) assert await spawner.list_active_labels({"spawned-by": "workflow-runner"}) == [("a1", {})] + + +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 70724eee..9bcad2f6 100644 --- a/tests/unit/spawner/test_factory.py +++ b/tests/unit/spawner/test_factory.py @@ -27,7 +27,7 @@ def test_builds_openshell_spawner_no_auth(self, mocker: MockerFixture) -> None: assert spawner._bearer_token == "" def test_owner_instance_forwarded(self, mocker: MockerFixture) -> None: - """owner_instance/max_lifetime_seconds reach OpenShellSpawner (stamped as labels on spawn).""" + """Owner/lifetime settings reach OpenShellSpawner (stamped as labels on spawn).""" from cloud_agents.spawner.factory import build_spawner mocker.patch("openshell.SandboxClient") @@ -36,11 +36,13 @@ def test_owner_instance_forwarded(self, mocker: MockerFixture) -> None: "openshell", gateway_url="gw:17670", owner_instance="runner-a", - max_lifetime_seconds=7200, + min_lifetime_seconds=7200, + expiry_skew_seconds=30, ) assert spawner._owner_instance == "runner-a" - assert spawner._max_lifetime_seconds == 7200 + 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.""" diff --git a/tests/unit/spawner/test_lifetime.py b/tests/unit/spawner/test_lifetime.py new file mode 100644 index 00000000..b01e70cf --- /dev/null +++ b/tests/unit/spawner/test_lifetime.py @@ -0,0 +1,47 @@ +"""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 ( + cli_session_lifetime_seconds, + step_sandbox_lifetime_seconds, +) + +# Everything around the step's own run time: gateway ready wait + HTTP ready +# wait + Temporal heartbeat timeout + destroy grace. +STEP_OVERHEAD = 300 + 60 + 180 + 120 + + +class TestStepSandboxLifetime: + def test_default_step_timeout(self) -> None: + assert step_sandbox_lifetime_seconds({"name": "s"}) == 600 + STEP_OVERHEAD + + def test_step_timeout_drives_lifetime(self) -> None: + assert step_sandbox_lifetime_seconds({"timeout_seconds": 200_000}) == ( + 200_000 + STEP_OVERHEAD + ) + + def test_permissions_timeout_wins_when_longer(self) -> None: + step = {"timeout_seconds": 100, "permissions": {"timeout_seconds": 5000}} + assert step_sandbox_lifetime_seconds(step) == 5000 + STEP_OVERHEAD + + def test_step_timeout_wins_when_longer(self) -> None: + step = {"timeout_seconds": 9000, "permissions": {"timeout_seconds": 50}} + assert step_sandbox_lifetime_seconds(step) == 9000 + STEP_OVERHEAD + + def test_constants_match_their_sources(self) -> None: + """The margins mirror the real waits/timeouts they bound.""" + assert lifetime.DEFAULT_STEP_TIMEOUT_SECONDS == 600 + assert lifetime.SANDBOX_GATEWAY_READY_TIMEOUT_SECONDS == 300 + assert lifetime.SANDBOX_HTTP_READY_TIMEOUT_SECONDS == 60 + assert lifetime.SANDBOX_ACTIVITY_HEARTBEAT_TIMEOUT_SECONDS == 180 + + +class TestCliSessionLifetime: + def test_follows_max_session_seconds(self) -> None: + assert cli_session_lifetime_seconds(3600, 30.0) == 3600 + 30 + 300 + 60 + 120 + assert cli_session_lifetime_seconds(7200, 30.0) == 7200 + 30 + 300 + 60 + 120 + + def test_rounds_check_interval_up(self) -> None: + assert cli_session_lifetime_seconds(100, 0.5) == 100 + 1 + 300 + 60 + 120 diff --git a/tests/unit/spawner/test_openshell_spawner.py b/tests/unit/spawner/test_openshell_spawner.py index 43540147..b70b305e 100644 --- a/tests/unit/spawner/test_openshell_spawner.py +++ b/tests/unit/spawner/test_openshell_spawner.py @@ -512,11 +512,9 @@ async def mock_ready(*args, **kwargs): "cloud-agents/owner-instance": "runner-a", } - @pytest.mark.asyncio - async def test_spawn_attaches_expires_at_label(self, mocker: MockerFixture) -> None: - """max_lifetime_seconds is stamped as cloud-agents/expires-at (unix - seconds of spawn time + lifetime) so any replica's reconcile can reap - the sandbox once it is past its maximum legitimate life.""" + @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: @@ -530,11 +528,7 @@ def __init__(self, name): mock_client.wait_ready.return_value = SandboxRef("sb") mock_client.exec_stream = lambda *a, **k: iter([]) - spawner = OpenShellSpawner( - openshell_client=mock_client, - max_lifetime_seconds=7200, - clock=lambda: 1_700_000_000.9, - ) + spawner = OpenShellSpawner(openshell_client=mock_client, **kwargs) mocker.patch.object( spawner, "_expose_service", return_value=("http://gateway:17670", "host") ) @@ -544,14 +538,72 @@ async def mock_ready(*args, **kwargs): mocker.patch.object(spawner, "_wait_ready_with_host", side_effect=mock_ready) mocker.patch.object(OpenShellSpawner, "_build_network_policy") + return spawner, mock_client - await spawner.spawn( - "agent-1", "sandbox:latest", env={}, labels={"cloud-agents/expires-at": "9999999999"} + @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"] + assert labels["cloud-agents/expires-at"] == str(1_700_000_000 + 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"] == "1700007200" - assert "cloud-agents/owner-instance" not in 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 (only the owner may reap + 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.asyncio + async def test_spawn_strips_reserved_caller_labels_when_unconfigured( + self, mocker: MockerFixture + ) -> None: + """Caller-supplied owner-instance/expires-at labels are always dropped, + even when the spawner has no owner or lifetime to stamp -- otherwise a + caller could make a sandbox look owned by (or expired for) a 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( diff --git a/tests/unit/workflow/temporal/test_activities.py b/tests/unit/workflow/temporal/test_activities.py index 48f52e37..cdd75ed5 100644 --- a/tests/unit/workflow/temporal/test_activities.py +++ b/tests/unit/workflow/temporal/test_activities.py @@ -375,6 +375,46 @@ 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 own timeout, so a long + step's expires-at outlasts its start_to_close_timeout.""" + 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", "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.""" diff --git a/tests/unit/workflow/temporal/test_startup_reconciliation.py b/tests/unit/workflow/temporal/test_startup_reconciliation.py index 0bdf246c..91694e8d 100644 --- a/tests/unit/workflow/temporal/test_startup_reconciliation.py +++ b/tests/unit/workflow/temporal/test_startup_reconciliation.py @@ -164,10 +164,15 @@ def test_explicit_env_wins(self, monkeypatch) -> None: monkeypatch.setenv("HOSTNAME", "other") assert entrypoint._runner_instance_id() == "workflow-runner-7d9f-abc12" - def test_falls_back_to_hostname(self, monkeypatch) -> None: + def test_falls_back_to_hostname_with_warning(self, monkeypatch, caplog) -> None: + """HOSTNAME isn't unique for runners sharing a host network, so the + fallback warns to set RUNNER_INSTANCE_ID.""" monkeypatch.delenv("RUNNER_INSTANCE_ID", raising=False) monkeypatch.setenv("HOSTNAME", "runner-host") - assert entrypoint._runner_instance_id() == "runner-host" + with caplog.at_level("WARNING"): + assert entrypoint._runner_instance_id() == "runner-host" + assert "RUNNER_INSTANCE_ID" in caplog.text + assert "host network" in caplog.text def test_unset_returns_empty(self, monkeypatch) -> None: monkeypatch.delenv("RUNNER_INSTANCE_ID", raising=False) @@ -191,45 +196,131 @@ def test_invalid_hostname_skipped_with_warning(self, monkeypatch, caplog) -> Non assert "HOSTNAME" in caplog.text -class TestSandboxMaxLifetime: - """_sandbox_max_lifetime_seconds() parses and validates SANDBOX_MAX_LIFETIME_SECONDS.""" +class TestSandboxLifetimeSettings: + """SANDBOX_MIN_LIFETIME_SECONDS / SANDBOX_EXPIRY_SKEW_SECONDS parsing.""" - def test_default(self, monkeypatch) -> None: - monkeypatch.delenv("SANDBOX_MAX_LIFETIME_SECONDS", raising=False) - assert entrypoint._sandbox_max_lifetime_seconds() == 86400 + 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_MAX_LIFETIME_SECONDS", "7200") - assert entrypoint._sandbox_max_lifetime_seconds() == 7200 + 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", "3899", "0", "-5"]) - def test_invalid_or_below_floor_fails_startup(self, monkeypatch, bad) -> None: - monkeypatch.setenv("SANDBOX_MAX_LIFETIME_SECONDS", bad) - with pytest.raises(ValueError, match="SANDBOX_MAX_LIFETIME_SECONDS"): - entrypoint._sandbox_max_lifetime_seconds() + @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() - def test_floor_value_accepted(self, monkeypatch) -> None: - monkeypatch.setenv("SANDBOX_MAX_LIFETIME_SECONDS", "3900") - assert entrypoint._sandbox_max_lifetime_seconds() == 3900 + @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() class TestCreateSpawnerWiring: - """_create_spawner() threads identity and lifetime into the spawner.""" + """_create_spawner() threads identity and lifetime settings into the spawner.""" def test_owner_and_lifetime_passed_to_spawner(self, mocker, monkeypatch) -> None: mocker.patch.object(entrypoint, "SPAWNER_TYPE", "openshell") - monkeypatch.setenv("SANDBOX_MAX_LIFETIME_SECONDS", "7200") + 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(owner_instance="runner-a") assert build.call_args.kwargs["owner_instance"] == "runner-a" - assert build.call_args.kwargs["max_lifetime_seconds"] == 7200 + assert build.call_args.kwargs["min_lifetime_seconds"] == 7200 + assert build.call_args.kwargs["expiry_skew_seconds"] == 45 - def test_lifetime_below_floor_fails_startup(self, mocker, monkeypatch) -> None: + def test_invalid_lifetime_fails_startup(self, mocker, monkeypatch) -> None: mocker.patch.object(entrypoint, "SPAWNER_TYPE", "openshell") - monkeypatch.setenv("SANDBOX_MAX_LIFETIME_SECONDS", "60") + monkeypatch.setenv("SANDBOX_MIN_LIFETIME_SECONDS", "nope") mocker.patch("cloud_agents.spawner.factory.build_spawner") - with pytest.raises(ValueError, match="SANDBOX_MAX_LIFETIME_SECONDS"): + with pytest.raises(ValueError, match="SANDBOX_MIN_LIFETIME_SECONDS"): entrypoint._create_spawner(owner_instance="runner-a") + + +class TestLongStepSurvivesOtherReplicaRestart: + """End to end: spawn label -> another replica's reconcile.""" + + @staticmethod + async def _expires_at_for_step(mocker, step: dict, spawn_time: float) -> str: + from cloud_agents.spawner.lifetime import step_sandbox_lifetime_seconds + from cloud_agents.spawner.openshell_spawner import OpenShellSpawner + + class SandboxRef: + id = "id" + name = "sb" + + client = mocker.Mock() + client.create.return_value = SandboxRef() + client.exec_stream = lambda *a, **k: iter([]) + spawner = OpenShellSpawner( + openshell_client=client, + owner_instance="runner-b", + min_lifetime_seconds=86400, + expiry_skew_seconds=600, + clock=lambda: spawn_time, + ) + 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") + await spawner.spawn( + "ca-long", "img", env={}, lifetime_seconds=step_sandbox_lifetime_seconds(step) + ) + return client.create.call_args.kwargs["labels"][EXPIRES_KEY] + + @pytest.mark.asyncio + async def test_step_longer_than_global_minimum_kept_until_its_end(self, mocker) -> None: + from cloud_agents.spawner.lifetime import step_sandbox_lifetime_seconds + + step = {"name": "long", "timeout_seconds": 200_000} # > 86400 global minimum + expires_at = await self._expires_at_for_step(mocker, step, spawn_time=NOW) + + latest_legit_end = NOW + step_sandbox_lifetime_seconds(step) + assert int(expires_at) >= NOW + 200_000 + 300 + 60 + 180 + assert int(expires_at) >= latest_legit_end + + other = _fake_spawner({"ca-long": {OWNER_KEY: "runner-b", EXPIRES_KEY: expires_at}}) + await reconcile_orphaned_sandboxes( + other, owner_instance="runner-a", now=latest_legit_end + 600 / 2 + ) + other.destroy.assert_not_called() + + await reconcile_orphaned_sandboxes( + other, owner_instance="runner-a", now=latest_legit_end + 600 + 1 + ) + other.destroy.assert_called_once_with("ca-long") + + @pytest.mark.asyncio + async def test_no_lifetime_spawn_never_reaped_by_other_instance(self, mocker) -> None: + from cloud_agents.spawner.openshell_spawner import OpenShellSpawner + + class SandboxRef: + id = "id" + name = "sb" + + client = mocker.Mock() + client.create.return_value = SandboxRef() + client.exec_stream = lambda *a, **k: iter([]) + spawner = OpenShellSpawner( + openshell_client=client, owner_instance="runner-b", min_lifetime_seconds=60 + ) + 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") + await spawner.spawn("ca-nolife", "img", env={}) + labels = dict(client.create.call_args.kwargs["labels"]) + labels.pop("spawned-by") + + other = _fake_spawner({"ca-nolife": labels}) + await reconcile_orphaned_sandboxes(other, owner_instance="runner-a", now=NOW * 10) + other.destroy.assert_not_called() diff --git a/tests/unit/workflow/test_cli_session.py b/tests/unit/workflow/test_cli_session.py index 958a9607..af2f29fe 100644 --- a/tests/unit/workflow/test_cli_session.py +++ b/tests/unit/workflow/test_cli_session.py @@ -100,6 +100,27 @@ async def test_launch_calls_spawner_spawn(self) -> None: ) assert agent_name.startswith("cli-") + @pytest.mark.asyncio + async def test_launch_lifetime_follows_max_session_seconds(self) -> None: + """CLI sandboxes get an expiry covering the session's own max duration.""" + from cloud_agents.spawner.lifetime import cli_session_lifetime_seconds + + spawner = AsyncMock() + spawner.spawn = AsyncMock(return_value="http://cli-agent:8080") + + launcher = CLISessionLauncher(max_session_seconds=7200) + await launcher.launch( + spawner=spawner, + context_markdown="# ctx", + prompt="p", + image="quay.io/sandbox:latest", + workflow_id="wf-abc", + ) + + lifetime = spawner.spawn.call_args.kwargs["lifetime_seconds"] + assert lifetime == cli_session_lifetime_seconds(7200, launcher._check_interval) + assert lifetime > 7200 + @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_step_runner.py b/tests/unit/workflow/test_step_runner.py index 7cdf6454..02bb0dfb 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"]["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_forwards_otel_endpoint_to_sandbox( self, From 68515c6df212d2a1d464862fd6bc4bfb9cd32b9b Mon Sep 17 00:00:00 2001 From: James Wong <2421248+jameswnl@users.noreply.github.com> Date: Sat, 31 Oct 2026 22:50:53 -0400 Subject: [PATCH 04/11] Bound transcript fetch and local POST so sandboxes fit their expiry The post-run GET /v1/agent/events reused the step-sized HTTP timeout after the Temporal heartbeat loop had stopped, so a sandbox could live about twice its step bound and outlive its expires-at label. Transcript collection in both runners now has its own 30s wall-clock bound (SANDBOX_TRANSCRIPT_TIMEOUT_SECONDS, added to the step lifetime), and the local engine's run POST enforces http_timeout as an overall deadline, since httpx's timeout is per read. CLI sessions claim a lifetime only while the launcher's timeout monitor is running. OpenShellSpawner rejects negative min_lifetime_seconds and expiry_skew_seconds, execution.py uses the shared default step timeout, and the legacy cleanup snippet in the docs pages through the listing. Co-Authored-By: Claude Opus 5.5 --- docs/sandbox-contract.md | 32 ++++- src/cloud_agents/spawner/lifetime.py | 9 +- src/cloud_agents/spawner/openshell_spawner.py | 6 + src/cloud_agents/workflow/cli_session.py | 8 +- src/cloud_agents/workflow/core/execution.py | 3 +- src/cloud_agents/workflow/core/step_runner.py | 31 +++-- .../workflow/executor/temporal/activities.py | 17 ++- tests/unit/spawner/test_lifetime.py | 5 +- tests/unit/spawner/test_openshell_spawner.py | 8 ++ .../unit/workflow/temporal/test_activities.py | 4 +- tests/unit/workflow/test_cli_session.py | 20 +++ tests/unit/workflow/test_sandbox_deadlines.py | 122 ++++++++++++++++++ 12 files changed, 236 insertions(+), 29 deletions(-) create mode 100644 tests/unit/workflow/test_sandbox_deadlines.py diff --git a/docs/sandbox-contract.md b/docs/sandbox-contract.md index f15371d6..3d64a13e 100644 --- a/docs/sandbox-contract.md +++ b/docs/sandbox-contract.md @@ -150,11 +150,14 @@ call site passes its own lifetime: `timeout_seconds`, `permissions.timeout_seconds`; each defaulting to 600) + 300s gateway ready wait + 60s HTTP ready wait + 180s activity heartbeat timeout (a timed-out activity only learns of cancellation via a heartbeat) - + 120s destroy grace. Each retry attempt spawns a new sandbox (the attempt + + 30s transcript fetch (its own wall-clock bound) + 120s destroy grace. The + local engine enforces the HTTP timeout as an overall deadline on the run + call, since httpx's own timeout is per read. Each retry attempt spawns a new sandbox (the attempt number is part of the `ca-` name; the activity itself runs with `maximum_attempts=1`), so the lifetime is per attempt. - CLI sessions: `max_session_seconds` + the timeout monitor's check interval - + 300s + 60s + 120s. + + 300s + 60s + 120s, but only while the launcher's timeout monitor is + running; otherwise no lifetime (and no `expires-at`) is set. - A spawn with no lifetime gets no `expires-at`, so only its owner can reap it. `SANDBOX_MIN_LIFETIME_SECONDS` (default 86400) is a floor, not a cap: it only @@ -185,8 +188,25 @@ gateway needs, as in `cloud_agents/spawner/factory.py`): from openshell import SandboxClient client = SandboxClient(endpoint="") -for ref in client.list(workspace="default", label_selector="spawned-by=workflow-runner", limit=1000): - if "cloud-agents/owner-instance" not in ref.labels and "cloud-agents/expires-at" not in ref.labels: - print("deleting", ref.name) - client.delete(ref.name, workspace="default") +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/owner-instance" not in ref.labels + and "cloud-agents/expires-at" not in ref.labels + ] + if len(refs) < page: + break + offset += page +# Delete after listing so deletions don't shift later pages. +for name in legacy: + print("deleting", name) + client.delete(name, workspace="default") ``` diff --git a/src/cloud_agents/spawner/lifetime.py b/src/cloud_agents/spawner/lifetime.py index a2cc42bf..5a0d5651 100644 --- a/src/cloud_agents/spawner/lifetime.py +++ b/src/cloud_agents/spawner/lifetime.py @@ -37,6 +37,9 @@ # run_sandbox_step's heartbeat_timeout (temporal/workflow.py): cancellation # after start_to_close_timeout reaches the activity only via a heartbeat. SANDBOX_ACTIVITY_HEARTBEAT_TIMEOUT_SECONDS = 180 +# Wall-clock bound on the post-run GET /v1/agent/events transcript fetch, +# which runs after the Temporal heartbeat loop has stopped. +SANDBOX_TRANSCRIPT_TIMEOUT_SECONDS = 30 # Time for the finally-block destroy() to run after the step ends. SANDBOX_DESTROY_GRACE_SECONDS = 120 @@ -48,8 +51,9 @@ def step_sandbox_lifetime_seconds(step: dict[str, Any]) -> int: (Temporal start_to_close_timeout) and permissions.timeout_seconds (the sandbox HTTP call timeout, the only bound on the local engine), plus the spawn readiness waits, the heartbeat delay before a timed-out activity - sees cancellation, and destroy grace. Each retry attempt spawns a fresh - sandbox (attempt is part of compute_pod_name()), so this is per attempt. + sees cancellation, the transcript fetch, and destroy grace. Each retry + attempt spawns a fresh sandbox (attempt is part of compute_pod_name()), + so this is per attempt. """ permissions = step.get("permissions") or {} run_seconds = max( @@ -61,6 +65,7 @@ def step_sandbox_lifetime_seconds(step: dict[str, Any]) -> int: + SANDBOX_GATEWAY_READY_TIMEOUT_SECONDS + SANDBOX_HTTP_READY_TIMEOUT_SECONDS + SANDBOX_ACTIVITY_HEARTBEAT_TIMEOUT_SECONDS + + SANDBOX_TRANSCRIPT_TIMEOUT_SECONDS + SANDBOX_DESTROY_GRACE_SECONDS ) diff --git a/src/cloud_agents/spawner/openshell_spawner.py b/src/cloud_agents/spawner/openshell_spawner.py index e1f1206d..6d19014b 100644 --- a/src/cloud_agents/spawner/openshell_spawner.py +++ b/src/cloud_agents/spawner/openshell_spawner.py @@ -368,6 +368,12 @@ def __init__( """ super().__init__(**kwargs) self._owner_instance = owner_instance + 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 diff --git a/src/cloud_agents/workflow/cli_session.py b/src/cloud_agents/workflow/cli_session.py index 3be0ecca..bf8c0c3b 100644 --- a/src/cloud_agents/workflow/cli_session.py +++ b/src/cloud_agents/workflow/cli_session.py @@ -170,8 +170,12 @@ async def launch( service_account=service_account, credential_secret_name=credential_secret_name, mcp_secret_mounts=mcp_secret_mounts, - lifetime_seconds=cli_session_lifetime_seconds( - self.max_session_seconds, self._check_interval + # Only the timeout monitor enforces max_session_seconds; + # without it, claim no lifetime so no other replica reaps it. + lifetime_seconds=( + cli_session_lifetime_seconds(self.max_session_seconds, self._check_interval) + if self._timeout_task is not None + else None ), ) diff --git a/src/cloud_agents/workflow/core/execution.py b/src/cloud_agents/workflow/core/execution.py index 86871000..c4c648a6 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 e42eece3..cf968a8c 100644 --- a/src/cloud_agents/workflow/core/step_runner.py +++ b/src/cloud_agents/workflow/core/step_runner.py @@ -27,6 +27,7 @@ from cloud_agents.runtime.circuit_breaker import ProviderCircuitBreaker from cloud_agents.spawner.lifetime import ( DEFAULT_STEP_TIMEOUT_SECONDS, + SANDBOX_TRANSCRIPT_TIMEOUT_SECONDS, step_sandbox_lifetime_seconds, ) from cloud_agents.workflow.core.mcp_resolver import resolve_mcp_servers @@ -77,11 +78,17 @@ 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. + async with asyncio.timeout(SANDBOX_TRANSCRIPT_TIMEOUT_SECONDS): + async with httpx.AsyncClient( + **{**client_kwargs, "timeout": SANDBOX_TRANSCRIPT_TIMEOUT_SECONDS} + ) as client: + response = await client.get( + f"{endpoint}/v1/agent/events", + headers=http_headers or None, + ) if response.status_code == 404: return empty @@ -435,11 +442,15 @@ async def _run_step_inner( try: async with httpx.AsyncClient(**client_kwargs) as client: try: - response = await client.post( - f"{endpoint}/v1/agent/run", - json=request_body, - headers=http_headers or None, - ) + # httpx's timeout is per read; enforce http_timeout as + # an overall deadline (the local engine has no other + # wall-clock bound on the step). + async with asyncio.timeout(http_timeout): + response = await client.post( + f"{endpoint}/v1/agent/run", + json=request_body, + headers=http_headers or None, + ) except (ssl.SSLError, httpx.ConnectError) as tls_exc: emit_audit( event_type="tls_error", diff --git a/src/cloud_agents/workflow/executor/temporal/activities.py b/src/cloud_agents/workflow/executor/temporal/activities.py index 9f3419e8..afbfd88a 100644 --- a/src/cloud_agents/workflow/executor/temporal/activities.py +++ b/src/cloud_agents/workflow/executor/temporal/activities.py @@ -25,6 +25,7 @@ from cloud_agents.runtime.circuit_breaker import ProviderCircuitBreaker from cloud_agents.spawner.lifetime import ( DEFAULT_STEP_TIMEOUT_SECONDS, + SANDBOX_TRANSCRIPT_TIMEOUT_SECONDS, step_sandbox_lifetime_seconds, ) from cloud_agents.workflow.notifiers.escalation import LogPackager @@ -318,11 +319,17 @@ 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. + async with asyncio.timeout(SANDBOX_TRANSCRIPT_TIMEOUT_SECONDS): + async with httpx.AsyncClient( + **{**client_kwargs, "timeout": SANDBOX_TRANSCRIPT_TIMEOUT_SECONDS} + ) as client: + response = await client.get( + f"{endpoint}/v1/agent/events", + headers=http_headers or None, + ) if response.status_code == 404: logger.debug("Event log not found for step '%s' (HTTP 404)", step_name) diff --git a/tests/unit/spawner/test_lifetime.py b/tests/unit/spawner/test_lifetime.py index b01e70cf..3ac7d67a 100644 --- a/tests/unit/spawner/test_lifetime.py +++ b/tests/unit/spawner/test_lifetime.py @@ -9,8 +9,8 @@ ) # Everything around the step's own run time: gateway ready wait + HTTP ready -# wait + Temporal heartbeat timeout + destroy grace. -STEP_OVERHEAD = 300 + 60 + 180 + 120 +# wait + Temporal heartbeat timeout + transcript collection + destroy grace. +STEP_OVERHEAD = 300 + 60 + 180 + 30 + 120 class TestStepSandboxLifetime: @@ -36,6 +36,7 @@ def test_constants_match_their_sources(self) -> None: assert lifetime.SANDBOX_GATEWAY_READY_TIMEOUT_SECONDS == 300 assert lifetime.SANDBOX_HTTP_READY_TIMEOUT_SECONDS == 60 assert lifetime.SANDBOX_ACTIVITY_HEARTBEAT_TIMEOUT_SECONDS == 180 + assert lifetime.SANDBOX_TRANSCRIPT_TIMEOUT_SECONDS == 30 class TestCliSessionLifetime: diff --git a/tests/unit/spawner/test_openshell_spawner.py b/tests/unit/spawner/test_openshell_spawner.py index b70b305e..773a6cc7 100644 --- a/tests/unit/spawner/test_openshell_spawner.py +++ b/tests/unit/spawner/test_openshell_spawner.py @@ -579,6 +579,14 @@ async def test_spawn_without_lifetime_has_no_expiry(self, mocker: MockerFixture) 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 diff --git a/tests/unit/workflow/temporal/test_activities.py b/tests/unit/workflow/temporal/test_activities.py index cdd75ed5..426801a3 100644 --- a/tests/unit/workflow/temporal/test_activities.py +++ b/tests/unit/workflow/temporal/test_activities.py @@ -457,7 +457,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/test_cli_session.py b/tests/unit/workflow/test_cli_session.py index af2f29fe..334c93b1 100644 --- a/tests/unit/workflow/test_cli_session.py +++ b/tests/unit/workflow/test_cli_session.py @@ -109,6 +109,7 @@ async def test_launch_lifetime_follows_max_session_seconds(self) -> None: spawner.spawn = AsyncMock(return_value="http://cli-agent:8080") launcher = CLISessionLauncher(max_session_seconds=7200) + launcher.start_timeout_monitor(spawner) await launcher.launch( spawner=spawner, context_markdown="# ctx", @@ -120,6 +121,25 @@ async def test_launch_lifetime_follows_max_session_seconds(self) -> None: lifetime = spawner.spawn.call_args.kwargs["lifetime_seconds"] assert lifetime == cli_session_lifetime_seconds(7200, launcher._check_interval) assert lifetime > 7200 + await launcher.shutdown() + + @pytest.mark.asyncio + async def test_launch_without_timeout_monitor_has_no_lifetime(self) -> None: + """Without the timeout monitor nothing enforces max_session_seconds, so + no lifetime (no expiry) is claimed -- only the owner may reap it.""" + spawner = AsyncMock() + spawner.spawn = AsyncMock(return_value="http://cli-agent:8080") + + launcher = CLISessionLauncher(max_session_seconds=7200) + await launcher.launch( + spawner=spawner, + context_markdown="# ctx", + prompt="p", + image="quay.io/sandbox:latest", + workflow_id="wf-abc", + ) + + assert spawner.spawn.call_args.kwargs["lifetime_seconds"] is None @pytest.mark.asyncio async def test_launch_returns_session_id(self) -> None: diff --git a/tests/unit/workflow/test_sandbox_deadlines.py b/tests/unit/workflow/test_sandbox_deadlines.py new file mode 100644 index 00000000..8261ae2c --- /dev/null +++ b/tests/unit/workflow/test_sandbox_deadlines.py @@ -0,0 +1,122 @@ +"""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() From 5c756efae2fee21782ca7c3053b16de158a7ef56 Mon Sep 17 00:00:00 2001 From: James Wong <2421248+jameswnl@users.noreply.github.com> Date: Sat, 31 Oct 2026 23:10:29 -0400 Subject: [PATCH 05/11] Give local run timeouts a clear, audited error When the local engine's overall POST deadline fired with a provider credential set, the secret-redaction handler re-raised RuntimeError(str(TimeoutError())), which is empty, so the step failed with a blank error. The timeout is now caught at the POST and re-raised as "Agent run timed out after s", which passes through redaction unchanged. It also increments ls_sandbox_timeout_total and emits a sandbox_timeout audit event with reason "timeout", the local counterpart of the Temporal path's cancellation event. Co-Authored-By: Claude Opus 5.5 --- src/cloud_agents/workflow/core/step_runner.py | 11 ++++ tests/unit/workflow/test_sandbox_deadlines.py | 55 +++++++++++++++++++ 2 files changed, 66 insertions(+) diff --git a/src/cloud_agents/workflow/core/step_runner.py b/src/cloud_agents/workflow/core/step_runner.py index cf968a8c..f780fbb9 100644 --- a/src/cloud_agents/workflow/core/step_runner.py +++ b/src/cloud_agents/workflow/core/step_runner.py @@ -451,6 +451,17 @@ async def _run_step_inner( json=request_body, headers=http_headers or None, ) + 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 except (ssl.SSLError, httpx.ConnectError) as tls_exc: emit_audit( event_type="tls_error", diff --git a/tests/unit/workflow/test_sandbox_deadlines.py b/tests/unit/workflow/test_sandbox_deadlines.py index 8261ae2c..2c340425 100644 --- a/tests/unit/workflow/test_sandbox_deadlines.py +++ b/tests/unit/workflow/test_sandbox_deadlines.py @@ -120,3 +120,58 @@ async def trickle(*args, **kwargs): 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" From 8635b8e89a76fa024181eb29917b11033e2b8b04 Mon Sep 17 00:00:00 2001 From: James Wong <2421248+jameswnl@users.noreply.github.com> Date: Sat, 31 Oct 2026 23:27:03 -0400 Subject: [PATCH 06/11] Reconcile only expired sandboxes, bounded by enforced deadlines A matching runner identity never proves a sandbox's previous owner is gone, so the owner-instance fast path could destroy live sandboxes. Startup reconcile now destroys only sandboxes past their expires-at label, and the identity mechanism is removed: RUNNER_INSTANCE_ID/HOSTNAME resolution, owner-instance stamping, and the Helm/Kind/Podman wiring. Caller-supplied expires-at and leftover owner-instance labels are still stripped. Reconcile deletes exactly the expired gateway ref: the new list_sandbox_labels()/destroy_sandbox() carry the unique sandbox name through to deletion, instead of destroy(agent_name), which re-expanded by agent-name label and could delete a live or legacy ref sharing it. The expiry is now the sum of enforced wall-clock deadlines, measured from when it is stamped: a single 420s spawn budget (CreateSandbox 30s RPC timeout + 300s gateway ready + 60s HTTP readiness + 30s post-create) that starts at the stamp and covers create and every post-create phase, the run POST (now also enforced locally in the Temporal activity), the 30s transcript fetch and a new 30s transcript-save bound, plus 120s destroy grace. The stamp is rounded up rather than down. On a spawn timeout only a sandbox whose name CreateSandbox returned is deleted. CLI sessions have no enforced bound and get no expiry. Docs state the assumptions (enforced deadlines plus a clock-skew margin), that old runners must be drained before new ones admit work, and give a dry-run legacy cleanup that skips CLI sessions. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- deploy/helm/templates/deployment.yaml | 5 - deploy/kind/workflow-runner-2-replicas.yaml | 5 - deploy/kind/workflow-runner-openshell.yaml | 5 - deploy/kind/workflow-runner.yaml | 5 - deploy/podman/docker-compose.local.yaml | 2 - deploy/podman/docker-compose.yaml | 2 - docs/ARCHITECTURE.md | 2 +- docs/sandbox-contract.md | 123 ++--- src/cloud_agents/spawner/base.py | 24 +- src/cloud_agents/spawner/factory.py | 1 - src/cloud_agents/spawner/lifetime.py | 98 ++-- src/cloud_agents/spawner/openshell_spawner.py | 240 +++++---- src/cloud_agents/workflow/cli_session.py | 11 +- src/cloud_agents/workflow/core/step_runner.py | 10 +- .../workflow/executor/local/entrypoint.py | 6 +- .../workflow/executor/temporal/activities.py | 37 +- .../workflow/executor/temporal/entrypoint.py | 106 +--- tests/unit/spawner/test_base.py | 15 +- tests/unit/spawner/test_factory.py | 4 +- tests/unit/spawner/test_lifetime.py | 67 ++- tests/unit/spawner/test_openshell_spawner.py | 76 +-- .../unit/workflow/temporal/test_activities.py | 11 +- .../workflow/temporal/test_cleanup_metrics.py | 24 +- .../temporal/test_startup_reconciliation.py | 455 +++++++++++------- tests/unit/workflow/test_cli_session.py | 33 +- tests/unit/workflow/test_sandbox_deadlines.py | 106 ++++ tests/unit/workflow/test_step_runner.py | 2 +- 28 files changed, 803 insertions(+), 674 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 3bc0a3f6..bfac48fd 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. Reconcile destroys sandboxes whose `cloud-agents/owner-instance` label matches this replica's identity (`RUNNER_INSTANCE_ID`, Helm: pod name, else `HOSTNAME`) plus any sandbox past its `cloud-agents/expires-at` label (spawn time + max(per-sandbox lifetime from `spawner/lifetime.py`, `SANDBOX_MIN_LIFETIME_SECONDS`) + `SANDBOX_EXPIRY_SKEW_SECONDS`; spawns without a lifetime get no expiry); other replicas' unexpired sandboxes and legacy sandboxes without `expires-at` are left alone. Old and new runner versions must not run side by side for long (old runners destroy every `spawned-by` sandbox) -- see `docs/sandbox-contract.md#labels`. | +| 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, 30s transcript fetch, 30s save, 120s grace); 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/deploy/helm/templates/deployment.yaml b/deploy/helm/templates/deployment.yaml index bb498fad..60d51f6c 100644 --- a/deploy/helm/templates/deployment.yaml +++ b/deploy/helm/templates/deployment.yaml @@ -29,11 +29,6 @@ spec: value: {{ .Values.temporal.namespace | quote }} - name: WORKFLOW_SPAWNER value: {{ .Values.spawner.type | quote }} - # Scopes startup orphan cleanup to this pod's own sandboxes - - name: RUNNER_INSTANCE_ID - valueFrom: - fieldRef: - fieldPath: metadata.name - name: OPENSHELL_GATEWAY_URL value: {{ .Values.spawner.gatewayUrl | quote }} - name: OPENSHELL_WORKSPACE diff --git a/deploy/kind/workflow-runner-2-replicas.yaml b/deploy/kind/workflow-runner-2-replicas.yaml index 67cdc4e3..09d03a80 100644 --- a/deploy/kind/workflow-runner-2-replicas.yaml +++ b/deploy/kind/workflow-runner-2-replicas.yaml @@ -46,11 +46,6 @@ spec: value: "default" - name: WORKFLOW_SPAWNER value: "openshell" - # Scopes startup orphan cleanup to this pod's own sandboxes - - name: RUNNER_INSTANCE_ID - valueFrom: - fieldRef: - fieldPath: metadata.name - name: OPENSHELL_GATEWAY_URL value: "CHANGEME.example.com:17670" # your OpenShell gateway address - name: AUTH_REQUIRED diff --git a/deploy/kind/workflow-runner-openshell.yaml b/deploy/kind/workflow-runner-openshell.yaml index b1cc313a..381962e8 100644 --- a/deploy/kind/workflow-runner-openshell.yaml +++ b/deploy/kind/workflow-runner-openshell.yaml @@ -44,11 +44,6 @@ spec: value: "default" - name: WORKFLOW_SPAWNER value: "openshell" - # Scopes startup orphan cleanup to this pod's own sandboxes - - name: RUNNER_INSTANCE_ID - valueFrom: - fieldRef: - fieldPath: metadata.name - name: OPENSHELL_GATEWAY_URL value: "CHANGEME.example.com:17670" # your OpenShell gateway address - name: AUTH_REQUIRED diff --git a/deploy/kind/workflow-runner.yaml b/deploy/kind/workflow-runner.yaml index 830d01ac..7084ab8b 100644 --- a/deploy/kind/workflow-runner.yaml +++ b/deploy/kind/workflow-runner.yaml @@ -35,11 +35,6 @@ spec: value: "default" - name: WORKFLOW_SPAWNER value: "openshell" - # Scopes startup orphan cleanup to this pod's own sandboxes - - name: RUNNER_INSTANCE_ID - valueFrom: - fieldRef: - fieldPath: metadata.name - name: OPENSHELL_GATEWAY_URL value: "CHANGEME.example.com:17670" # your OpenShell gateway address - name: AUTH_REQUIRED diff --git a/deploy/podman/docker-compose.local.yaml b/deploy/podman/docker-compose.local.yaml index b44e7d14..78ded4c4 100644 --- a/deploy/podman/docker-compose.local.yaml +++ b/deploy/podman/docker-compose.local.yaml @@ -40,8 +40,6 @@ services: environment: WORKFLOW_ENGINE: local WORKFLOW_SPAWNER: openshell - # Stable per-runner identity for scoping startup orphan cleanup - RUNNER_INSTANCE_ID: workflow-runner OPENSHELL_GATEWAY_URL: ${OPENSHELL_GATEWAY_URL:?set to your separately-deployed OpenShell gateway address} AUTH_REQUIRED: "false" RUN_STATE_DB_URL: postgresql://workflow:workflow-pass@postgres:5432/cloud_agents diff --git a/deploy/podman/docker-compose.yaml b/deploy/podman/docker-compose.yaml index 8fbcf781..fc9b4ddc 100644 --- a/deploy/podman/docker-compose.yaml +++ b/deploy/podman/docker-compose.yaml @@ -65,8 +65,6 @@ services: TEMPORAL_URL: temporal-server:7233 TEMPORAL_NAMESPACE: default WORKFLOW_SPAWNER: openshell - # Stable per-runner identity for scoping startup orphan cleanup - RUNNER_INSTANCE_ID: workflow-runner OPENSHELL_GATEWAY_URL: ${OPENSHELL_GATEWAY_URL:?set to your separately-deployed OpenShell gateway address} AUTH_REQUIRED: "false" OPENAI_API_KEY: ${OPENAI_API_KEY:-} diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 19e5e220..64ad8fe8 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, scoped to the restarting replica's own sandboxes via the `cloud-agents/owner-instance` label (`RUNNER_INSTANCE_ID`, else `HOSTNAME`) plus any sandbox past its per-sandbox `cloud-agents/expires-at` label (see [sandbox-contract.md](sandbox-contract.md#labels), including the upgrade/rollback caveat and one-time legacy cleanup). +- **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 3d64a13e..e3a637bb 100644 --- a/docs/sandbox-contract.md +++ b/docs/sandbox-contract.md @@ -129,64 +129,74 @@ Spawned sandbox pods carry these labels for lifecycle management: | `cloud-agents/attempt` | Retry attempt number | | `spawned-by` | `workflow-runner` (always set) | | `cloud-agents/agent-name` | Agent name (always set; the gateway assigns the sandbox name) | -| `cloud-agents/owner-instance` | Runner replica's identity: `RUNNER_INSTANCE_ID`, else `HOSTNAME` (set only when one is available) | -| `cloud-agents/expires-at` | Unix seconds: spawn time + max(per-sandbox lifetime, `SANDBOX_MIN_LIFETIME_SECONDS`) + `SANDBOX_EXPIRY_SKEW_SECONDS` (set only when the caller passes a lifetime) | +| `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 -makes one `spawned-by=workflow-runner` listing and destroys sandboxes whose -`cloud-agents/owner-instance` matches its own identity (the Helm chart sets -`RUNNER_INSTANCE_ID` to the pod name), plus any sandbox whose -`cloud-agents/expires-at` is in the past regardless of owner (e.g. left by a -replaced pod). Other replicas' unexpired sandboxes, sandboxes with no -`expires-at` label and sandboxes with a malformed `expires-at` are left alone -and logged. With no identity, only expired sandboxes are destroyed. -Caller-supplied `owner-instance` / `expires-at` labels are always dropped. - -**Per-sandbox lifetime** (`cloud_agents/spawner/lifetime.py`). `expires-at` -must never be earlier than the sandbox's latest legitimate end, so each spawn -call site passes its own lifetime: - -- Workflow steps (Temporal activity and local engine): max(step - `timeout_seconds`, `permissions.timeout_seconds`; each defaulting to 600) - + 300s gateway ready wait + 60s HTTP ready wait + 180s activity heartbeat - timeout (a timed-out activity only learns of cancellation via a heartbeat) - + 30s transcript fetch (its own wall-clock bound) + 120s destroy grace. The - local engine enforces the HTTP timeout as an overall deadline on the run - call, since httpx's own timeout is per read. Each retry attempt spawns a new sandbox (the attempt - number is part of the `ca-` name; the activity itself runs with - `maximum_attempts=1`), so the lifetime is per attempt. -- CLI sessions: `max_session_seconds` + the timeout monitor's check interval - + 300s + 60s + 120s, but only while the launcher's timeout monitor is - running; otherwise no lifetime (and no `expires-at`) is set. -- A spawn with no lifetime gets no `expires-at`, so only its owner can reap it. - -`SANDBOX_MIN_LIFETIME_SECONDS` (default 86400) is a floor, not a cap: it only -delays how soon another replica may reap an orphan. `SANDBOX_EXPIRY_SKEW_SECONDS` -(default 600) covers clock skew between replicas. Both must be non-negative -integers or startup fails. - -**Identity.** An explicit `RUNNER_INSTANCE_ID` must be a valid label value or -startup fails. The `HOSTNAME` fallback logs a warning: runners sharing a host -network (same hostname) must each set a distinct `RUNNER_INSTANCE_ID`. An -invalid `HOSTNAME` only disables own-instance cleanup. Bare-process dev runs -with neither variable set skip own-instance cleanup (expired sandboxes are -still reaped); the Podman compose files set `RUNNER_INSTANCE_ID`. - -**Upgrades and rollbacks.** Runners from before owner scoping destroy *every* -`spawned-by=workflow-runner` sandbox on startup, including new runners' live -ones. Don't run old and new runner versions side by side for long: finish the -rollout promptly, or use a `Recreate` deployment strategy. A rollback carries -the same risk in reverse. - -**Legacy sandboxes.** Sandboxes spawned by older runners carry neither -`owner-instance` nor `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`): +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** (`SANDBOX_SPAWN_DEADLINE_SECONDS`). One `asyncio` deadline in + `OpenShellSpawner._do_spawn` 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. 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). Both engines enforce it + as an overall deadline on `POST /v1/agent/run`, since httpx's own timeout is + per read. Temporal's `start_to_close_timeout` can only end a step earlier. +- **Transcript fetch: 30s, transcript-store save: 30s.** +- **Destroy grace: 120s.** A margin, not a safety requirement: once the + transcript save finishes the sandbox is no longer used. + +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: @@ -199,14 +209,15 @@ while True: legacy += [ ref.name for ref in refs - if "cloud-agents/owner-instance" not in ref.labels - and "cloud-agents/expires-at" not in ref.labels + 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("deleting", name) - client.delete(name, workspace="default") + 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 eca728ee..6aae133c 100644 --- a/src/cloud_agents/spawner/base.py +++ b/src/cloud_agents/spawner/base.py @@ -266,33 +266,41 @@ async def _do_list_active( ) -> list[str]: """Implementation-specific listing of active agents.""" - async def list_active_labels( + async def list_sandbox_labels( self, labels: dict[str, str] | None = None, ) -> list[tuple[str, dict[str, str]]]: - """List active spawned agent names with each sandbox's labels. + """List active sandboxes as (exact sandbox name, labels). Args: labels: Optional label selector to filter results. Returns: - (agent name, labels) pairs for active agents matching the given - labels, so callers can filter on label values a selector can't + 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_active_labels(labels) + return await self._do_list_sandbox_labels(labels) - async def _do_list_active_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 treats a sandbox with no owner/expiry labels - as legacy and never destroys it, so this default is fail-safe. + 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.""" + await self._do_destroy_sandbox(sandbox_name) + + async def _do_destroy_sandbox(self, sandbox_name: str) -> None: + """Default: names from the default listing are agent names.""" + await self.destroy(sandbox_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 96816fad..fee5e9d5 100644 --- a/src/cloud_agents/spawner/factory.py +++ b/src/cloud_agents/spawner/factory.py @@ -37,7 +37,6 @@ "max_pods", "extra_readable_paths", "extra_env", - "owner_instance", "min_lifetime_seconds", "expiry_skew_seconds", } diff --git a/src/cloud_agents/spawner/lifetime.py b/src/cloud_agents/spawner/lifetime.py index 5a0d5651..fd2b4b1f 100644 --- a/src/cloud_agents/spawner/lifetime.py +++ b/src/cloud_agents/spawner/lifetime.py @@ -1,14 +1,18 @@ -"""Sandbox ownership labels and lifetime bounds for orphan reconciliation. +"""Sandbox expiry labels and the enforced deadlines they're computed from. -Shared by OpenShellSpawner (which stamps the labels at spawn time) and -reconcile_orphaned_sandboxes() (which filters on them at startup), and by the -spawn call sites that compute each sandbox's lifetime. Kept dependency-free so -the Temporal workflow module can import it. +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 end, or another replica's startup reconcile could destroy -it while still in use. Each spawn call site therefore passes a per-sandbox -lifetime_seconds covering everything that can keep the sandbox alive. +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. """ from __future__ import annotations @@ -19,68 +23,56 @@ # 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"} -# Runner replica that spawned the sandbox; reconcile destroys its own. -OWNER_INSTANCE_LABEL_KEY = "cloud-agents/owner-instance" # Unix seconds after which any replica's reconcile may destroy the sandbox. EXPIRES_AT_LABEL_KEY = "cloud-agents/expires-at" -# Set only by the spawner from its own config; dropped from caller labels. -RESERVED_LABEL_KEYS = frozenset({OWNER_INSTANCE_LABEL_KEY, EXPIRES_AT_LABEL_KEY}) +# 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 timeout when neither the step nor its definition sets one; becomes the -# run_sandbox_step activity's start_to_close_timeout (temporal/workflow.py) -# and the default sandbox HTTP timeout (permissions.timeout_seconds). +# 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 -# run_sandbox_step's heartbeat_timeout (temporal/workflow.py): cancellation -# after start_to_close_timeout reaches the activity only via a heartbeat. +# 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, -# which runs after the Temporal heartbeat loop has stopped. +# Wall-clock bound on the post-run GET /v1/agent/events transcript fetch ... SANDBOX_TRANSCRIPT_TIMEOUT_SECONDS = 30 -# Time for the finally-block destroy() to run after the step ends. +# ... and on persisting it to the transcript store, before destroy. +SANDBOX_TRANSCRIPT_SAVE_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 step_sandbox_lifetime_seconds(step: dict[str, Any]) -> int: - """Latest legitimate life of one workflow step attempt's sandbox. - - The step's run time is bounded by the larger of its timeout_seconds - (Temporal start_to_close_timeout) and permissions.timeout_seconds (the - sandbox HTTP call timeout, the only bound on the local engine), plus the - spawn readiness waits, the heartbeat delay before a timed-out activity - sees cancellation, the transcript fetch, and destroy grace. Each retry - attempt spawns a fresh sandbox (attempt is part of compute_pod_name()), - so this is per attempt. - """ +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 {} - run_seconds = max( - step.get("timeout_seconds") or DEFAULT_STEP_TIMEOUT_SECONDS, - permissions.get("timeout_seconds") or DEFAULT_STEP_TIMEOUT_SECONDS, - ) - return ( - math.ceil(run_seconds) - + SANDBOX_GATEWAY_READY_TIMEOUT_SECONDS - + SANDBOX_HTTP_READY_TIMEOUT_SECONDS - + SANDBOX_ACTIVITY_HEARTBEAT_TIMEOUT_SECONDS - + SANDBOX_TRANSCRIPT_TIMEOUT_SECONDS - + SANDBOX_DESTROY_GRACE_SECONDS - ) - + return float(permissions.get("timeout_seconds", DEFAULT_STEP_TIMEOUT_SECONDS)) -def cli_session_lifetime_seconds(max_session_seconds: int, check_interval: float) -> int: - """Latest legitimate life of a CLI session sandbox. - CLISessionLauncher's timeout monitor destroys a session within one check - interval after max_session_seconds; add the spawn readiness waits and - destroy grace. +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, plus destroy grace. Each + retry attempt spawns a fresh sandbox (attempt is part of + compute_pod_name()), so this is per attempt. """ return ( - max_session_seconds - + math.ceil(check_interval) - + SANDBOX_GATEWAY_READY_TIMEOUT_SECONDS - + SANDBOX_HTTP_READY_TIMEOUT_SECONDS + SANDBOX_SPAWN_DEADLINE_SECONDS + + math.ceil(run_timeout_seconds(step)) + + SANDBOX_TRANSCRIPT_TIMEOUT_SECONDS + + SANDBOX_TRANSCRIPT_SAVE_TIMEOUT_SECONDS + SANDBOX_DESTROY_GRACE_SECONDS ) diff --git a/src/cloud_agents/spawner/openshell_spawner.py b/src/cloud_agents/spawner/openshell_spawner.py index 6d19014b..814a04e9 100644 --- a/src/cloud_agents/spawner/openshell_spawner.py +++ b/src/cloud_agents/spawner/openshell_spawner.py @@ -17,6 +17,7 @@ import asyncio import json import logging +import math import os import ssl import time @@ -28,10 +29,10 @@ from cloud_agents.spawner.base import AgentSpawner from cloud_agents.spawner.lifetime import ( EXPIRES_AT_LABEL_KEY, - OWNER_INSTANCE_LABEL_KEY, RESERVED_LABEL_KEYS, SANDBOX_GATEWAY_READY_TIMEOUT_SECONDS, SANDBOX_HTTP_READY_TIMEOUT_SECONDS, + SANDBOX_SPAWN_DEADLINE_SECONDS, SPAWNED_BY_LABEL, ) @@ -176,18 +177,10 @@ class OpenShellSpawner(AgentSpawner): # (issue #224). Shared with reconcile via cloud_agents.spawner.lifetime. _SPAWNED_BY_LABEL: ClassVar[dict[str, str]] = SPAWNED_BY_LABEL - # Identifies which runner replica spawned a sandbox (value: the - # owner_instance constructor arg, wired from RUNNER_INSTANCE_ID) so - # reconcile_orphaned_sandboxes() only destroys this replica's own orphans, - # never another live replica's sandboxes. Omitted when owner_instance is - # unset. - _OWNER_INSTANCE_LABEL_KEY: ClassVar[str] = OWNER_INSTANCE_LABEL_KEY - # Unix seconds after which the sandbox has outlived any legitimate use - # (spawn time + max(lifetime_seconds, min_lifetime_seconds) + skew). Lets - # any replica's reconcile_orphaned_sandboxes() reap sandboxes left by a - # replaced pod, whose owner-instance value will never come back. Omitted - # when the caller passes no lifetime_seconds. + # (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 @@ -303,7 +296,6 @@ def __init__( bearer_token_provider: Callable[[], str] | None = None, extra_readable_paths: list[str] | None = None, extra_env: dict[str, str] | None = None, - owner_instance: str = "", min_lifetime_seconds: int = 0, expiry_skew_seconds: int = 600, clock: Callable[[], float] = time.time, @@ -352,22 +344,19 @@ 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. - owner_instance: Stable identity of this runner replica (e.g. its - pod name), attached to every sandbox as the - _OWNER_INSTANCE_LABEL_KEY label so startup reconciliation - can tell this replica's orphans apart from other replicas' - live sandboxes. Empty means no owner label is attached. 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) - self._owner_instance = owner_instance for name, value in ( ("min_lifetime_seconds", min_lifetime_seconds), ("expiry_skew_seconds", expiry_skew_seconds), @@ -1071,25 +1060,28 @@ 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). Caller-supplied owner-instance / - # expires-at are always dropped: only this spawner's own config may - # mark a sandbox as owned by, or expired for, a runner replica. + # 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 = { **{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, } - if self._owner_instance: - sandbox_labels[self._OWNER_INSTANCE_LABEL_KEY] = self._owner_instance + # 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; only its " - "owner instance's startup reconcile can reap it", + "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( - int(self._clock()) + math.ceil(stamped_at) + max(lifetime_seconds, self._min_lifetime_seconds) + self._expiry_skew_seconds ) @@ -1119,75 +1111,81 @@ async def _do_spawn( else: self._build_baseline_filesystem_policy(spec, allowed_skills=allowed_skills) + # 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 try: - sandbox_ref = await asyncio.to_thread( - self._client.create, - workspace=self._workspace, - spec=spec, - labels=sandbox_labels, - ) - sandbox_name = sandbox_ref.name - sandbox_id = sandbox_ref.id - self._sandbox_names[agent_name] = sandbox_name - self._sandbox_ids[agent_name] = sandbox_id + async with asyncio.timeout_at(spawn_deadline): + sandbox_ref = await asyncio.to_thread( + self._client.create, + workspace=self._workspace, + spec=spec, + labels=sandbox_labels, + ) + 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 - await asyncio.to_thread( - self._client.wait_ready, - sandbox_name, - workspace=self._workspace, - timeout_seconds=SANDBOX_GATEWAY_READY_TIMEOUT_SECONDS, - ) + await asyncio.to_thread( + self._client.wait_ready, + sandbox_name, + workspace=self._workspace, + timeout_seconds=SANDBOX_GATEWAY_READY_TIMEOUT_SECONDS, + ) - # Credential Provider already created and attached via spec.providers - # before sandbox creation (see above) -- no post-create injection needed. - # The old _inject_credentials path (CreateProvider + Attach after - # wait_ready with real env) is removed to avoid exposing the real - # credential in spec.environment (issue #199). - - if mcp_secret_mounts: - await self._inject_mcp_secrets(agent_name, mcp_secret_mounts, env) - - # Advisory (read_only=True) spawns use _build_filesystem_policy(), - # which grants blanket "/" read but no write outside /tmp, - # /home/agent, /var/log, MCP, and credentials -- not - # _MATERIALIZED_SKILLS_DIR. Materializing there would fail with - # the same EACCES this method now raises loudly for, so advisory - # spawns skip materialize entirely and list _SKILLS_ROOT (the - # master) directly below instead -- consistent with advisory - # mode's existing documented semantics that its blanket read - # grant already covers all of /skills regardless of - # allowed_skills, since advisory is an integrity boundary - # (no-write), not a confidentiality one. - if allowed_skills and not read_only: - await self._materialize_allowed_skills(sandbox_id, allowed_skills) - - # self._extra_env first, then the caller's own env on top, so an - # explicit caller-provided value (e.g. a different derived image's - # PYTHONPATH) wins on collision rather than being silently - # overridden by the spawner's own default (issue #192). - # Filter credential keys from server_env as well -- start_server - # execs inside the sandbox, so env there would also expose the - # real credential to the sandboxed process (issue #199). - filtered_env = {k: v for k, v in env.items() if k not in cred_keys} - server_env = {**self._extra_env, **filtered_env} - if read_only: - server_env["LIGHTSPEED_SKILLS_DIR"] = self._SKILLS_ROOT - await self.start_server(sandbox_id, _DEFAULT_SERVER_COMMAND, env=server_env) - - endpoint, virtual_host = await self._expose_service( - sandbox_name, - port=8080, - ) - self._virtual_hosts[sandbox_name] = virtual_host + # Credential Provider already created and attached via spec.providers + # before sandbox creation (see above) -- no post-create injection needed. + # The old _inject_credentials path (CreateProvider + Attach after + # wait_ready with real env) is removed to avoid exposing the real + # credential in spec.environment (issue #199). + + if mcp_secret_mounts: + await self._inject_mcp_secrets(agent_name, mcp_secret_mounts, env) + + # Advisory (read_only=True) spawns use _build_filesystem_policy(), + # which grants blanket "/" read but no write outside /tmp, + # /home/agent, /var/log, MCP, and credentials -- not + # _MATERIALIZED_SKILLS_DIR. Materializing there would fail with + # the same EACCES this method now raises loudly for, so advisory + # spawns skip materialize entirely and list _SKILLS_ROOT (the + # master) directly below instead -- consistent with advisory + # mode's existing documented semantics that its blanket read + # grant already covers all of /skills regardless of + # allowed_skills, since advisory is an integrity boundary + # (no-write), not a confidentiality one. + if allowed_skills and not read_only: + await self._materialize_allowed_skills(sandbox_id, allowed_skills) + + # self._extra_env first, then the caller's own env on top, so an + # explicit caller-provided value (e.g. a different derived image's + # PYTHONPATH) wins on collision rather than being silently + # overridden by the spawner's own default (issue #192). + # Filter credential keys from server_env as well -- start_server + # execs inside the sandbox, so env there would also expose the + # real credential to the sandboxed process (issue #199). + filtered_env = {k: v for k, v in env.items() if k not in cred_keys} + server_env = {**self._extra_env, **filtered_env} + if read_only: + server_env["LIGHTSPEED_SKILLS_DIR"] = self._SKILLS_ROOT + await self.start_server(sandbox_id, _DEFAULT_SERVER_COMMAND, env=server_env) + + endpoint, virtual_host = await self._expose_service( + sandbox_name, + port=8080, + ) + self._virtual_hosts[sandbox_name] = virtual_host - ready = await self._wait_ready_with_host( - endpoint, - virtual_host, - timeout=SANDBOX_HTTP_READY_TIMEOUT_SECONDS, - ) - if not ready: - raise RuntimeError(f"Sandbox '{sandbox_name}' HTTP server did not become ready") - except Exception: + ready = await self._wait_ready_with_host( + endpoint, + virtual_host, + timeout=SANDBOX_HTTP_READY_TIMEOUT_SECONDS, + ) + if not ready: + raise RuntimeError(f"Sandbox '{sandbox_name}' HTTP server did not become ready") + except Exception as exc: logger.warning( "Post-create step failed for sandbox '%s' (agent=%s); " "deleting sandbox to prevent orphan", @@ -1200,8 +1198,13 @@ 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. + if created_name is not None: + await self._cleanup_sandbox(agent_name, created_name) + else: + self._provider_ids.pop(agent_name, None) if provider_id: try: await self._delete_provider(provider_id) @@ -1212,6 +1215,13 @@ async def _do_spawn( logger.warning( "Failed to delete orphaned provider '%s'", provider_id, exc_info=True ) + if isinstance(exc, TimeoutError): + # str(TimeoutError()) is empty; callers' secret redaction + # would turn that into a blank error. + raise TimeoutError( + f"Spawning sandbox for agent '{agent_name}' exceeded its " + f"{SANDBOX_SPAWN_DEADLINE_SECONDS}s deadline" + ) from None raise logger.info( @@ -2082,18 +2092,43 @@ async def _do_list_active( of being silently dropped -- destroy() falls back to treating such a name literally, so this remains cleanable. """ - return [name for name, _ in await self._do_list_active_labels(labels)] + return [ + ref.labels.get(self._AGENT_NAME_LABEL_KEY) or ref.name + for ref in await self._list_refs(labels) + ] - async def _do_list_active_labels( + async def _do_list_sandbox_labels( self, labels: dict[str, str] | None = None, ) -> list[tuple[str, dict[str, str]]]: - """List active sandboxes as (agent name, labels) from one gateway call. + """List (exact gateway sandbox name, labels) from one gateway call. - Same query and name recovery as _do_list_active(); also returns each - sandbox's labels so reconcile_orphaned_sandboxes() can partition by - owner-instance/expires-at client-side. + 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, + ) + 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 = await asyncio.to_thread( self._client.list, @@ -2105,7 +2140,4 @@ async def _do_list_active_labels( # ever legitimately exceeds this. limit=1000, ) - return [ - (ref.labels.get(self._AGENT_NAME_LABEL_KEY) or ref.name, dict(ref.labels)) - for ref in refs - ] + return list(refs) diff --git a/src/cloud_agents/workflow/cli_session.py b/src/cloud_agents/workflow/cli_session.py index bf8c0c3b..93b3a8df 100644 --- a/src/cloud_agents/workflow/cli_session.py +++ b/src/cloud_agents/workflow/cli_session.py @@ -21,7 +21,6 @@ from pydantic import BaseModel from cloud_agents.runtime.audit import emit_audit -from cloud_agents.spawner.lifetime import cli_session_lifetime_seconds if TYPE_CHECKING: from cloud_agents.spawner.base import AgentSpawner @@ -162,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, @@ -170,13 +172,6 @@ async def launch( service_account=service_account, credential_secret_name=credential_secret_name, mcp_secret_mounts=mcp_secret_mounts, - # Only the timeout monitor enforces max_session_seconds; - # without it, claim no lifetime so no other replica reaps it. - lifetime_seconds=( - cli_session_lifetime_seconds(self.max_session_seconds, self._check_interval) - if self._timeout_task is not None - else None - ), ) info = CLISessionInfo( diff --git a/src/cloud_agents/workflow/core/step_runner.py b/src/cloud_agents/workflow/core/step_runner.py index f780fbb9..d9ed0658 100644 --- a/src/cloud_agents/workflow/core/step_runner.py +++ b/src/cloud_agents/workflow/core/step_runner.py @@ -26,8 +26,9 @@ from cloud_agents.runtime.audit import emit_audit from cloud_agents.runtime.circuit_breaker import ProviderCircuitBreaker from cloud_agents.spawner.lifetime import ( - DEFAULT_STEP_TIMEOUT_SECONDS, + SANDBOX_TRANSCRIPT_SAVE_TIMEOUT_SECONDS, SANDBOX_TRANSCRIPT_TIMEOUT_SECONDS, + run_timeout_seconds, step_sandbox_lifetime_seconds, ) from cloud_agents.workflow.core.mcp_resolver import resolve_mcp_servers @@ -318,7 +319,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", DEFAULT_STEP_TIMEOUT_SECONDS)) + http_timeout = run_timeout_seconds(step) if spawner is None: logger.info("No spawner configured — returning stub result for '%s'", step_name) @@ -496,7 +497,10 @@ 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). + async with asyncio.timeout(SANDBOX_TRANSCRIPT_SAVE_TIMEOUT_SECONDS): + await transcript_store.save(workflow_id, output_key, transcript) except Exception: logger.warning( "Failed to save transcript to store for step '%s'", diff --git a/src/cloud_agents/workflow/executor/local/entrypoint.py b/src/cloud_agents/workflow/executor/local/entrypoint.py index 56f8410f..3339d385 100644 --- a/src/cloud_agents/workflow/executor/local/entrypoint.py +++ b/src/cloud_agents/workflow/executor/local/entrypoint.py @@ -26,7 +26,6 @@ _create_spawner, _get_auth_dependency, _load_content_policy, - _runner_instance_id, reconcile_orphaned_sandboxes, ) @@ -42,8 +41,7 @@ def build_local_app() -> FastAPI: configure_logging() init_tracing("workflow-runner") - owner_instance = _runner_instance_id() - spawner = _create_spawner(owner_instance) + spawner = _create_spawner() transcript_store = TranscriptStore.from_env() run_state_store = RunStateStore.from_env() @@ -66,7 +64,7 @@ def build_local_app() -> FastAPI: @asynccontextmanager async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]: """Connect stores and clean up orphans on startup.""" - await reconcile_orphaned_sandboxes(spawner, owner_instance) + await reconcile_orphaned_sandboxes(spawner) if transcript_store: try: diff --git a/src/cloud_agents/workflow/executor/temporal/activities.py b/src/cloud_agents/workflow/executor/temporal/activities.py index afbfd88a..aeb09d9e 100644 --- a/src/cloud_agents/workflow/executor/temporal/activities.py +++ b/src/cloud_agents/workflow/executor/temporal/activities.py @@ -24,8 +24,9 @@ from cloud_agents.runtime.audit import emit_audit from cloud_agents.runtime.circuit_breaker import ProviderCircuitBreaker from cloud_agents.spawner.lifetime import ( - DEFAULT_STEP_TIMEOUT_SECONDS, + SANDBOX_TRANSCRIPT_SAVE_TIMEOUT_SECONDS, SANDBOX_TRANSCRIPT_TIMEOUT_SECONDS, + run_timeout_seconds, step_sandbox_lifetime_seconds, ) from cloud_agents.workflow.notifiers.escalation import LogPackager @@ -538,7 +539,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", DEFAULT_STEP_TIMEOUT_SECONDS)) + http_timeout = run_timeout_seconds(step) if spawner is None: logger.info("No spawner configured — returning stub result for '%s'", step_name) @@ -657,11 +658,30 @@ async def _run_sandbox_step_inner( try: async with httpx.AsyncClient(**client_kwargs) as client: try: - response = await client.post( - f"{endpoint}/v1/agent/run", - json=request_body, - headers=http_headers or None, + # httpx's timeout is per read; enforce http_timeout as + # an overall local deadline rather than relying on + # heartbeat-delivered cancellation. + async with asyncio.timeout(http_timeout): + response = await client.post( + f"{endpoint}/v1/agent/run", + json=request_body, + headers=http_headers or None, + ) + 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 except ssl.SSLError as tls_exc: emit_audit( event_type="tls_error", @@ -703,7 +723,10 @@ 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). + async with asyncio.timeout(SANDBOX_TRANSCRIPT_SAVE_TIMEOUT_SECONDS): + await transcript_store.save(workflow_id, output_key, transcript) except Exception: logger.warning( "Failed to save transcript to store for step '%s'", diff --git a/src/cloud_agents/workflow/executor/temporal/entrypoint.py b/src/cloud_agents/workflow/executor/temporal/entrypoint.py index aba30dfc..3538cfd1 100644 --- a/src/cloud_agents/workflow/executor/temporal/entrypoint.py +++ b/src/cloud_agents/workflow/executor/temporal/entrypoint.py @@ -10,7 +10,6 @@ import logging import os -import re import time from collections.abc import AsyncGenerator from contextlib import asynccontextmanager @@ -21,11 +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, - OWNER_INSTANCE_LABEL_KEY, - SPAWNED_BY_LABEL, -) +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 @@ -80,55 +75,15 @@ def _build_tls_config(): SPAWNER_TYPE = os.environ.get("WORKFLOW_SPAWNER", "") -# Kubernetes label value syntax; owner-instance is stamped as a sandbox label. -_LABEL_VALUE_RE = re.compile(r"^(?:[A-Za-z0-9](?:[-A-Za-z0-9_.]{0,61}[A-Za-z0-9])?)?$") - -# Floor for every sandbox's expires-at label, on top of its own per-sandbox -# lifetime (cloud_agents.spawner.lifetime). Safety comes from the per-sandbox -# lifetime, so any non-negative value is safe; the floor only delays how soon -# another replica may reap an orphan. +# 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 _runner_instance_id() -> str: - """Resolve this runner replica's stable identity for sandbox ownership. - - RUNNER_INSTANCE_ID (the Helm chart sets it to the pod name), else - HOSTNAME, else "". The value is stamped on every sandbox as an owner label - and scopes startup reconciliation to this replica's own orphans. - - Raises: - ValueError: If RUNNER_INSTANCE_ID is set but isn't a legal label value. - An unusable HOSTNAME fallback only logs a warning and returns "". - """ - explicit = os.environ.get("RUNNER_INSTANCE_ID", "") - if explicit: - if not _LABEL_VALUE_RE.match(explicit): - raise ValueError( - f"RUNNER_INSTANCE_ID={explicit!r} is not a valid label value " - "(max 63 chars of [A-Za-z0-9-_.], alphanumeric at both ends)" - ) - return explicit - hostname = os.environ.get("HOSTNAME", "") - if hostname and not _LABEL_VALUE_RE.match(hostname): - logger.warning( - "HOSTNAME=%r is not a valid label value — set RUNNER_INSTANCE_ID; " - "own-instance sandbox cleanup disabled", - hostname, - ) - return "" - if hostname: - logger.warning( - "RUNNER_INSTANCE_ID not set — using HOSTNAME=%r as runner identity. " - "Runners sharing a host network (same hostname) must each set a " - "distinct RUNNER_INSTANCE_ID, or they will reap each other's sandboxes", - hostname, - ) - return hostname - - 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, "") @@ -155,7 +110,7 @@ def _sandbox_expiry_skew_seconds() -> int: return _non_negative_int_env("SANDBOX_EXPIRY_SKEW_SECONDS", DEFAULT_SANDBOX_EXPIRY_SKEW_SECONDS) -def _create_spawner(owner_instance: str = ""): +def _create_spawner(): """Create spawner based on environment config. Thin env-var-reading wrapper around cloud_agents.spawner.factory.build_spawner @@ -182,7 +137,6 @@ def _create_spawner(owner_instance: str = ""): tls_cert=os.environ.get("OPENSHELL_TLS_CERT", ""), tls_key=os.environ.get("OPENSHELL_TLS_KEY", ""), bearer_token=os.environ.get("OPENSHELL_BEARER_TOKEN", ""), - owner_instance=owner_instance, min_lifetime_seconds=_sandbox_min_lifetime_seconds(), expiry_skew_seconds=_sandbox_expiry_skew_seconds(), ) @@ -195,44 +149,31 @@ def _create_spawner(owner_instance: str = ""): async def reconcile_orphaned_sandboxes( - spawner: AgentSpawner | None, owner_instance: str = "", now: float | None = None + spawner: AgentSpawner | None, now: float | None = None ) -> None: - """Destroy orphaned sandboxes left from a previous crash. + """Destroy expired orphaned sandboxes left from a previous crash. On startup, lists sandboxes labelled "spawned-by=workflow-runner" once and - destroys those that either carry this replica's - "cloud-agents/owner-instance=" label, or whose - "cloud-agents/expires-at" is in the past regardless of owner (e.g. left - by a replaced pod whose name never comes back). This prevents resource - leaks after unclean shutdowns without touching sandboxes that other live - runner replicas are still using. - - Other replicas' unexpired sandboxes, sandboxes with no expires-at label - (spawned before expiry labelling existed) and sandboxes with a malformed - expires-at are left alone and logged. When owner_instance is empty only - expired sandboxes are destroyed. + 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. + + 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. - owner_instance: This replica's identity (see _runner_instance_id()). - Must match the value the spawner stamps on sandboxes it creates. now: Current unix time; defaults to time.time(). Injectable for tests. """ if spawner is None: return - if not owner_instance: - logger.warning( - "RUNNER_INSTANCE_ID/HOSTNAME not set — skipping own-instance orphan " - "cleanup (only expired sandboxes will be destroyed)" - ) now = time.time() if now is None else now orphans = [] no_expiry = 0 - for name, labels in await spawner.list_active_labels(SPAWNED_BY_LABEL): - if owner_instance and labels.get(OWNER_INSTANCE_LABEL_KEY) == owner_instance: - orphans.append(name) - continue + 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 @@ -249,17 +190,13 @@ async def reconcile_orphaned_sandboxes( if expired: orphans.append(name) if no_expiry: - logger.info( - "Leaving %d sandbox(es) with no expires-at label untouched " - "(legacy, or owned by another runner instance)", - 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 Exception as exc: logger.error("Failed to destroy orphaned sandbox '%s': %s", name, exc) @@ -352,8 +289,7 @@ def build_temporal_app( configure_logging() init_tracing("workflow-runner") - owner_instance = _runner_instance_id() - spawner = _create_spawner(owner_instance) + spawner = _create_spawner() transcript_store = TranscriptStore.from_env() if transcript_store is not None: logger.info("Transcript store configured (TRANSCRIPT_DB_URL set)") @@ -365,7 +301,7 @@ def build_temporal_app( @asynccontextmanager async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]: """Connect Temporal client and start worker on startup.""" - await reconcile_orphaned_sandboxes(spawner, owner_instance) + await reconcile_orphaned_sandboxes(spawner) # Connect transcript store (best-effort: failures are non-fatal) if transcript_store is not None: diff --git a/tests/unit/spawner/test_base.py b/tests/unit/spawner/test_base.py index 0ac8dffa..78acdce9 100644 --- a/tests/unit/spawner/test_base.py +++ b/tests/unit/spawner/test_base.py @@ -437,16 +437,25 @@ def test_millicore_cpu_exceeds_max_rejected(self) -> None: SpawnConfig(cpu_limit="5000m") -class TestListActiveLabelsDefault: +class TestListSandboxLabelsDefault: """Spawners without label support report no labels, so reconcile treats - their sandboxes as legacy and never destroys them.""" + 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_active_labels({"spawned-by": "workflow-runner"}) == [("a1", {})] + assert await spawner.list_sandbox_labels({"spawned-by": "workflow-runner"}) == [("a1", {})] + + @pytest.mark.asyncio + async def test_default_destroy_sandbox_destroys_that_name(self) -> None: + spawner = MockSpawner() + await spawner.spawn("a1", "img", env={}) + + await spawner.destroy_sandbox("a1") + + assert spawner.destroyed == ["a1"] class TestSpawnForwardsLifetime: diff --git a/tests/unit/spawner/test_factory.py b/tests/unit/spawner/test_factory.py index 9bcad2f6..cff32ec7 100644 --- a/tests/unit/spawner/test_factory.py +++ b/tests/unit/spawner/test_factory.py @@ -26,7 +26,7 @@ def test_builds_openshell_spawner_no_auth(self, mocker: MockerFixture) -> None: assert spawner._tls_ca == "" assert spawner._bearer_token == "" - def test_owner_instance_forwarded(self, mocker: MockerFixture) -> None: + 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 @@ -35,12 +35,10 @@ def test_owner_instance_forwarded(self, mocker: MockerFixture) -> None: spawner = build_spawner( "openshell", gateway_url="gw:17670", - owner_instance="runner-a", min_lifetime_seconds=7200, expiry_skew_seconds=30, ) - assert spawner._owner_instance == "runner-a" assert spawner._min_lifetime_seconds == 7200 assert spawner._expiry_skew_seconds == 30 diff --git a/tests/unit/spawner/test_lifetime.py b/tests/unit/spawner/test_lifetime.py index 3ac7d67a..cd1663ca 100644 --- a/tests/unit/spawner/test_lifetime.py +++ b/tests/unit/spawner/test_lifetime.py @@ -3,46 +3,45 @@ from __future__ import annotations from cloud_agents.spawner import lifetime -from cloud_agents.spawner.lifetime import ( - cli_session_lifetime_seconds, - step_sandbox_lifetime_seconds, -) +from cloud_agents.spawner.lifetime import run_timeout_seconds, step_sandbox_lifetime_seconds -# Everything around the step's own run time: gateway ready wait + HTTP ready -# wait + Temporal heartbeat timeout + transcript collection + destroy grace. -STEP_OVERHEAD = 300 + 60 + 180 + 30 + 120 +# Enforced deadlines around the run itself: spawn budget + transcript fetch + +# transcript save, plus destroy grace. +STEP_OVERHEAD = 420 + 30 + 30 + 120 -class TestStepSandboxLifetime: - def test_default_step_timeout(self) -> None: - assert step_sandbox_lifetime_seconds({"name": "s"}) == 600 + STEP_OVERHEAD +class TestRunTimeout: + def test_default(self) -> None: + assert run_timeout_seconds({"name": "s"}) == 600 - def test_step_timeout_drives_lifetime(self) -> None: - assert step_sandbox_lifetime_seconds({"timeout_seconds": 200_000}) == ( - 200_000 + STEP_OVERHEAD - ) + def test_permissions_timeout(self) -> None: + assert run_timeout_seconds({"permissions": {"timeout_seconds": 5000}}) == 5000 - def test_permissions_timeout_wins_when_longer(self) -> None: - step = {"timeout_seconds": 100, "permissions": {"timeout_seconds": 5000}} - assert step_sandbox_lifetime_seconds(step) == 5000 + STEP_OVERHEAD - def test_step_timeout_wins_when_longer(self) -> None: - step = {"timeout_seconds": 9000, "permissions": {"timeout_seconds": 50}} - assert step_sandbox_lifetime_seconds(step) == 9000 + STEP_OVERHEAD +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_constants_match_their_sources(self) -> None: - """The margins mirror the real waits/timeouts they bound.""" + 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_GATEWAY_READY_TIMEOUT_SECONDS == 300 - assert lifetime.SANDBOX_HTTP_READY_TIMEOUT_SECONDS == 60 - assert lifetime.SANDBOX_ACTIVITY_HEARTBEAT_TIMEOUT_SECONDS == 180 assert lifetime.SANDBOX_TRANSCRIPT_TIMEOUT_SECONDS == 30 - - -class TestCliSessionLifetime: - def test_follows_max_session_seconds(self) -> None: - assert cli_session_lifetime_seconds(3600, 30.0) == 3600 + 30 + 300 + 60 + 120 - assert cli_session_lifetime_seconds(7200, 30.0) == 7200 + 30 + 300 + 60 + 120 - - def test_rounds_check_interval_up(self) -> None: - assert cli_session_lifetime_seconds(100, 0.5) == 100 + 1 + 300 + 60 + 120 + assert lifetime.SANDBOX_TRANSCRIPT_SAVE_TIMEOUT_SECONDS == 30 diff --git a/tests/unit/spawner/test_openshell_spawner.py b/tests/unit/spawner/test_openshell_spawner.py index 773a6cc7..d47c16a7 100644 --- a/tests/unit/spawner/test_openshell_spawner.py +++ b/tests/unit/spawner/test_openshell_spawner.py @@ -472,46 +472,6 @@ async def mock_ready(*args, **kwargs): "cloud-agents/agent-name": "agent-1", } - @pytest.mark.asyncio - async def test_spawn_attaches_owner_instance_label(self, mocker: MockerFixture) -> None: - """owner_instance is stamped as cloud-agents/owner-instance so - reconcile_orphaned_sandboxes() only destroys this replica's sandboxes, - and it wins over a caller-supplied label of the same key.""" - 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, owner_instance="runner-a") - 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") - - await spawner.spawn( - "agent-1", "sandbox:latest", env={}, labels={"cloud-agents/owner-instance": "spoof"} - ) - - create_kwargs = mock_client.create.call_args.kwargs - assert create_kwargs["labels"] == { - "spawned-by": "workflow-runner", - "cloud-agents/agent-name": "agent-1", - "cloud-agents/owner-instance": "runner-a", - } - @staticmethod def _spawner_with_mocks(mocker: MockerFixture, **kwargs: Any): """OpenShellSpawner with gateway calls mocked, for label assertions.""" @@ -554,7 +514,8 @@ async def test_spawn_expires_at_uses_per_sandbox_lifetime(self, mocker: MockerFi await spawner.spawn("agent-1", "sandbox:latest", env={}, lifetime_seconds=200_000) labels = mock_client.create.call_args.kwargs["labels"] - assert labels["cloud-agents/expires-at"] == str(1_700_000_000 + 200_000 + 600) + # 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: @@ -569,7 +530,7 @@ async def test_spawn_expires_at_floors_at_min_lifetime(self, mocker: MockerFixtu @pytest.mark.asyncio async def test_spawn_without_lifetime_has_no_expiry(self, mocker: MockerFixture) -> None: - """No lifetime from the caller -> no expires-at (only the owner may reap + """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 @@ -591,9 +552,9 @@ def test_negative_lifetime_settings_rejected(self, mocker: MockerFixture, kwargs async def test_spawn_strips_reserved_caller_labels_when_unconfigured( self, mocker: MockerFixture ) -> None: - """Caller-supplied owner-instance/expires-at labels are always dropped, - even when the spawner has no owner or lifetime to stamp -- otherwise a - caller could make a sandbox look owned by (or expired for) a replica.""" + """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( @@ -1302,11 +1263,12 @@ async def test_list_active_queries_gateway_not_local_state(self, mocker: MockerF ) @pytest.mark.asyncio - async def test_list_active_labels_returns_names_with_labels( + async def test_list_sandbox_labels_returns_exact_sandbox_names( self, mocker: MockerFixture ) -> None: - """One ListSandboxes call yields each agent name with its labels, so - reconcile can partition by owner/expiry client-side.""" + """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() @@ -1316,10 +1278,10 @@ async def test_list_active_labels_returns_names_with_labels( ] spawner = OpenShellSpawner(openshell_client=mock_client) - result = await spawner.list_active_labels({"spawned-by": "workflow-runner"}) + result = await spawner.list_sandbox_labels({"spawned-by": "workflow-runner"}) assert result == [ - ("agent-1", {"cloud-agents/agent-name": "agent-1", "k": "v"}), + ("petname-1", {"cloud-agents/agent-name": "agent-1", "k": "v"}), ("petname-2", {}), ] mock_client.list.assert_called_once_with( @@ -1328,6 +1290,20 @@ async def test_list_active_labels_returns_names_with_labels( limit=1000, ) + @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 diff --git a/tests/unit/workflow/temporal/test_activities.py b/tests/unit/workflow/temporal/test_activities.py index 426801a3..4caaff6f 100644 --- a/tests/unit/workflow/temporal/test_activities.py +++ b/tests/unit/workflow/temporal/test_activities.py @@ -377,8 +377,8 @@ async def test_permissions_service_account_passed(self, mocker: MockerFixture) - @pytest.mark.asyncio async def test_spawn_gets_per_step_lifetime(self, mocker: MockerFixture) -> None: - """The sandbox's lifetime covers this step's own timeout, so a long - step's expires-at outlasts its start_to_close_timeout.""" + """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() @@ -399,7 +399,12 @@ async def test_spawn_gets_per_step_lifetime(self, mocker: MockerFixture) -> None ) mock_http.return_value.__aexit__ = mocker.AsyncMock(return_value=False) - step = {"name": "s1", "prompt": "check", "output_key": "r1", "timeout_seconds": 200_000} + step = { + "name": "s1", + "prompt": "check", + "output_key": "r1", + "permissions": {"timeout_seconds": 200_000}, + } await run_sandbox_step( { "step": step, diff --git a/tests/unit/workflow/temporal/test_cleanup_metrics.py b/tests/unit/workflow/temporal/test_cleanup_metrics.py index badb4d30..d1f2e516 100644 --- a/tests/unit/workflow/temporal/test_cleanup_metrics.py +++ b/tests/unit/workflow/temporal/test_cleanup_metrics.py @@ -104,14 +104,14 @@ 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_labels.return_value = [ - ("orphan-1", {"cloud-agents/owner-instance": "runner-a"}), - ("orphan-2", {"cloud-agents/owner-instance": "runner-a"}), + 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") - await reconcile_orphaned_sandboxes(mock_spawner, owner_instance="runner-a") + await reconcile_orphaned_sandboxes(mock_spawner) after = _get_counter_value("ls_sandbox_orphans_cleaned") assert after >= before + 2 @@ -122,11 +122,11 @@ 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_labels.return_value = [] + mock_spawner.list_sandbox_labels.return_value = [] before = _get_counter_value("ls_sandbox_orphans_cleaned") - await reconcile_orphaned_sandboxes(mock_spawner, owner_instance="runner-a") + await reconcile_orphaned_sandboxes(mock_spawner) after = _get_counter_value("ls_sandbox_orphans_cleaned") assert after == before @@ -139,10 +139,10 @@ 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_labels.return_value = [ - ("orphan-ok", {"cloud-agents/owner-instance": "runner-a"}), - ("orphan-fail", {"cloud-agents/owner-instance": "runner-a"}), - ("orphan-ok2", {"cloud-agents/owner-instance": "runner-a"}), + 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 @@ -153,11 +153,11 @@ 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") - await reconcile_orphaned_sandboxes(mock_spawner, owner_instance="runner-a") + await reconcile_orphaned_sandboxes(mock_spawner) after = _get_counter_value("ls_sandbox_orphans_cleaned") assert after >= before + 2 # 2 succeeded, 1 failed diff --git a/tests/unit/workflow/temporal/test_startup_reconciliation.py b/tests/unit/workflow/temporal/test_startup_reconciliation.py index 91694e8d..aaa51a95 100644 --- a/tests/unit/workflow/temporal/test_startup_reconciliation.py +++ b/tests/unit/workflow/temporal/test_startup_reconciliation.py @@ -2,6 +2,10 @@ from __future__ import annotations +import asyncio +import threading +import time +from typing import Any from unittest.mock import AsyncMock import pytest @@ -9,7 +13,7 @@ from cloud_agents.workflow.executor.temporal import entrypoint from cloud_agents.workflow.executor.temporal.entrypoint import reconcile_orphaned_sandboxes -OWNER_KEY = "cloud-agents/owner-instance" +AGENT_KEY = "cloud-agents/agent-name" EXPIRES_KEY = "cloud-agents/expires-at" NOW = 1_700_000_000.0 PAST = str(int(NOW) - 1) @@ -17,183 +21,122 @@ def _fake_spawner(sandboxes: dict[str, dict[str, str]]) -> AsyncMock: - """Build a spawner whose list_active_labels() returns sandboxes as-is. + """Spawner whose list_sandbox_labels() returns sandboxes as-is. - sandboxes maps agent name -> labels beyond spawned-by (an empty dict is a - legacy sandbox carrying only spawned-by=workflow-runner). + 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_active_labels(labels: dict[str, str] | None = None): + 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_active_labels.side_effect = list_active_labels + 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.call_args_list} + 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_orphaned_containers_destroyed_on_startup(self) -> None: - """Startup reconciliation destroys this instance's orphaned sandboxes, - expired or not, with a single gateway listing.""" + async def test_expired_sandboxes_destroyed_by_exact_name(self) -> None: mock_spawner = _fake_spawner( - { - "ca-orphan1": {OWNER_KEY: "runner-a", EXPIRES_KEY: FUTURE}, - "ca-orphan2": {OWNER_KEY: "runner-a"}, - } + {"sb-old1": {EXPIRES_KEY: PAST}, "sb-old2": {EXPIRES_KEY: PAST}} ) - await reconcile_orphaned_sandboxes(mock_spawner, owner_instance="runner-a", now=NOW) + await reconcile_orphaned_sandboxes(mock_spawner, now=NOW) - mock_spawner.list_active_labels.assert_called_once() - mock_spawner.list_active.assert_not_called() - assert _destroyed(mock_spawner) == {"ca-orphan1", "ca-orphan2"} + 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_other_instance_unexpired_sandboxes_survive(self) -> None: - """A restarting replica must not destroy another live replica's sandboxes.""" - mock_spawner = _fake_spawner( - { - "ca-mine": {OWNER_KEY: "runner-a", EXPIRES_KEY: FUTURE}, - "ca-theirs": {OWNER_KEY: "runner-b", EXPIRES_KEY: FUTURE}, - } - ) + async def test_unexpired_sandboxes_survive(self) -> None: + mock_spawner = _fake_spawner({"sb-live": {EXPIRES_KEY: FUTURE}}) - await reconcile_orphaned_sandboxes(mock_spawner, owner_instance="runner-a", now=NOW) + await reconcile_orphaned_sandboxes(mock_spawner, now=NOW) - assert _destroyed(mock_spawner) == {"ca-mine"} + mock_spawner.destroy_sandbox.assert_not_called() @pytest.mark.asyncio - async def test_other_instance_expired_sandbox_destroyed(self) -> None: - """Sandboxes past expires-at are reaped regardless of owner (e.g. left - by a replaced pod whose name will never come back).""" - mock_spawner = _fake_spawner({"ca-stale": {OWNER_KEY: "runner-gone", EXPIRES_KEY: PAST}}) + 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}} + ) - await reconcile_orphaned_sandboxes(mock_spawner, owner_instance="runner-a", now=NOW) + await reconcile_orphaned_sandboxes(mock_spawner, now=NOW) - assert _destroyed(mock_spawner) == {"ca-stale"} + 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({"ca-weird": {OWNER_KEY: "runner-b", EXPIRES_KEY: "soon"}}) + mock_spawner = _fake_spawner({"sb-weird": {EXPIRES_KEY: "soon"}}) with caplog.at_level("WARNING"): - await reconcile_orphaned_sandboxes(mock_spawner, owner_instance="runner-a", now=NOW) + await reconcile_orphaned_sandboxes(mock_spawner, now=NOW) - mock_spawner.destroy.assert_not_called() - assert "ca-weird" in caplog.text + mock_spawner.destroy_sandbox.assert_not_called() + assert "sb-weird" in caplog.text @pytest.mark.asyncio - async def test_legacy_sandboxes_left_alone_and_logged(self, caplog) -> None: - """Sandboxes without expires-at (legacy, or another owner without a - configured lifetime) are never destroyed by another instance.""" - mock_spawner = _fake_spawner({"ca-legacy": {}, "ca-noexpiry": {OWNER_KEY: "runner-b"}}) + 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, owner_instance="runner-a", now=NOW) + await reconcile_orphaned_sandboxes(mock_spawner, now=NOW) - mock_spawner.destroy.assert_not_called() + mock_spawner.destroy_sandbox.assert_not_called() assert "2 sandbox(es)" in caplog.text - @pytest.mark.asyncio - async def test_unset_identity_still_reaps_expired(self, caplog) -> None: - """Without an identity, own-instance cleanup is skipped with a warning, - but expired sandboxes are still destroyed.""" - mock_spawner = _fake_spawner( - { - "ca-expired": {OWNER_KEY: "runner-b", EXPIRES_KEY: PAST}, - "ca-live": {OWNER_KEY: "runner-b", EXPIRES_KEY: FUTURE}, - "ca-legacy": {}, - } - ) - - with caplog.at_level("WARNING"): - await reconcile_orphaned_sandboxes(mock_spawner, owner_instance="", now=NOW) - - assert _destroyed(mock_spawner) == {"ca-expired"} - assert "RUNNER_INSTANCE_ID" in caplog.text - - @pytest.mark.asyncio - async def test_unset_identity_is_default(self) -> None: - mock_spawner = _fake_spawner({"ca-any": {OWNER_KEY: ""}}) - - await reconcile_orphaned_sandboxes(mock_spawner, now=NOW) - - mock_spawner.destroy.assert_not_called() - @pytest.mark.asyncio async def test_no_orphans_no_destroy(self) -> None: mock_spawner = _fake_spawner({}) - await reconcile_orphaned_sandboxes(mock_spawner, owner_instance="runner-a", now=NOW) + await reconcile_orphaned_sandboxes(mock_spawner, now=NOW) - 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 = _fake_spawner({n: {OWNER_KEY: "a"} for n in ("o1", "o2", "o3")}) - 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, owner_instance="a", now=NOW) + 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, owner_instance="runner-a") + await reconcile_orphaned_sandboxes(None) -class TestRunnerInstanceId: - """_runner_instance_id(): RUNNER_INSTANCE_ID, else HOSTNAME, else "".""" +class TestNoRunnerIdentity: + """The owner-identity mechanism is gone: nothing resolves or stamps it.""" - def test_explicit_env_wins(self, monkeypatch) -> None: - monkeypatch.setenv("RUNNER_INSTANCE_ID", "workflow-runner-7d9f-abc12") - monkeypatch.setenv("HOSTNAME", "other") - assert entrypoint._runner_instance_id() == "workflow-runner-7d9f-abc12" + def test_entrypoint_has_no_identity_resolution(self) -> None: + assert not hasattr(entrypoint, "_runner_instance_id") - def test_falls_back_to_hostname_with_warning(self, monkeypatch, caplog) -> None: - """HOSTNAME isn't unique for runners sharing a host network, so the - fallback warns to set RUNNER_INSTANCE_ID.""" - monkeypatch.delenv("RUNNER_INSTANCE_ID", raising=False) - monkeypatch.setenv("HOSTNAME", "runner-host") - with caplog.at_level("WARNING"): - assert entrypoint._runner_instance_id() == "runner-host" - assert "RUNNER_INSTANCE_ID" in caplog.text - assert "host network" in caplog.text - - def test_unset_returns_empty(self, monkeypatch) -> None: - monkeypatch.delenv("RUNNER_INSTANCE_ID", raising=False) - monkeypatch.delenv("HOSTNAME", raising=False) - assert entrypoint._runner_instance_id() == "" - - @pytest.mark.parametrize("bad", ["has space", "a" * 64, "-leading", "trailing.", "x/y"]) - def test_invalid_explicit_id_fails_startup(self, monkeypatch, bad) -> None: - monkeypatch.setenv("RUNNER_INSTANCE_ID", bad) - with pytest.raises(ValueError, match="RUNNER_INSTANCE_ID"): - entrypoint._runner_instance_id() - - def test_invalid_hostname_skipped_with_warning(self, monkeypatch, caplog) -> None: - """A HOSTNAME fallback that isn't a legal label value (e.g. a long - FQDN on a dev machine) disables own-instance cleanup instead of - failing startup.""" - monkeypatch.delenv("RUNNER_INSTANCE_ID", raising=False) - monkeypatch.setenv("HOSTNAME", "h" * 64) - with caplog.at_level("WARNING"): - assert entrypoint._runner_instance_id() == "" - assert "HOSTNAME" in caplog.text + 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: @@ -223,104 +166,242 @@ def test_invalid_skew_fails_startup(self, monkeypatch, bad) -> None: with pytest.raises(ValueError, match="SANDBOX_EXPIRY_SKEW_SECONDS"): entrypoint._sandbox_expiry_skew_seconds() - -class TestCreateSpawnerWiring: - """_create_spawner() threads identity and lifetime settings into the spawner.""" - - def test_owner_and_lifetime_passed_to_spawner(self, mocker, monkeypatch) -> None: + 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(owner_instance="runner-a") + entrypoint._create_spawner() - assert build.call_args.kwargs["owner_instance"] == "runner-a" assert build.call_args.kwargs["min_lifetime_seconds"] == 7200 assert build.call_args.kwargs["expiry_skew_seconds"] == 45 - def test_invalid_lifetime_fails_startup(self, mocker, monkeypatch) -> None: - mocker.patch.object(entrypoint, "SPAWNER_TYPE", "openshell") - monkeypatch.setenv("SANDBOX_MIN_LIFETIME_SECONDS", "nope") - mocker.patch("cloud_agents.spawner.factory.build_spawner") - with pytest.raises(ValueError, match="SANDBOX_MIN_LIFETIME_SECONDS"): - entrypoint._create_spawner(owner_instance="runner-a") +# --- Real OpenShellSpawner against a fake gateway --------------------------- -class TestLongStepSurvivesOtherReplicaRestart: - """End to end: spawn label -> another replica's reconcile.""" +class _FakeRef: + def __init__(self, name: str, labels: dict[str, str]): + self.name = name + self.id = f"id-{name}" + self.labels = labels - @staticmethod - async def _expires_at_for_step(mocker, step: dict, spawn_time: float) -> str: - from cloud_agents.spawner.lifetime import step_sandbox_lifetime_seconds - from cloud_agents.spawner.openshell_spawner import OpenShellSpawner - class SandboxRef: - id = "id" - name = "sb" - - client = mocker.Mock() - client.create.return_value = SandboxRef() - client.exec_stream = lambda *a, **k: iter([]) - spawner = OpenShellSpawner( - openshell_client=client, - owner_instance="runner-b", - min_lifetime_seconds=86400, - expiry_skew_seconds=600, - clock=lambda: spawn_time, - ) - 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") - await spawner.spawn( - "ca-long", "img", env={}, lifetime_seconds=step_sandbox_lifetime_seconds(step) +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)), + ] ) - return client.create.call_args.kwargs["labels"][EXPIRES_KEY] + spawner = _real_spawner(mocker, gateway) + + await reconcile_orphaned_sandboxes(spawner, now=NOW) + + assert gateway.deleted == ["sb-expired"] @pytest.mark.asyncio - async def test_step_longer_than_global_minimum_kept_until_its_end(self, mocker) -> None: - from cloud_agents.spawner.lifetime import step_sandbox_lifetime_seconds + 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) - step = {"name": "long", "timeout_seconds": 200_000} # > 86400 global minimum - expires_at = await self._expires_at_for_step(mocker, step, spawn_time=NOW) + await reconcile_orphaned_sandboxes(spawner, now=NOW) - latest_legit_end = NOW + step_sandbox_lifetime_seconds(step) - assert int(expires_at) >= NOW + 200_000 + 300 + 60 + 180 - assert int(expires_at) >= latest_legit_end + assert gateway.deleted == ["sb-expired"] - other = _fake_spawner({"ca-long": {OWNER_KEY: "runner-b", EXPIRES_KEY: expires_at}}) - await reconcile_orphaned_sandboxes( - other, owner_instance="runner-a", now=latest_legit_end + 600 / 2 + @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"}), + ] ) - other.destroy.assert_not_called() + spawner = _real_spawner(mocker, gateway) + + await reconcile_orphaned_sandboxes(spawner, now=NOW) + + assert gateway.deleted == ["sb-expired"] + + +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, so expires-at is exactly as early as the bound allows. + """ - await reconcile_orphaned_sandboxes( - other, owner_instance="runner-a", now=latest_legit_end + 600 + 1 + DEADLINE = 1 + + @pytest.fixture(autouse=True) + def _short_deadline(self, mocker): + import cloud_agents.spawner.openshell_spawner as mod + + mocker.patch.object(mod, "SANDBOX_SPAWN_DEADLINE_SECONDS", self.DEADLINE) + + 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), + 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) + 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 ) - other.destroy.assert_called_once_with("ca-long") + + 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_no_lifetime_spawn_never_reaped_by_other_instance(self, mocker) -> None: - from cloud_agents.spawner.openshell_spawner import OpenShellSpawner + 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) - class SandboxRef: - id = "id" - name = "sb" + mocker.patch.object(spawner, "start_server", side_effect=hang) - client = mocker.Mock() - client.create.return_value = SandboxRef() - client.exec_stream = lambda *a, **k: iter([]) - spawner = OpenShellSpawner( - openshell_client=client, owner_instance="runner-b", min_lifetime_seconds=60 + 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 ) - 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") - await spawner.spawn("ca-nolife", "img", env={}) - labels = dict(client.create.call_args.kwargs["labels"]) - labels.pop("spawned-by") - - other = _fake_spawner({"ca-nolife": labels}) - await reconcile_orphaned_sandboxes(other, owner_instance="runner-a", now=NOW * 10) - other.destroy.assert_not_called() + + 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") diff --git a/tests/unit/workflow/test_cli_session.py b/tests/unit/workflow/test_cli_session.py index 334c93b1..2487017e 100644 --- a/tests/unit/workflow/test_cli_session.py +++ b/tests/unit/workflow/test_cli_session.py @@ -101,15 +101,16 @@ async def test_launch_calls_spawner_spawn(self) -> None: assert agent_name.startswith("cli-") @pytest.mark.asyncio - async def test_launch_lifetime_follows_max_session_seconds(self) -> None: - """CLI sandboxes get an expiry covering the session's own max duration.""" - from cloud_agents.spawner.lifetime import cli_session_lifetime_seconds - + @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) - launcher.start_timeout_monitor(spawner) + if with_monitor: + launcher.start_timeout_monitor(spawner) await launcher.launch( spawner=spawner, context_markdown="# ctx", @@ -117,29 +118,9 @@ async def test_launch_lifetime_follows_max_session_seconds(self) -> None: image="quay.io/sandbox:latest", workflow_id="wf-abc", ) - - lifetime = spawner.spawn.call_args.kwargs["lifetime_seconds"] - assert lifetime == cli_session_lifetime_seconds(7200, launcher._check_interval) - assert lifetime > 7200 await launcher.shutdown() - @pytest.mark.asyncio - async def test_launch_without_timeout_monitor_has_no_lifetime(self) -> None: - """Without the timeout monitor nothing enforces max_session_seconds, so - no lifetime (no expiry) is claimed -- only the owner may reap it.""" - spawner = AsyncMock() - spawner.spawn = AsyncMock(return_value="http://cli-agent:8080") - - launcher = CLISessionLauncher(max_session_seconds=7200) - await launcher.launch( - spawner=spawner, - context_markdown="# ctx", - prompt="p", - image="quay.io/sandbox:latest", - workflow_id="wf-abc", - ) - - assert spawner.spawn.call_args.kwargs["lifetime_seconds"] is None + assert spawner.spawn.call_args.kwargs.get("lifetime_seconds") is None @pytest.mark.asyncio async def test_launch_returns_session_id(self) -> None: diff --git a/tests/unit/workflow/test_sandbox_deadlines.py b/tests/unit/workflow/test_sandbox_deadlines.py index 2c340425..b74f1625 100644 --- a/tests/unit/workflow/test_sandbox_deadlines.py +++ b/tests/unit/workflow/test_sandbox_deadlines.py @@ -175,3 +175,109 @@ async def trickle(*args, **kwargs): 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() diff --git a/tests/unit/workflow/test_step_runner.py b/tests/unit/workflow/test_step_runner.py index 02bb0dfb..65075832 100644 --- a/tests/unit/workflow/test_step_runner.py +++ b/tests/unit/workflow/test_step_runner.py @@ -128,7 +128,7 @@ async def test_run_step_passes_per_step_lifetime( from cloud_agents.spawner.lifetime import step_sandbox_lifetime_seconds from cloud_agents.workflow.core.step_runner import run_step - step_input["step"]["timeout_seconds"] = 150_000 + 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"] From 43252fec898b39f5a0860373e739b5af300fb3b3 Mon Sep 17 00:00:00 2001 From: James Wong <2421248+jameswnl@users.noreply.github.com> Date: Sat, 31 Oct 2026 23:53:47 -0400 Subject: [PATCH 07/11] Harden spawn cleanup, heartbeats, exact destroy and listing - Cancellation during spawn now cleans up like any other failure: _do_spawn deletes the exact created sandbox and base spawn() restores the active count on BaseException, then re-raises. - The Temporal activity heartbeats from before spawn() until the activity ends, so a long spawn can't trip the 180s heartbeat timeout; the task is cancelled in the outer finally on every path. - AgentSpawner._do_destroy_sandbox() raises NotImplementedError instead of falling back to agent-name destroy(), which could delete more than the selected sandbox; reconcile skips and logs such sandboxes. - OpenShellSpawner pages ListSandboxes with offset instead of a single limit=1000 call. The progress-streaming tests' POST mock now yields once, as a real agent run does; they had relied on an incidental await in the old heartbeat placement for the progress task to start. Co-Authored-By: Claude Opus 5.5 --- src/cloud_agents/spawner/base.py | 23 +++++-- src/cloud_agents/spawner/openshell_spawner.py | 32 +++++---- .../workflow/executor/temporal/activities.py | 10 +-- .../workflow/executor/temporal/entrypoint.py | 6 ++ tests/unit/spawner/test_base.py | 26 +++++++- tests/unit/spawner/test_openshell_spawner.py | 20 ++++++ .../temporal/test_progress_streaming.py | 11 +++- .../temporal/test_startup_reconciliation.py | 58 ++++++++++++++++ tests/unit/workflow/test_sandbox_deadlines.py | 66 +++++++++++++++++++ 9 files changed, 226 insertions(+), 26 deletions(-) diff --git a/src/cloud_agents/spawner/base.py b/src/cloud_agents/spawner/base.py index 6aae133c..aec1eea4 100644 --- a/src/cloud_agents/spawner/base.py +++ b/src/cloud_agents/spawner/base.py @@ -204,7 +204,8 @@ async def spawn( 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 @@ -272,6 +273,9 @@ async def list_sandbox_labels( ) -> 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. @@ -294,12 +298,23 @@ async def _do_list_sandbox_labels( 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.""" + """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: - """Default: names from the default listing are agent names.""" - await self.destroy(sandbox_name) + """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/openshell_spawner.py b/src/cloud_agents/spawner/openshell_spawner.py index 814a04e9..1215d543 100644 --- a/src/cloud_agents/spawner/openshell_spawner.py +++ b/src/cloud_agents/spawner/openshell_spawner.py @@ -171,6 +171,9 @@ 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=...) @@ -1185,7 +1188,8 @@ async def _do_spawn( ) if not ready: raise RuntimeError(f"Sandbox '{sandbox_name}' HTTP server did not become ready") - except Exception as exc: + 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", @@ -2130,14 +2134,18 @@ async def _do_destroy_sandbox(self, sandbox_name: str) -> None: 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 = 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 list(refs) + 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/executor/temporal/activities.py b/src/cloud_agents/workflow/executor/temporal/activities.py index aeb09d9e..446d71e4 100644 --- a/src/cloud_agents/workflow/executor/temporal/activities.py +++ b/src/cloud_agents/workflow/executor/temporal/activities.py @@ -572,6 +572,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") @@ -654,7 +657,6 @@ async def _run_sandbox_step_inner( _progress_streaming_loop(spawner, sandbox_id) ) - heartbeat_task = asyncio.create_task(_heartbeat_loop()) try: async with httpx.AsyncClient(**client_kwargs) as client: try: @@ -698,9 +700,6 @@ async def _run_sandbox_step_inner( ).inc() raise 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): @@ -775,6 +774,9 @@ async def _run_sandbox_step_inner( raise finally: + heartbeat_task.cancel() + with contextlib.suppress(asyncio.CancelledError): + await heartbeat_task 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 3538cfd1..764de6b2 100644 --- a/src/cloud_agents/workflow/executor/temporal/entrypoint.py +++ b/src/cloud_agents/workflow/executor/temporal/entrypoint.py @@ -198,6 +198,12 @@ async def reconcile_orphaned_sandboxes( try: 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/tests/unit/spawner/test_base.py b/tests/unit/spawner/test_base.py index 78acdce9..97f47b2b 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 @@ -449,13 +451,31 @@ async def test_default_returns_empty_labels(self) -> None: assert await spawner.list_sandbox_labels({"spawned-by": "workflow-runner"}) == [("a1", {})] @pytest.mark.asyncio - async def test_default_destroy_sandbox_destroys_that_name(self) -> None: + 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={}) - await spawner.destroy_sandbox("a1") + with pytest.raises(NotImplementedError): + await spawner.destroy_sandbox("a1") + + assert spawner.destroyed == [] - assert spawner.destroyed == ["a1"] + @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: diff --git a/tests/unit/spawner/test_openshell_spawner.py b/tests/unit/spawner/test_openshell_spawner.py index d47c16a7..14977b2b 100644 --- a/tests/unit/spawner/test_openshell_spawner.py +++ b/tests/unit/spawner/test_openshell_spawner.py @@ -1260,6 +1260,7 @@ 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 @@ -1288,8 +1289,26 @@ async def test_list_sandbox_labels_returns_exact_sandbox_names( 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 @@ -1320,6 +1339,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_progress_streaming.py b/tests/unit/workflow/temporal/test_progress_streaming.py index 7f56f065..3eb43e69 100644 --- a/tests/unit/workflow/temporal/test_progress_streaming.py +++ b/tests/unit/workflow/temporal/test_progress_streaming.py @@ -53,9 +53,14 @@ def _mock_http_success(mocker: MockerFixture) -> MagicMock: mock_http = mocker.patch( "cloud_agents.workflow.executor.temporal.activities.httpx.AsyncClient", ) - mock_client_instance = mocker.MagicMock( - post=mocker.AsyncMock(return_value=mock_response), - ) + + 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(side_effect=post)) mock_http.return_value.__aenter__ = mocker.AsyncMock( return_value=mock_client_instance, ) diff --git a/tests/unit/workflow/temporal/test_startup_reconciliation.py b/tests/unit/workflow/temporal/test_startup_reconciliation.py index aaa51a95..ef529020 100644 --- a/tests/unit/workflow/temporal/test_startup_reconciliation.py +++ b/tests/unit/workflow/temporal/test_startup_reconciliation.py @@ -300,6 +300,64 @@ async def test_expired_and_unlabelled_legacy_only_expired_deleted(self, mocker) 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 diff --git a/tests/unit/workflow/test_sandbox_deadlines.py b/tests/unit/workflow/test_sandbox_deadlines.py index b74f1625..0d8c5c88 100644 --- a/tests/unit/workflow/test_sandbox_deadlines.py +++ b/tests/unit/workflow/test_sandbox_deadlines.py @@ -281,3 +281,69 @@ async def hang(*args, **kwargs): 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 From 28fae8334ce42700f94751efe1964f065d841f36 Mon Sep 17 00:00:00 2001 From: James Wong <2421248+jameswnl@users.noreply.github.com> Date: Sun, 1 Nov 2026 00:03:17 -0400 Subject: [PATCH 08/11] Bound stalled client closes and cleanup within the sandbox lifetime The run deadline sat inside the HTTP client context, so a client close that stalled, or a progress task slow to cancel, kept the step using the sandbox past its expiry. Nesting asyncio.timeout can't fix that: a timeout fires once, so cleanup that runs after it (a close following a POST that timed out) gets no bound of its own. The new await_within()/cancel_within() helpers in spawner/lifetime.py run the work as a task, wait for it up to its deadline, then cancel it and wait at most a 5s cancel grace. Work still running after that is abandoned: logged, never awaited again, and the step fails or moves on without touching the sandbox from that phase. Both engines run the run call (POST plus client close), the transcript fetch (GET plus client close) and the transcript save through await_within(), and cancel the progress stream (and the Temporal heartbeat) with cancel_within(). A timed-out run therefore never goes on to fetch the transcript. The step lifetime is now 420 + run timeout + 30 + 30 + 4 x 5 + 120 seconds. Docs describe bounded cooperative I/O versus abandoned uncooperative work, and that Python can't preempt arbitrary code. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- docs/sandbox-contract.md | 28 +- src/cloud_agents/spawner/lifetime.py | 78 ++++- src/cloud_agents/workflow/core/step_runner.py | 67 +++-- .../workflow/executor/temporal/activities.py | 78 ++--- tests/unit/spawner/test_lifetime.py | 7 +- tests/unit/workflow/test_bounded_io.py | 279 ++++++++++++++++++ 7 files changed, 464 insertions(+), 75 deletions(-) create mode 100644 tests/unit/workflow/test_bounded_io.py diff --git a/CLAUDE.md b/CLAUDE.md index bfac48fd..c3f4e9fb 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. 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, 30s transcript fetch, 30s save, 120s grace); 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`. | +| 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 + 4×5s cancel grace + 120s grace; each post-spawn phase runs 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/sandbox-contract.md b/docs/sandbox-contract.md index e3a637bb..6659107e 100644 --- a/docs/sandbox-contract.md +++ b/docs/sandbox-contract.md @@ -160,13 +160,33 @@ enforced deadlines measured from when `expires-at` is stamped: 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). Both engines enforce it - as an overall deadline on `POST /v1/agent/run`, since httpx's own timeout is - per read. Temporal's `start_to_close_timeout` can only end a step earlier. -- **Transcript fetch: 30s, transcript-store save: 30s.** +- **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 + 4 × 5 + 120 seconds. + +**Bounded vs. abandoned work.** Each post-spawn phase runs 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. The spawn budget uses `asyncio.timeout_at` around SDK calls made via +`asyncio.to_thread` (cancellation returns immediately; see above) and the +readiness check. + 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 diff --git a/src/cloud_agents/spawner/lifetime.py b/src/cloud_agents/spawner/lifetime.py index fd2b4b1f..0ab903ed 100644 --- a/src/cloud_agents/spawner/lifetime.py +++ b/src/cloud_agents/spawner/lifetime.py @@ -13,12 +13,28 @@ 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. + +Each post-spawn I/O phase runs 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 typing import Any +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). @@ -50,6 +66,9 @@ 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 # 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. @@ -65,14 +84,65 @@ def run_timeout_seconds(step: dict[str, Any]) -> float: 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, plus destroy grace. Each - retry attempt spawns a fresh sandbox (attempt is part of - compute_pod_name()), so this is per attempt. + transcript fetch and transcript save deadlines, a cancel grace for each + of the four bounded post-spawn phases (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 + + 4 * SANDBOX_CANCEL_GRACE_SECONDS + SANDBOX_DESTROY_GRACE_SECONDS ) + + +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: + TimeoutError: 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 TimeoutError(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() + done, _ = await asyncio.wait({task}, timeout=SANDBOX_CANCEL_GRACE_SECONDS) + if task in done: + _consume(task) + return + logger.warning( + "%s did not stop within %ss of cancellation — abandoning it", + what, + SANDBOX_CANCEL_GRACE_SECONDS, + ) + task.add_done_callback(_consume) + + +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/workflow/core/step_runner.py b/src/cloud_agents/workflow/core/step_runner.py index d9ed0658..32b5dc3a 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 @@ -28,6 +27,8 @@ 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, ) @@ -81,16 +82,21 @@ async def _collect_transcript( try: # 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. - async with asyncio.timeout(SANDBOX_TRANSCRIPT_TIMEOUT_SECONDS): + # 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: - response = await client.get( + 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 @@ -440,29 +446,14 @@ 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: - # httpx's timeout is per read; enforce http_timeout as - # an overall deadline (the local engine has no other - # wall-clock bound on the step). - async with asyncio.timeout(http_timeout): - response = await client.post( - f"{endpoint}/v1/agent/run", - json=request_body, - headers=http_headers or None, - ) - 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"}, + return await client.post( + f"{endpoint}/v1/agent/run", + json=request_body, + headers=http_headers or None, ) - # 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 except (ssl.SSLError, httpx.ConnectError) as tls_exc: emit_audit( event_type="tls_error", @@ -478,11 +469,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) @@ -499,8 +505,11 @@ async def _run_step_inner( try: # Runs before destroy, so it's bounded like every other # phase in the sandbox lifetime (cloud_agents.spawner.lifetime). - async with asyncio.timeout(SANDBOX_TRANSCRIPT_SAVE_TIMEOUT_SECONDS): - await transcript_store.save(workflow_id, output_key, transcript) + 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 446d71e4..900ea957 100644 --- a/src/cloud_agents/workflow/executor/temporal/activities.py +++ b/src/cloud_agents/workflow/executor/temporal/activities.py @@ -26,6 +26,8 @@ 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, ) @@ -322,16 +324,21 @@ async def _collect_transcript( try: # 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. - async with asyncio.timeout(SANDBOX_TRANSCRIPT_TIMEOUT_SECONDS): + # 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: - response = await client.get( + 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) return empty @@ -657,33 +664,14 @@ async def _run_sandbox_step_inner( _progress_streaming_loop(spawner, sandbox_id) ) - try: + async def _run_call() -> httpx.Response: async with httpx.AsyncClient(**client_kwargs) as client: try: - # httpx's timeout is per read; enforce http_timeout as - # an overall local deadline rather than relying on - # heartbeat-delivered cancellation. - async with asyncio.timeout(http_timeout): - response = await client.post( - f"{endpoint}/v1/agent/run", - json=request_body, - headers=http_headers or None, - ) - except TimeoutError: - from cloud_agents.workflow.executor.temporal.metrics import ( - ls_sandbox_timeout_total, + return await client.post( + f"{endpoint}/v1/agent/run", + json=request_body, + headers=http_headers or None, ) - - 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 except ssl.SSLError as tls_exc: emit_audit( event_type="tls_error", @@ -699,11 +687,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: 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) @@ -724,8 +731,11 @@ async def _run_sandbox_step_inner( try: # Runs before destroy, so it's bounded like every other # phase in the sandbox lifetime (cloud_agents.spawner.lifetime). - async with asyncio.timeout(SANDBOX_TRANSCRIPT_SAVE_TIMEOUT_SECONDS): - await transcript_store.save(workflow_id, output_key, transcript) + 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'", @@ -774,9 +784,7 @@ async def _run_sandbox_step_inner( raise finally: - heartbeat_task.cancel() - with contextlib.suppress(asyncio.CancelledError): - await heartbeat_task + 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/tests/unit/spawner/test_lifetime.py b/tests/unit/spawner/test_lifetime.py index cd1663ca..db7f80bc 100644 --- a/tests/unit/spawner/test_lifetime.py +++ b/tests/unit/spawner/test_lifetime.py @@ -6,8 +6,10 @@ 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, plus destroy grace. -STEP_OVERHEAD = 420 + 30 + 30 + 120 +# transcript save, a cancel grace for each of the four bounded I/O phases +# (run call, progress cleanup, transcript fetch, transcript save), plus +# destroy grace. +STEP_OVERHEAD = 420 + 30 + 30 + 4 * 5 + 120 class TestRunTimeout: @@ -45,3 +47,4 @@ def test_constants(self) -> None: 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/workflow/test_bounded_io.py b/tests/unit/workflow/test_bounded_io.py new file mode 100644 index 00000000..4bbfc324 --- /dev/null +++ b/tests/unit/workflow/test_bounded_io.py @@ -0,0 +1,279 @@ +"""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) From bbf6e695b3438e0e6b16521af3de79ac167f051e Mon Sep 17 00:00:00 2001 From: James Wong <2421248+jameswnl@users.noreply.github.com> Date: Sun, 1 Nov 2026 00:11:52 -0400 Subject: [PATCH 09/11] Run the spawn budget and its failure cleanup through await_within The spawn budget used asyncio.timeout_at, which fires once, so cleanup that runs after the deadline (e.g. the readiness check's HTTP client close) had no bound of its own, and the best-effort delete after a failed spawn could block the caller indefinitely. CreateSandbox and all post-create work now run as a nested coroutine through await_within(), with the rest of the budget that started at the expires-at stamp, so work still running after the deadline is cancelled and, past the cancel grace, abandoned and logged. The failure-path sandbox cleanup and provider delete are each bounded by SANDBOX_SPAWN_CLEANUP_TIMEOUT_SECONDS (30s); that's not part of the lifetime, because a sandbox whose spawn failed is no longer used. The step lifetime is now 420 + run timeout + 30 + 30 + 5 x 5 + 120 seconds. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- docs/sandbox-contract.md | 21 ++- src/cloud_agents/spawner/lifetime.py | 13 +- src/cloud_agents/spawner/openshell_spawner.py | 167 +++++++++++------- tests/unit/spawner/test_lifetime.py | 8 +- .../temporal/test_startup_reconciliation.py | 87 ++++++++- 6 files changed, 209 insertions(+), 89 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index c3f4e9fb..3f2561f5 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. 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 + 4×5s cancel grace + 120s grace; each post-spawn phase runs 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`. | +| 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/sandbox-contract.md b/docs/sandbox-contract.md index 6659107e..8c028bac 100644 --- a/docs/sandbox-contract.md +++ b/docs/sandbox-contract.md @@ -149,13 +149,18 @@ nothing. **Per-sandbox lifetime** (`cloud_agents/spawner/lifetime.py`), the sum of the enforced deadlines measured from when `expires-at` is stamped: -- **Spawn: 420s** (`SANDBOX_SPAWN_DEADLINE_SECONDS`). One `asyncio` deadline in - `OpenShellSpawner._do_spawn` that starts at the same instant `expires-at` is - stamped and covers CreateSandbox (30s SDK RPC timeout), the 300s gateway +- **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. Cancelling the + 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 @@ -170,9 +175,9 @@ enforced deadlines measured from when `expires-at` is stamped: - **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 + 4 × 5 + 120 seconds. +So a step's lifetime is 420 + run timeout + 30 + 30 + 5 × 5 + 120 seconds. -**Bounded vs. abandoned work.** Each post-spawn phase runs through +**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 @@ -183,9 +188,7 @@ 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. The spawn budget uses `asyncio.timeout_at` around SDK calls made via -`asyncio.to_thread` (cancellation returns immediately; see above) and the -readiness check. +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 diff --git a/src/cloud_agents/spawner/lifetime.py b/src/cloud_agents/spawner/lifetime.py index 0ab903ed..9990f4ea 100644 --- a/src/cloud_agents/spawner/lifetime.py +++ b/src/cloud_agents/spawner/lifetime.py @@ -14,7 +14,7 @@ Lifecycles without an enforced latest-use bound (e.g. CLI sessions) pass no lifetime and get no expiry, so startup reconcile never reaps them. -Each post-spawn I/O phase runs through await_within(): the work runs as a +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 @@ -69,6 +69,11 @@ # 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. @@ -85,8 +90,8 @@ 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 four bounded post-spawn phases (run, progress cleanup, transcript - fetch, transcript save), plus destroy grace. Each retry attempt spawns a + 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. """ @@ -95,7 +100,7 @@ def step_sandbox_lifetime_seconds(step: dict[str, Any]) -> int: + math.ceil(run_timeout_seconds(step)) + SANDBOX_TRANSCRIPT_TIMEOUT_SECONDS + SANDBOX_TRANSCRIPT_SAVE_TIMEOUT_SECONDS - + 4 * SANDBOX_CANCEL_GRACE_SECONDS + + 5 * SANDBOX_CANCEL_GRACE_SECONDS + SANDBOX_DESTROY_GRACE_SECONDS ) diff --git a/src/cloud_agents/spawner/openshell_spawner.py b/src/cloud_agents/spawner/openshell_spawner.py index 1215d543..b1cf990e 100644 --- a/src/cloud_agents/spawner/openshell_spawner.py +++ b/src/cloud_agents/spawner/openshell_spawner.py @@ -32,8 +32,10 @@ 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, + await_within, ) if TYPE_CHECKING: @@ -1119,75 +1121,87 @@ async def _do_spawn( # 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 - try: - async with asyncio.timeout_at(spawn_deadline): - sandbox_ref = await asyncio.to_thread( - self._client.create, - workspace=self._workspace, - spec=spec, - labels=sandbox_labels, - ) - 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 - await asyncio.to_thread( - self._client.wait_ready, - sandbox_name, - workspace=self._workspace, - timeout_seconds=SANDBOX_GATEWAY_READY_TIMEOUT_SECONDS, - ) + 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 = created_name = sandbox_ref.name + sandbox_id = sandbox_ref.id + self._sandbox_names[agent_name] = sandbox_name + self._sandbox_ids[agent_name] = sandbox_id - # Credential Provider already created and attached via spec.providers - # before sandbox creation (see above) -- no post-create injection needed. - # The old _inject_credentials path (CreateProvider + Attach after - # wait_ready with real env) is removed to avoid exposing the real - # credential in spec.environment (issue #199). - - if mcp_secret_mounts: - await self._inject_mcp_secrets(agent_name, mcp_secret_mounts, env) - - # Advisory (read_only=True) spawns use _build_filesystem_policy(), - # which grants blanket "/" read but no write outside /tmp, - # /home/agent, /var/log, MCP, and credentials -- not - # _MATERIALIZED_SKILLS_DIR. Materializing there would fail with - # the same EACCES this method now raises loudly for, so advisory - # spawns skip materialize entirely and list _SKILLS_ROOT (the - # master) directly below instead -- consistent with advisory - # mode's existing documented semantics that its blanket read - # grant already covers all of /skills regardless of - # allowed_skills, since advisory is an integrity boundary - # (no-write), not a confidentiality one. - if allowed_skills and not read_only: - await self._materialize_allowed_skills(sandbox_id, allowed_skills) - - # self._extra_env first, then the caller's own env on top, so an - # explicit caller-provided value (e.g. a different derived image's - # PYTHONPATH) wins on collision rather than being silently - # overridden by the spawner's own default (issue #192). - # Filter credential keys from server_env as well -- start_server - # execs inside the sandbox, so env there would also expose the - # real credential to the sandboxed process (issue #199). - filtered_env = {k: v for k, v in env.items() if k not in cred_keys} - server_env = {**self._extra_env, **filtered_env} - if read_only: - server_env["LIGHTSPEED_SKILLS_DIR"] = self._SKILLS_ROOT - await self.start_server(sandbox_id, _DEFAULT_SERVER_COMMAND, env=server_env) - - endpoint, virtual_host = await self._expose_service( - sandbox_name, - port=8080, - ) - self._virtual_hosts[sandbox_name] = virtual_host + await asyncio.to_thread( + self._client.wait_ready, + sandbox_name, + workspace=self._workspace, + timeout_seconds=SANDBOX_GATEWAY_READY_TIMEOUT_SECONDS, + ) - ready = await self._wait_ready_with_host( - endpoint, - virtual_host, - timeout=SANDBOX_HTTP_READY_TIMEOUT_SECONDS, - ) - if not ready: - raise RuntimeError(f"Sandbox '{sandbox_name}' HTTP server did not become ready") + # Credential Provider already created and attached via spec.providers + # before sandbox creation (see above) -- no post-create injection needed. + # The old _inject_credentials path (CreateProvider + Attach after + # wait_ready with real env) is removed to avoid exposing the real + # credential in spec.environment (issue #199). + + if mcp_secret_mounts: + await self._inject_mcp_secrets(agent_name, mcp_secret_mounts, env) + + # Advisory (read_only=True) spawns use _build_filesystem_policy(), + # which grants blanket "/" read but no write outside /tmp, + # /home/agent, /var/log, MCP, and credentials -- not + # _MATERIALIZED_SKILLS_DIR. Materializing there would fail with + # the same EACCES this method now raises loudly for, so advisory + # spawns skip materialize entirely and list _SKILLS_ROOT (the + # master) directly below instead -- consistent with advisory + # mode's existing documented semantics that its blanket read + # grant already covers all of /skills regardless of + # allowed_skills, since advisory is an integrity boundary + # (no-write), not a confidentiality one. + if allowed_skills and not read_only: + await self._materialize_allowed_skills(sandbox_id, allowed_skills) + + # self._extra_env first, then the caller's own env on top, so an + # explicit caller-provided value (e.g. a different derived image's + # PYTHONPATH) wins on collision rather than being silently + # overridden by the spawner's own default (issue #192). + # Filter credential keys from server_env as well -- start_server + # execs inside the sandbox, so env there would also expose the + # real credential to the sandboxed process (issue #199). + filtered_env = {k: v for k, v in env.items() if k not in cred_keys} + server_env = {**self._extra_env, **filtered_env} + if read_only: + server_env["LIGHTSPEED_SKILLS_DIR"] = self._SKILLS_ROOT + await self.start_server(sandbox_id, _DEFAULT_SERVER_COMMAND, env=server_env) + + endpoint, virtual_host = await self._expose_service( + sandbox_name, + port=8080, + ) + self._virtual_hosts[sandbox_name] = virtual_host + + ready = await self._wait_ready_with_host( + endpoint, + virtual_host, + timeout=SANDBOX_HTTP_READY_TIMEOUT_SECONDS, + ) + if not ready: + raise RuntimeError(f"Sandbox '{sandbox_name}' HTTP server did not become ready") + 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( @@ -1205,13 +1219,30 @@ async def _do_spawn( # 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: - await self._cleanup_sandbox(agent_name, created_name) + 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 ) diff --git a/tests/unit/spawner/test_lifetime.py b/tests/unit/spawner/test_lifetime.py index db7f80bc..a88fe72d 100644 --- a/tests/unit/spawner/test_lifetime.py +++ b/tests/unit/spawner/test_lifetime.py @@ -6,10 +6,10 @@ 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 four bounded I/O phases -# (run call, progress cleanup, transcript fetch, transcript save), plus -# destroy grace. -STEP_OVERHEAD = 420 + 30 + 30 + 4 * 5 + 120 +# 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: diff --git a/tests/unit/workflow/temporal/test_startup_reconciliation.py b/tests/unit/workflow/temporal/test_startup_reconciliation.py index ef529020..a1f811b8 100644 --- a/tests/unit/workflow/temporal/test_startup_reconciliation.py +++ b/tests/unit/workflow/temporal/test_startup_reconciliation.py @@ -364,22 +364,29 @@ class TestSpawnDeadlineRealSpawner: budget is never reaped before its spawn could have finished using it. Uses min_lifetime=0, skew=0 and lifetime_seconds == the (patched) - budget, so expires-at is exactly as early as the bound allows. + 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), + spawner.spawn( + "ca-agent", "img", env={}, lifetime_seconds=self.DEADLINE + self.GRACE + ), timeout=10, ) assert "deadline" in str(exc_info.value) @@ -392,7 +399,7 @@ async def _assert_not_reaped_before_budget_end(self, gateway, clock, name) -> No from cloud_agents.spawner.openshell_spawner import OpenShellSpawner other = OpenShellSpawner(openshell_client=reader) - await reconcile_orphaned_sandboxes(other, now=stamp + self.DEADLINE) + 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] @@ -463,3 +470,77 @@ async def test_slow_create_sandbox_bounded_and_left_to_expiry(self, mocker) -> N 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) From 0a9e277f3390791728a9ce62d005e50fe80d1f94 Mon Sep 17 00:00:00 2001 From: James Wong <2421248+jameswnl@users.noreply.github.com> Date: Sun, 1 Nov 2026 00:29:21 -0400 Subject: [PATCH 10/11] Consume abandoned task outcomes and keep spawn timeouts accurate - cancel_within() attaches its consume callback right after cancel(), so if the caller is cancelled again during the cancel grace the abandoned task's eventual exception is still retrieved ("Task exception was never retrieved" no longer leaks), and the abandonment is logged. - await_within() raises SandboxDeadlineExceeded (a TimeoutError) for its own deadline. The spawner reports "exceeded its deadline" only for that; a spawn phase's own TimeoutError propagates unchanged. - Progress-streaming tests no longer leak un-awaited AsyncMock coroutines into later tests: AsyncMock spawners get a sync get_query_ssl_context, and the shared HTTP mock answers the transcript GET. With those changes test_progress_streaming.py and test_bounded_io.py pass together under -W error in either order. Co-Authored-By: Claude Opus 5.5 --- src/cloud_agents/spawner/lifetime.py | 34 ++++++++++------ src/cloud_agents/spawner/openshell_spawner.py | 7 ++-- .../temporal/test_progress_streaming.py | 12 +++++- .../temporal/test_startup_reconciliation.py | 16 ++++++++ tests/unit/workflow/test_bounded_io.py | 40 +++++++++++++++++++ 5 files changed, 93 insertions(+), 16 deletions(-) diff --git a/src/cloud_agents/spawner/lifetime.py b/src/cloud_agents/spawner/lifetime.py index 9990f4ea..ef5eacd4 100644 --- a/src/cloud_agents/spawner/lifetime.py +++ b/src/cloud_agents/spawner/lifetime.py @@ -105,6 +105,11 @@ def step_sandbox_lifetime_seconds(step: dict[str, Any]) -> int: ) +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. @@ -113,8 +118,8 @@ async def await_within(work: Awaitable[T], timeout: float, *, what: str) -> T: no bound of its own. Raises: - TimeoutError: If work didn't finish within timeout. It is cancelled - and, if still running after the cancel grace, abandoned. + 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: @@ -125,7 +130,7 @@ async def await_within(work: Awaitable[T], timeout: float, *, what: str) -> T: if task in done: return task.result() await cancel_within(task, what=what) - raise TimeoutError(f"{what} timed out after {timeout:g}s") + raise SandboxDeadlineExceeded(f"{what} timed out after {timeout:g}s") async def cancel_within(task: asyncio.Future[Any], *, what: str) -> None: @@ -135,16 +140,21 @@ async def cancel_within(task: asyncio.Future[Any], *, what: str) -> None: awaited again. Its eventual result or error is consumed, not raised. """ task.cancel() - done, _ = await asyncio.wait({task}, timeout=SANDBOX_CANCEL_GRACE_SECONDS) - if task in done: - _consume(task) - return - logger.warning( - "%s did not stop within %ss of cancellation — abandoning it", - what, - SANDBOX_CANCEL_GRACE_SECONDS, - ) + # 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: diff --git a/src/cloud_agents/spawner/openshell_spawner.py b/src/cloud_agents/spawner/openshell_spawner.py index b1cf990e..55817a72 100644 --- a/src/cloud_agents/spawner/openshell_spawner.py +++ b/src/cloud_agents/spawner/openshell_spawner.py @@ -35,6 +35,7 @@ SANDBOX_SPAWN_CLEANUP_TIMEOUT_SECONDS, SANDBOX_SPAWN_DEADLINE_SECONDS, SPAWNED_BY_LABEL, + SandboxDeadlineExceeded, await_within, ) @@ -1250,9 +1251,9 @@ async def _create_and_start() -> str: logger.warning( "Failed to delete orphaned provider '%s'", provider_id, exc_info=True ) - if isinstance(exc, TimeoutError): - # str(TimeoutError()) is empty; callers' secret redaction - # would turn that into a blank error. + 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" diff --git a/tests/unit/workflow/temporal/test_progress_streaming.py b/tests/unit/workflow/temporal/test_progress_streaming.py index 3eb43e69..5ad4b03f 100644 --- a/tests/unit/workflow/temporal/test_progress_streaming.py +++ b/tests/unit/workflow/temporal/test_progress_streaming.py @@ -60,7 +60,11 @@ async def post(*args, **kwargs): await asyncio.sleep(0.05) return mock_response - mock_client_instance = mocker.MagicMock(post=mocker.AsyncMock(side_effect=post)) + mock_client_instance = mocker.MagicMock( + 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, ) @@ -198,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 @@ -223,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 a1f811b8..21fd3447 100644 --- a/tests/unit/workflow/temporal/test_startup_reconciliation.py +++ b/tests/unit/workflow/temporal/test_startup_reconciliation.py @@ -544,3 +544,19 @@ async def stuck_cleanup(*args, **kwargs): 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"] diff --git a/tests/unit/workflow/test_bounded_io.py b/tests/unit/workflow/test_bounded_io.py index 4bbfc324..4f9bb4b7 100644 --- a/tests/unit/workflow/test_bounded_io.py +++ b/tests/unit/workflow/test_bounded_io.py @@ -277,3 +277,43 @@ async def test_uncooperative_task_abandoned_and_logged(self, caplog) -> None: 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 From beb5ea9d0804436de8fa40757c477e62c8ced2ae Mon Sep 17 00:00:00 2001 From: James Wong <2421248+jameswnl@users.noreply.github.com> Date: Sun, 1 Nov 2026 00:59:20 -0400 Subject: [PATCH 11/11] Test MCP secret writes inside the spawn budget Since the merge of #277, MCP secret files are written within _create_and_start, under the spawn budget. Regressions using the real OpenShellSpawner against a fake gateway: - a failing secret write deletes exactly the created sandbox and restores the active count; - a hanging secret write is cut off by the spawn budget, raising the deadline error, and the sandbox is deleted; - the MCP secret key stays out of spec.environment while other env passes through (read from either the real protobuf map or the session-wide openshell stub that test_openshell_spawner.py may install). Co-Authored-By: Claude Opus 5.5 --- .../temporal/test_startup_reconciliation.py | 90 ++++++++++++++++++- 1 file changed, 89 insertions(+), 1 deletion(-) diff --git a/tests/unit/workflow/temporal/test_startup_reconciliation.py b/tests/unit/workflow/temporal/test_startup_reconciliation.py index 21fd3447..6c8db6b5 100644 --- a/tests/unit/workflow/temporal/test_startup_reconciliation.py +++ b/tests/unit/workflow/temporal/test_startup_reconciliation.py @@ -6,7 +6,7 @@ import threading import time from typing import Any -from unittest.mock import AsyncMock +from unittest.mock import AsyncMock, MagicMock import pytest @@ -560,3 +560,91 @@ async def test_own_timeout_error_not_reported_as_deadline(self, mocker) -> None: 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"