: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): preserve active work during sandbox snapshot rotation (#109870)
Alessandro Pogliaghi5ea4c0a517b7
diff --git a/docs/internal/sandboxes-setup-guide.md b/docs/internal/sandboxes-setup-guide.mdindex 0914a7c633ba..f8d052dae6e7 100644--- a/docs/internal/sandboxes-setup-guide.md+++ b/docs/internal/sandboxes-setup-guide.md@@ -120,6 +120,14 @@ completion signal arrived during delivery. This applies to user and peer messageAn open turn blocks sandbox rotation. If its sandbox disappears before completion,a workflow-origin run fails instead of reporting unfinished work as completed.+With `tasks-rotation-activity-guard`, active heartbeats also block rotation until+the agent reports idle, including background work after a user turn ends.+Activity during snapshot capture or replacement startup abandons the handoff and+keeps the live sandbox. The event relay stays active until startup finishes, and+an abandoned handoff with new activity requests a fresh snapshot.+Directory resume snapshots cover `/tmp/workspace`, including nested Git worktrees+and agent state. Paths outside that directory are not included.+## Running via the UIThis is very minimal at the moment, but the tasks page can be used to see whatdiff --git a/products/tasks/backend/temporal/process_task/tests/test_workflow.py b/products/tasks/backend/temporal/process_task/tests/test_workflow.pyindex ef38157a40a1..4a25226b6f8d 100644--- a/products/tasks/backend/temporal/process_task/tests/test_workflow.py+++ b/products/tasks/backend/temporal/process_task/tests/test_workflow.py@@ -605,6 +605,7 @@ class TestSandboxRotation:wf = ProcessTaskWorkflow()wf._context = _build_context(github_integration_id=123, state={"mode": "interactive"})wf._context.sandbox_rotation_enabled = overrides.get("rotation_enabled", True)+ wf._sandbox_rotation_idle = Truewf._agent_active = overrides.get("agent_active", False)wf._end_of_turn_received = overrides["end_of_turn_received"]wf._task_completed = overrides.get("task_completed", False)@@ -619,6 +620,7 @@ class TestSandboxRotation:wf = ProcessTaskWorkflow()wf._context = _build_context(github_integration_id=123, state={"mode": "interactive"})wf._context.sandbox_rotation_enabled = True+ wf._sandbox_rotation_idle = Truewf._agent_active = Nonewf._end_of_turn_received = Falsemonkeypatch.setattr(process_task_workflow_module.workflow, "in_workflow", Mock(return_value=True))@@ -626,7 +628,65 @@ class TestSandboxRotation:monkeypatch.setattr(process_task_workflow_module.workflow, "patched", patched)assert wf._sandbox_rotation_block_reason() is None- patched.assert_called_once_with("tasks-block-rotation-on-open-turn")+ assert patched.call_args_list == [+ call("tasks-block-rotation-on-open-turn"),+ call("tasks-rotation-activity-guard"),+ ]++ @pytest.mark.parametrize("patched", [True, False])+ async def test_background_heartbeats_block_rotation_without_reopening_the_user_turn(+ self, monkeypatch: pytest.MonkeyPatch, patched: bool+ ) -> None:+ wf = self._workflow(monkeypatch)+ monkeypatch.setattr(process_task_workflow_module.workflow, "now", Mock(return_value=datetime.now(UTC)))+ monkeypatch.setattr(process_task_workflow_module.workflow, "in_workflow", Mock(return_value=True))+ monkeypatch.setattr(process_task_workflow_module.workflow, "patched", Mock(return_value=patched))++ await wf.agent_state_changed(False)+ assert wf._sandbox_rotation_block_reason() is None++ await wf.heartbeat(agent_active=True)++ assert wf._end_of_turn_received is True+ assert wf._agent_active is False+ assert wf._sandbox_rotation_block_reason() == ("agent_activity" if patched else None)++ await wf.agent_state_changed(False)+ assert wf._sandbox_rotation_block_reason() is None++ @pytest.mark.parametrize("signal", ["heartbeat", "agent_state_changed"])+ @pytest.mark.parametrize("finishes_before_snapshot", [True, False])+ async def test_activity_during_snapshot_preserves_the_live_sandbox(+ self, monkeypatch: pytest.MonkeyPatch, signal: str, finishes_before_snapshot: bool+ ) -> None:+ wf = self._workflow(monkeypatch)+ monkeypatch.setattr(process_task_workflow_module.workflow, "now", Mock(return_value=datetime.now(UTC)))+ await wf.agent_state_changed(False)++ async def snapshot_activity(+ activity_fn: object, _input: object, **_kwargs: object+ ) -> CreateResumeSnapshotOutput:+ assert activity_fn is process_task_workflow_module.create_resume_snapshot+ await getattr(wf, signal)(True)+ if finishes_before_snapshot:+ await wf.agent_state_changed(False)+ return self._snapshot()++ execute_activity = AsyncMock(side_effect=snapshot_activity)+ monkeypatch.setattr(process_task_workflow_module.workflow, "execute_activity", execute_activity)+ relay = self._relay("relay-old")+ refresh = self._relay("refresh-old")++ rotation = await wf._rotate_sandbox_before_deadline("sb-old", relay, refresh)++ assert rotation.sandbox_id is None+ assert rotation.reason == "activity_during_snapshot"+ assert rotation.snapshot_saved is False+ assert rotation.relay_task is relay+ assert rotation.credential_refresh_task is refresh+ assert wf._sandbox_id_for_cleanup == "sb-old"+ assert wf._sandbox_url == "https://old.example"+ execute_activity.assert_awaited_once()async def test_the_credential_refresh_loop_follows_the_run_to_the_new_sandbox(self, monkeypatch):wf = self._workflow(monkeypatch)@@ -886,16 +946,76 @@ class TestSandboxRotation:assert rotation.credential_refresh_task is refresh_oldprovision.assert_not_awaited()- async def test_a_failed_replacement_restores_the_old_sandbox_and_its_relay(self, monkeypatch):+ @pytest.mark.parametrize(+ "reason, phase, event_ingest",+ [+ ("provision_failed", "provision", False),+ ("activity_during_handoff", "provision", False),+ ("activity_during_handoff", "startup", False),+ ("activity_during_handoff", "relay_shutdown", False),+ ("activity_during_handoff", "provision", True),+ ("provision_failed", "startup", False),+ ],+ )+ async def test_an_abandoned_replacement_restores_the_old_sandbox_and_its_relay(+ self, monkeypatch: pytest.MonkeyPatch, reason: str, phase: str, event_ingest: bool+ ) -> None:wf = self._workflow(monkeypatch)+ monkeypatch.setattr(process_task_workflow_module.workflow, "now", Mock(return_value=datetime.now(UTC)))monkeypatch.setattr(wf, "_create_resume_snapshot_output", AsyncMock(return_value=self._snapshot()))+ activity_started = asyncio.Event()+ activity_observed = asyncio.Event()+ relay_ready = asyncio.Event()- async def fail_after_creating() -> GetSandboxForRepositoryOutput:+ async def report_activity() -> None:+ await wf.heartbeat(True)+ await wf.agent_state_changed(False)++ async def relay_activity() -> None:+ relay_ready.set()+ try:+ await activity_started.wait()+ await report_activity()+ activity_observed.set()+ await asyncio.Future[None]()+ finally:+ if phase == "relay_shutdown":+ await report_activity()++ async def refresh_credentials() -> None:+ await asyncio.Event().wait()++ relay_old = None if event_ingest else asyncio.create_task(relay_activity())+ refresh_old = asyncio.create_task(refresh_credentials())++ async def resume_activity() -> None:+ if event_ingest:+ await report_activity()+ else:+ assert relay_old is not None and not relay_old.done()+ activity_started.set()+ await asyncio.wait_for(activity_observed.wait(), timeout=1)++ async def provision() -> GetSandboxForRepositoryOutput:wf._sandbox_id_for_cleanup = "sb-half-built"- raise RuntimeError("agent server never came up")+ wf._sandbox_jwt_kid = "kid-half-built"+ if reason == "provision_failed" and phase == "provision":+ raise RuntimeError("agent server never came up")+ if phase == "provision":+ await resume_activity()+ return self._replacement()- monkeypatch.setattr(wf, "_get_sandbox_for_repository", fail_after_creating)- monkeypatch.setattr(wf, "_cancel_relay", AsyncMock())+ async def start(_output: GetSandboxForRepositoryOutput) -> None:+ if relay_old is not None:+ assert not relay_old.done()+ await relay_ready.wait()+ if phase == "startup":+ await resume_activity()+ if reason == "provision_failed":+ raise RuntimeError("agent server never came up")++ monkeypatch.setattr(wf, "_get_sandbox_for_repository", provision)+ monkeypatch.setattr(wf, "_start_agent_server", start)cleanup = AsyncMock()monkeypatch.setattr(wf, "_cleanup_sandbox", cleanup)relay_restarted = self._relay("relay-restarted")@@ -904,15 +1024,24 @@ class TestSandboxRotation:restore = AsyncMock(return_value=True)monkeypatch.setattr(wf, "_restore_sandbox_connection_state", restore)- rotation = await wf._rotate_sandbox_before_deadline(- "sb-old", self._relay("relay-old"), self._relay("refresh-old")- )+ try:+ rotation = await wf._rotate_sandbox_before_deadline("sb-old", relay_old, refresh_old)+ finally:+ for task in (relay_old, refresh_old):+ if task is not None and not task.done():+ task.cancel()+ await asyncio.gather(+ *(task for task in (relay_old, refresh_old) if task is not None), return_exceptions=True+ )assert rotation.sandbox_id is None+ assert rotation.reason == reason+ assert rotation.snapshot_saved is (reason == "provision_failed" and phase == "provision")assert rotation.relay_task is relay_restartedassert rotation.routing_restored is Trueassert wf._sandbox_id_for_cleanup == "sb-old"assert (wf._sandbox_url, wf._sandbox_connect_token) == ("https://old.example", "old-token")+ assert wf._sandbox_jwt_kid == "kid-old"cleanup.assert_awaited_once_with("sb-half-built", complete_stream=False)restore.assert_awaited_once_with("sb-old", "https://old.example", "old-token", "kid-old")@@ -3668,6 +3797,7 @@ class TestContinueAsNew:wf._agent_active = Falsewf._end_of_turn_received = Truewf._last_agent_heartbeat_at = datetime(2026, 7, 16, 10, 29, tzinfo=UTC)+ wf._sandbox_rotation_idle = Truewf._sandbox_ttl_expires_at = datetime(2026, 7, 16, 15, 0, tzinfo=UTC)wf._first_command_dispatched_recorded = Truewf._first_agent_activity_recorded = True@@ -3704,6 +3834,7 @@ class TestContinueAsNew:assert restored._last_active_time == datetime(2026, 7, 16, 10, 30, tzinfo=UTC)assert restored._agent_active is Falseassert restored._end_of_turn_received is True+ assert restored._sandbox_rotation_idle is Trueassert restored._last_agent_heartbeat_at == datetime(2026, 7, 16, 10, 29, tzinfo=UTC)assert restored._sandbox_ttl_expires_at == datetime(2026, 7, 16, 15, 0, tzinfo=UTC)assert restored._first_command_dispatched_recorded is Truediff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.pyindex ce1a501b485d..7f94cae31cb7 100644--- a/products/tasks/backend/temporal/process_task/workflow.py+++ b/products/tasks/backend/temporal/process_task/workflow.py@@ -216,6 +216,7 @@ class ResumedSandboxState:last_agent_heartbeat_at: Optional[str] = Nonesandbox_ttl_expires_at: Optional[str] = Nonesandbox_ttl_snapshot_taken: bool = False+ sandbox_rotation_idle: bool = Falsefirst_command_dispatched_recorded: bool = Falsefirst_agent_activity_recorded: bool = Falseboot_path: str | None = None@@ -441,6 +442,8 @@ _PATCH_ID_BLOCK_ROTATION_ON_OPEN_TURN = "tasks-block-rotation-on-open-turn"# already recorded the post-delivery reset must retain it during replay._PATCH_ID_PRESERVE_COMPLETION_DURING_DELIVERY = "tasks-preserve-completion-during-delivery"+_PATCH_ID_ROTATION_ACTIVITY_GUARD = "tasks-rotation-activity-guard"+def _turn_opens_on_dispatch() -> bool:if not workflow.in_workflow():@@ -460,6 +463,12 @@ def _preserve_completion_during_delivery() -> bool:return workflow.patched(_PATCH_ID_PRESERVE_COMPLETION_DURING_DELIVERY)+def _rotation_activity_guard() -> bool:+ if not workflow.in_workflow():+ return True+ return workflow.patched(_PATCH_ID_ROTATION_ACTIVITY_GUARD)++# Keeps an interactive run alive when follow-up delivery exhausts retries, releasing# the message's dedupe key so a retry can land; background runs keep the fail-fast# terminalization poll_for_turn callers rely on. Same cleanup lifecycle as above.@@ -546,6 +555,8 @@ class ProcessTaskWorkflow(PostHogWorkflow):self._turn_ended_received = Falseself._turn_completion_signal_count = 0self._last_agent_heartbeat_at: Optional[datetime] = None+ self._sandbox_rotation_idle = False+ self._sandbox_activity_count = 0self._prewarmed: bool = Falseself._first_user_message_received: bool = Falseself._sandbox_gone: bool = False@@ -870,6 +881,8 @@ class ProcessTaskWorkflow(PostHogWorkflow):return "followup_in_flight"if self._task_completed:return "run_completed"+ if _rotation_activity_guard() and not self._sandbox_rotation_idle:+ return "agent_activity"return Noneasync def _wait_for_sandbox_deadline(self) -> TaskEvent:@@ -2031,6 +2044,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):self._sandbox_ttl_expires_at.isoformat() if self._sandbox_ttl_expires_at else None),sandbox_ttl_snapshot_taken=self._sandbox_ttl_snapshot_taken,+ sandbox_rotation_idle=self._sandbox_rotation_idle,first_command_dispatched_recorded=self._first_command_dispatched_recorded,first_agent_activity_recorded=self._first_agent_activity_recorded,boot_path=self._boot_path,@@ -2051,6 +2065,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):return self._chain_started_at or workflow.info().start_timedef _restore_resumed_state(self, resumed: ResumedSandboxState) -> None:+ self._sandbox_rotation_idle = resumed.sandbox_rotation_idleself._chain_started_at = datetime.fromisoformat(resumed.chain_started_at) if resumed.chain_started_at else Noneself._is_agent_design_enabled = resumed.is_agent_design_enabledself._dev_stack_preview_enabled = resumed.dev_stack_preview_enabled@@ -3076,12 +3091,21 @@ class ProcessTaskWorkflow(PostHogWorkflow):stream fed."""self._resume_snapshot_invalidated = False+ activity_count = self._sandbox_activity_count+ guard_activity = _rotation_activity_guard()snapshot = await self._create_resume_snapshot_output(old_sandbox_id, reason="ttl_rotation", allow_pruning=False)if snapshot is None or not snapshot.external_id:return SandboxRotation(relay_task=relay_task, credential_refresh_task=credential_refresh_task, reason="snapshot_missing")+ if guard_activity and self._sandbox_activity_count != activity_count:+ return SandboxRotation(+ relay_task=relay_task,+ credential_refresh_task=credential_refresh_task,+ reason="activity_during_snapshot",+ )+self.context.state = {**(self.context.state or {}),"snapshot_external_id": snapshot.external_id,@@ -3099,7 +3123,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):ttl_snapshot_taken=self._sandbox_ttl_snapshot_taken,)- if relay_task is not None:+ if relay_task is not None and not guard_activity:await self._cancel_relay(relay_task)relay_task = Noneif credential_refresh_task is not None:@@ -3107,8 +3131,13 @@ class ProcessTaskWorkflow(PostHogWorkflow):credential_refresh_task = Nonetry:- sandbox_output = await self._get_sandbox_for_repository()- await self._start_agent_server(sandbox_output)+ try:+ sandbox_output = await self._get_sandbox_for_repository()+ await self._start_agent_server(sandbox_output)+ finally:+ if relay_task is not None:+ await self._cancel_relay(relay_task)+ relay_task = Noneexcept Exception as e:workflow.logger.warning("sandbox_rotation_failed",@@ -3119,7 +3148,11 @@ class ProcessTaskWorkflow(PostHogWorkflow):**self._activity_error_properties(e),},)- return await self._abandon_rotation(live_sandbox, reason="provision_failed")+ return await self._abandon_rotation(+ live_sandbox,+ reason="provision_failed",+ snapshot_activity_count=activity_count if guard_activity else None,+ )if not sandbox_output.used_snapshot:# Provisioning reports success for a replacement it had to build without the@@ -3135,7 +3168,16 @@ class ProcessTaskWorkflow(PostHogWorkflow):"replacement_sandbox_id": sandbox_output.sandbox_id,},)- return await self._abandon_rotation(live_sandbox, reason="snapshot_unused")+ return await self._abandon_rotation(+ live_sandbox,+ reason="snapshot_unused",+ snapshot_activity_count=activity_count if guard_activity else None,+ )++ if guard_activity and self._sandbox_activity_count != activity_count:+ return await self._abandon_rotation(+ live_sandbox, reason="activity_during_handoff", snapshot_activity_count=activity_count+ )self._sandbox_url = sandbox_output.sandbox_urlself._sandbox_connect_token = sandbox_output.connect_token@@ -3162,7 +3204,9 @@ class ProcessTaskWorkflow(PostHogWorkflow):snapshot_saved=True,)- async def _abandon_rotation(self, live: PreRotationSandbox, *, reason: str) -> SandboxRotation:+ async def _abandon_rotation(+ self, live: PreRotationSandbox, *, reason: str, snapshot_activity_count: int | None = None+ ) -> SandboxRotation:"""Back out of a rotation and put the run back on the sandbox it already had.Provisioning publishes the replacement's connection details as soon as that sandbox@@ -3188,7 +3232,8 @@ class ProcessTaskWorkflow(PostHogWorkflow):relay_task=relay_task,credential_refresh_task=self._spawn_credential_refresh(live.sandbox_id),routing_restored=routing_restored,- snapshot_saved=not self._resume_snapshot_invalidated,+ snapshot_saved=not self._resume_snapshot_invalidated+ and (snapshot_activity_count is None or self._sandbox_activity_count == snapshot_activity_count),reason=reason,)@@ -3574,6 +3619,8 @@ class ProcessTaskWorkflow(PostHogWorkflow):self._heartbeat_received = Trueself._last_active_time = nowself._last_agent_heartbeat_at = now+ self._sandbox_rotation_idle = False+ self._sandbox_activity_count += 1@temporalio.workflow.signalasync def client_activity(self) -> None:@@ -3582,6 +3629,9 @@ class ProcessTaskWorkflow(PostHogWorkflow):@temporalio.workflow.signalasync def agent_state_changed(self, agent_active: bool) -> None:+ self._sandbox_rotation_idle = not agent_active+ if agent_active:+ self._sandbox_activity_count += 1self._agent_active = agent_activeself._end_of_turn_received = not agent_activeself._last_turn_succeeded = False