Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(tasks): end zombie cloud runs that break git signing (#65750)

Alessandro Pogliaghi2b621b8db018
diff --git a/products/tasks/backend/temporal/execute_sandbox/tests/test_execute_sandbox_workflow.py b/products/tasks/backend/temporal/execute_sandbox/tests/test_execute_sandbox_workflow.py
index ddcf477782e7..310241228ec9 100644
--- a/products/tasks/backend/temporal/execute_sandbox/tests/test_execute_sandbox_workflow.py
+++ b/products/tasks/backend/temporal/execute_sandbox/tests/test_execute_sandbox_workflow.py
@@ -21,8 +21,14 @@ from products.tasks.backend.temporal.execute_sandbox.workflow import (
ExecuteSandboxWorkflow,
OutboundSignal,
PendingFollowup,
+ SandboxEvent,
+)
+from products.tasks.backend.temporal.process_task.activities.get_sandbox_for_repository import (
+ GetSandboxForRepositoryOutput,
)
from products.tasks.backend.temporal.process_task.activities.get_task_processing_context import TaskProcessingContext
+from products.tasks.backend.temporal.process_task.activities.start_agent_server import StartAgentServerOutput
+from products.tasks.backend.temporal.process_task.credential_refresh import CredentialRefreshExitReason
def _build_context(
@@ -518,6 +524,83 @@ class TestPersistSandboxId:
class TestRun:
+ async def test_credential_refresh_exit_marks_sandbox_gone(self, monkeypatch, silent_workflow_logger):
+ workflow = ExecuteSandboxWorkflow()
+ workflow._context = _build_context()
+ refresh_loop_mock = AsyncMock(return_value=CredentialRefreshExitReason.SANDBOX_GONE)
+
+ monkeypatch.setattr(execute_sandbox_workflow_module, "run_credential_refresh_loop", refresh_loop_mock)
+
+ await workflow._run_credential_refresh_until_sandbox_gone("sandbox-123")
+
+ assert workflow._sandbox_gone is True
+ refresh_loop_mock.assert_awaited_once_with(workflow.context, "sandbox-123")
+ silent_workflow_logger.warning.assert_called_once_with(
+ "execute_sandbox_sandbox_gone_detected",
+ run_id="run-id",
+ sandbox_id="sandbox-123",
+ )
+
+ async def test_run_ends_session_without_failing_when_sandbox_gone(self, monkeypatch, silent_workflow_logger):
+ workflow = ExecuteSandboxWorkflow()
+ context = _build_context(state={"mode": "interactive"}, use_modal_resume_snapshots=False)
+ update_status_mock = AsyncMock()
+ cleanup_sandbox_mock = AsyncMock()
+
+ monkeypatch.setattr(workflow, "_reap_orphaned_sandbox", AsyncMock())
+ monkeypatch.setattr(workflow, "_get_task_processing_context", AsyncMock(return_value=context))
+ monkeypatch.setattr(workflow, "_update_task_run_status", update_status_mock)
+ monkeypatch.setattr(workflow, "_emit_progress", AsyncMock())
+ monkeypatch.setattr(workflow, "_track_workflow_event", AsyncMock())
+ monkeypatch.setattr(workflow, "_persist_sandbox_id", AsyncMock())
+ monkeypatch.setattr(workflow, "_read_sandbox_logs", AsyncMock())
+ monkeypatch.setattr(workflow, "_cleanup_sandbox", cleanup_sandbox_mock)
+ monkeypatch.setattr(workflow, "_clear_persisted_sandbox_id", AsyncMock())
+ monkeypatch.setattr(workflow, "_flush_pending_outbound", AsyncMock())
+ monkeypatch.setattr(workflow, "_relay_sandbox_events", AsyncMock())
+ monkeypatch.setattr(workflow, "_run_credential_refresh_until_sandbox_gone", AsyncMock())
+ monkeypatch.setattr(
+ workflow,
+ "_get_sandbox_for_repository",
+ AsyncMock(
+ return_value=GetSandboxForRepositoryOutput(
+ sandbox_id="sandbox-123",
+ sandbox_url="https://sandbox.example",
+ connect_token="connect-token",
+ used_snapshot=False,
+ should_create_snapshot=False,
+ )
+ ),
+ )
+ monkeypatch.setattr(
+ workflow,
+ "_start_agent_server",
+ AsyncMock(
+ return_value=StartAgentServerOutput(
+ sandbox_url="https://sandbox.example",
+ connect_token="connect-token",
+ )
+ ),
+ )
+ monkeypatch.setattr(workflow, "_wait_for_event", AsyncMock(return_value=SandboxEvent.SANDBOX_GONE))
+
+ result = await workflow.run(ExecuteSandboxInput(run_id="run-id", parent_workflow_id="parent-wf-id"))
+
+ assert result.success is True
+ assert workflow._completion_status == "completed"
+ terminal_status_writes = [
+ call for call in update_status_mock.await_args_list if call.args[:1] in (("failed",), ("cancelled",))
+ ]
+ assert terminal_status_writes == []
+ cleanup_sandbox_mock.assert_awaited_once_with("sandbox-123")
+ completed_signals = [
+ outbound for outbound in workflow._pending_outbound if outbound.target_signal == PARENT_COMPLETED_SIGNAL
+ ]
+ assert len(completed_signals) == 1
+ payload = completed_signals[0].args[0]
+ assert isinstance(payload, ChildCompletionPayload)
+ assert payload.success is True
+
async def test_context_load_failure_marks_run_failed(self, monkeypatch, silent_workflow_logger):
workflow = ExecuteSandboxWorkflow()
get_context_mock = AsyncMock(side_effect=RuntimeError("database connection closed"))
diff --git a/products/tasks/backend/temporal/execute_sandbox/workflow.py b/products/tasks/backend/temporal/execute_sandbox/workflow.py
index 5c717507cb51..3757faa4979d 100644
--- a/products/tasks/backend/temporal/execute_sandbox/workflow.py
+++ b/products/tasks/backend/temporal/execute_sandbox/workflow.py
@@ -95,7 +95,10 @@ from products.tasks.backend.temporal.process_task.activities.update_task_run_sta
UpdateTaskRunStatusInput,
update_task_run_status,
)
-from products.tasks.backend.temporal.process_task.credential_refresh import run_credential_refresh_loop
+from products.tasks.backend.temporal.process_task.credential_refresh import (
+ CredentialRefreshExitReason,
+ run_credential_refresh_loop,
+)
from products.tasks.backend.temporal.utils import log_on_fail
# Names of signals this workflow sends back to the TaskManagement parent. Kept
@@ -202,6 +205,7 @@ class ChildCompletionPayload:
class SandboxEvent(StrEnum):
SIGNAL_RECEIVED = "signal_received"
TIMEOUT_REACHED = "timeout_reached"
+ SANDBOX_GONE = "sandbox_gone"
@temporalio.workflow.defn(name="execute-sandbox")
@@ -240,6 +244,7 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):
self._task_completed: bool = False
self._completion_status: str = "completed"
self._completion_error: Optional[str] = None
+ self._sandbox_gone: bool = False
self._heartbeat_received: bool = False
self._pending_followups: list[PendingFollowup] = []
@@ -319,11 +324,14 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):
await workflow.wait_condition(
lambda: (
self._task_completed
+ or self._sandbox_gone
or self._heartbeat_received
or len(self._pending_followups) > 0
or len(self._pending_outbound) > 0
)
)
+ if self._sandbox_gone and not self._task_completed:
+ return SandboxEvent.SANDBOX_GONE
return SandboxEvent.SIGNAL_RECEIVED
async def _wait_for_inactivity(self) -> SandboxEvent:
@@ -412,7 +420,9 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):
relay_task = asyncio.ensure_future(self._relay_sandbox_events(agent_server_output, sandbox_id=sandbox_id))
if self.context.has_github_credentials:
- credential_refresh_task = asyncio.ensure_future(run_credential_refresh_loop(self.context, sandbox_id))
+ credential_refresh_task = asyncio.ensure_future(
+ self._run_credential_refresh_until_sandbox_gone(sandbox_id)
+ )
if self._should_forward_pending_user_message():
await self._forward_pending_user_message()
@@ -427,6 +437,8 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):
case SandboxEvent.TIMEOUT_REACHED:
timed_out = True
break
+ case SandboxEvent.SANDBOX_GONE:
+ self._mark_sandbox_gone()
case SandboxEvent.SIGNAL_RECEIVED:
# complete_task lands here too — `_flush_pending_outbound`
# delivers its ACK and the `while not self._task_completed:`
@@ -1090,6 +1102,19 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):
if self._task_completed and self._completion_status in {"failed", "cancelled"}:
await self._update_task_run_status(self._completion_status, error_message=self._completion_error)
+ async def _run_credential_refresh_until_sandbox_gone(self, sandbox_id: str) -> None:
+ exit_reason = await run_credential_refresh_loop(self.context, sandbox_id)
+ if exit_reason == CredentialRefreshExitReason.SANDBOX_GONE:
+ workflow.logger.warning(
+ "execute_sandbox_sandbox_gone_detected",
+ run_id=self.context.run_id,
+ sandbox_id=sandbox_id,
+ )
+ self._sandbox_gone = True
+
+ def _mark_sandbox_gone(self) -> None:
+ self._task_completed = True
+
# `log_on_fail` only catches `Exception`, so `asyncio.CancelledError`
# (a `BaseException`) still propagates — required for cooperative
# cancellation of the relay task on shutdown.
diff --git a/products/tasks/backend/temporal/process_task/credential_refresh.py b/products/tasks/backend/temporal/process_task/credential_refresh.py
index 50b363e53e41..4e82005949c3 100644
--- a/products/tasks/backend/temporal/process_task/credential_refresh.py
+++ b/products/tasks/backend/temporal/process_task/credential_refresh.py
@@ -1,4 +1,5 @@
from datetime import timedelta
+from enum import StrEnum
from temporalio import workflow
from temporalio.common import RetryPolicy
@@ -9,7 +10,14 @@ from .activities.get_task_processing_context import TaskProcessingContext
from .activities.refresh_sandbox_credentials import RefreshSandboxCredentialsInput, refresh_sandbox_credentials
-async def run_credential_refresh_loop(context: TaskProcessingContext, sandbox_id: str) -> None:
+class CredentialRefreshExitReason(StrEnum):
+ SANDBOX_GONE = "sandbox_gone"
+
+
+SANDBOX_GONE_ERROR_MESSAGE = "Sandbox stopped; resume to continue"
+
+
+async def run_credential_refresh_loop(context: TaskProcessingContext, sandbox_id: str) -> CredentialRefreshExitReason:
"""Periodically re-inject fresh credentials into the running sandbox.
Sandbox credentials (GitHub token; user *or* installation, per authorship)
@@ -31,7 +39,7 @@ async def run_credential_refresh_loop(context: TaskProcessingContext, sandbox_id
)
if result.sandbox_gone:
workflow.logger.info("Stopping credential refresh loop: sandbox is gone")
- return
+ return CredentialRefreshExitReason.SANDBOX_GONE
next_refresh_seconds = result.next_refresh_seconds
except Exception as e:
# Non-fatal: keep the run alive and retry on the default cadence.
diff --git a/products/tasks/backend/temporal/process_task/tests/test_workflow.py b/products/tasks/backend/temporal/process_task/tests/test_workflow.py
index eadb57e4cd68..15c622f87893 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_workflow.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_workflow.py
@@ -41,6 +41,10 @@ from products.tasks.backend.temporal.process_task.activities import (
track_workflow_event,
update_task_run_status,
)
+from products.tasks.backend.temporal.process_task.credential_refresh import (
+ SANDBOX_GONE_ERROR_MESSAGE,
+ CredentialRefreshExitReason,
+)
from products.tasks.backend.temporal.process_task.workflow import (
PendingFollowup,
ProcessTaskInput,
@@ -353,6 +357,24 @@ class TestProcessTaskWorkflowUnit:
def test_warm_idle_timeout_is_shorter_than_active_inactivity(self):
assert WARM_IDLE_TIMEOUT < timedelta(seconds=INACTIVITY_TIMEOUT_USER_SECONDS)
+ async def test_credential_refresh_exit_marks_sandbox_gone(self, monkeypatch):
+ workflow = ProcessTaskWorkflow()
+ workflow._context = _build_context(github_integration_id=123)
+ logger = Mock()
+ refresh_loop_mock = AsyncMock(return_value=CredentialRefreshExitReason.SANDBOX_GONE)
+
+ monkeypatch.setattr(process_task_workflow_module.workflow, "logger", logger)
+ monkeypatch.setattr(process_task_workflow_module, "run_credential_refresh_loop", refresh_loop_mock)
+
+ await workflow._run_credential_refresh_until_sandbox_gone("sandbox-123")
+
+ assert workflow._sandbox_gone is True
+ refresh_loop_mock.assert_awaited_once_with(workflow.context, "sandbox-123")
+ logger.warning.assert_called_once_with(
+ "sandbox_gone_detected",
+ extra={"run_id": "run-id", "sandbox_id": "sandbox-123"},
+ )
+
async def test_run_cleans_up_sandbox_when_provisioning_fails_after_creation(self, monkeypatch):
workflow = ProcessTaskWorkflow()
get_task_processing_context_mock = AsyncMock(return_value=_build_context(github_integration_id=123))
@@ -466,6 +488,61 @@ class TestProcessTaskWorkflowUnit:
assert result.success is True
relay_sandbox_events_mock.assert_not_awaited()
+ async def test_run_completes_when_credential_refresh_detects_sandbox_gone(self, monkeypatch):
+ workflow = ProcessTaskWorkflow()
+ context = _build_context(github_integration_id=123)
+ update_task_run_status_mock = AsyncMock()
+ cleanup_sandbox_mock = AsyncMock()
+
+ monkeypatch.setattr(workflow, "_get_task_processing_context", AsyncMock(return_value=context))
+ monkeypatch.setattr(workflow, "_update_task_run_status", update_task_run_status_mock)
+ monkeypatch.setattr(workflow, "_track_workflow_event", AsyncMock())
+ monkeypatch.setattr(workflow, "_post_slack_update", AsyncMock())
+ monkeypatch.setattr(workflow, "_read_sandbox_logs", AsyncMock())
+ monkeypatch.setattr(workflow, "_cleanup_sandbox", cleanup_sandbox_mock)
+ monkeypatch.setattr(workflow, "_create_resume_snapshot", AsyncMock())
+ monkeypatch.setattr(workflow, "_emit_progress", AsyncMock())
+ monkeypatch.setattr(workflow, "_forward_pending_user_message", AsyncMock())
+ monkeypatch.setattr(
+ workflow,
+ "_get_sandbox_for_repository",
+ AsyncMock(
+ return_value=GetSandboxForRepositoryOutput(
+ sandbox_id="sandbox-123",
+ sandbox_url="https://sandbox.example",
+ connect_token="connect-token",
+ used_snapshot=False,
+ should_create_snapshot=False,
+ )
+ ),
+ )
+ monkeypatch.setattr(
+ workflow,
+ "_start_agent_server",
+ AsyncMock(
+ return_value=StartAgentServerOutput(
+ sandbox_url="https://sandbox.example",
+ connect_token="connect-token",
+ )
+ ),
+ )
+ monkeypatch.setattr(workflow, "_relay_sandbox_events", AsyncMock())
+ monkeypatch.setattr(workflow, "_run_credential_refresh_until_sandbox_gone", AsyncMock())
+ monkeypatch.setattr(
+ workflow, "_wait_for_event", AsyncMock(return_value=process_task_workflow_module.TaskEvent.SANDBOX_GONE)
+ )
+ monkeypatch.setattr(process_task_workflow_module.workflow, "patched", Mock(return_value=True))
+
+ result = await workflow.run(ProcessTaskInput(run_id="run-id"))
+
+ assert result.success is True
+ assert workflow._completion_status == "completed"
+ update_task_run_status_mock.assert_any_await(
+ "completed",
+ error_message=SANDBOX_GONE_ERROR_MESSAGE,
+ )
+ cleanup_sandbox_mock.assert_awaited_once_with("sandbox-123")
+
@pytest.mark.parametrize(
"patched, expected_post_slack_calls",
[
diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.py
index 1060cacc6bd0..c41c4bba7c09 100644
--- a/products/tasks/backend/temporal/process_task/workflow.py
+++ b/products/tasks/backend/temporal/process_task/workflow.py
@@ -49,7 +49,7 @@ from .activities.send_followup_to_sandbox import SendFollowupToSandboxInput, sen
from .activities.start_agent_server import StartAgentServerInput, StartAgentServerOutput, start_agent_server
from .activities.track_workflow_event import TrackWorkflowEventInput, track_workflow_event
from .activities.update_task_run_status import UpdateTaskRunStatusInput, update_task_run_status
-from .credential_refresh import run_credential_refresh_loop
+from .credential_refresh import SANDBOX_GONE_ERROR_MESSAGE, CredentialRefreshExitReason, run_credential_refresh_loop
@dataclass
@@ -79,6 +79,7 @@ class TaskEvent(StrEnum):
SIGNAL_RECEIVED = "signal_received"
TIMEOUT_REACHED = "timeout_reached"
CI_FOLLOW_UP = "ci_follow_up"
+ SANDBOX_GONE = "sandbox_gone"
class CIFollowUpDecision(StrEnum):
@@ -151,6 +152,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):
self._heartbeat_received: bool = False
self._prewarmed: bool = False
self._first_user_message_received: bool = False
+ self._sandbox_gone: bool = False
self._pending_followup: PendingFollowup | None = None
self._pending_followups: list[PendingFollowup] = []
self._ci_repetitions: int = 0
@@ -211,11 +213,14 @@ class ProcessTaskWorkflow(PostHogWorkflow):
await workflow.wait_condition(
lambda: (
self._task_completed
+ or self._sandbox_gone
or self._heartbeat_received
or self._pending_followup is not None
or len(self._pending_followups) > 0
)
)
+ if self._sandbox_gone and not self._task_completed:
+ return TaskEvent.SANDBOX_GONE
return TaskEvent.SIGNAL_RECEIVED
async def _wait_for_inactivity(self, timeout: timedelta = INACTIVITY_TIMEOUT):
@@ -440,7 +445,9 @@ class ProcessTaskWorkflow(PostHogWorkflow):
)
if self.context.has_github_credentials:
- credential_refresh_task = asyncio.ensure_future(run_credential_refresh_loop(self.context, sandbox_id))
+ credential_refresh_task = asyncio.ensure_future(
+ self._run_credential_refresh_until_sandbox_gone(sandbox_id)
+ )
if self._should_forward_pending_user_message():
await self._forward_pending_user_message()
@@ -475,6 +482,8 @@ class ProcessTaskWorkflow(PostHogWorkflow):
self._last_active_time = workflow.now()
case _:
raise ValueError(f"Unknown CIFollowUpDecision: {follow_up_result}")
+ case TaskEvent.SANDBOX_GONE:
+ self._mark_sandbox_gone()
case TaskEvent.SIGNAL_RECEIVED:
pending_followup_count = len(self._pending_followups) + (
1 if self._pending_followup is not None else 0
@@ -869,6 +878,20 @@ class ProcessTaskWorkflow(PostHogWorkflow):
retry_policy=RetryPolicy(maximum_attempts=3),
)
+ async def _run_credential_refresh_until_sandbox_gone(self, sandbox_id: str) -> None:
+ exit_reason = await run_credential_refresh_loop(self.context, sandbox_id)
+ if exit_reason == CredentialRefreshExitReason.SANDBOX_GONE:
+ workflow.logger.warning(
+ "sandbox_gone_detected",
+ extra={"run_id": self.context.run_id, "sandbox_id": sandbox_id},
+ )
+ self._sandbox_gone = True
+
+ def _mark_sandbox_gone(self) -> None:
+ self._completion_status = "completed"
+ self._completion_error = SANDBOX_GONE_ERROR_MESSAGE
+ self._task_completed = True
+
async def _relay_sandbox_events(
self, agent_server_output: StartAgentServerOutput, sandbox_id: str | None = None
) -> None: