: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
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.pyindex 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 CredentialRefreshExitReasondef _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.pyindex 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_staUpdateTaskRunStatusInput,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 = Falseself._completion_status: str = "completed"self._completion_error: Optional[str] = None+ self._sandbox_gone: bool = Falseself._heartbeat_received: bool = Falseself._pending_followups: list[PendingFollowup] = []@@ -319,11 +324,14 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):await workflow.wait_condition(lambda: (self._task_completed+ or self._sandbox_goneor self._heartbeat_receivedor len(self._pending_followups) > 0or len(self._pending_outbound) > 0))+ if self._sandbox_gone and not self._task_completed:+ return SandboxEvent.SANDBOX_GONEreturn SandboxEvent.SIGNAL_RECEIVEDasync 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 = Truebreak+ 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.pyindex 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 StrEnumfrom temporalio import workflowfrom temporalio.common import RetryPolicy@@ -9,7 +10,14 @@ from .activities.get_task_processing_context import TaskProcessingContextfrom .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_GONEnext_refresh_seconds = result.next_refresh_secondsexcept 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.pyindex 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 Truerelay_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.pyindex 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, senfrom .activities.start_agent_server import StartAgentServerInput, StartAgentServerOutput, start_agent_serverfrom .activities.track_workflow_event import TrackWorkflowEventInput, track_workflow_eventfrom .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 = Falseself._prewarmed: bool = Falseself._first_user_message_received: bool = False+ self._sandbox_gone: bool = Falseself._pending_followup: PendingFollowup | None = Noneself._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_goneor self._heartbeat_receivedor self._pending_followup is not Noneor len(self._pending_followups) > 0))+ if self._sandbox_gone and not self._task_completed:+ return TaskEvent.SANDBOX_GONEreturn TaskEvent.SIGNAL_RECEIVEDasync 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: