: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): block sandbox rotation while a turn is open (#109664)
Charles Vien7c3c96e6a1d3
diff --git a/docs/internal/sandboxes-setup-guide.md b/docs/internal/sandboxes-setup-guide.mdindex 8861f3b35a87..0914a7c633ba 100644--- a/docs/internal/sandboxes-setup-guide.md+++ b/docs/internal/sandboxes-setup-guide.md@@ -115,6 +115,11 @@ The activities live inCredential refresh runs in the background. For workflow histories with the `tasks-credential-refresh-propagate-cancel` patch, cancellation stops the loop even during an in-flight refresh activity.Other refresh failures retry on the default cadence.+A follow-up command read timeout leaves its turn open, even if an earlier turn's+completion signal arrived during delivery. This applies to user and peer messages.+An open turn blocks sandbox rotation. If its sandbox disappears before completion,+a workflow-origin run fails instead of reporting unfinished work as completed.+## 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/metrics.py b/products/tasks/backend/metrics.pyindex af68e3de63e2..a5b0fe02cff8 100644--- a/products/tasks/backend/metrics.py+++ b/products/tasks/backend/metrics.py@@ -749,6 +749,7 @@ _SANDBOX_DEADLINE_REASONS = {"no_sandbox","flag_disabled","agent_active",+ "turn_open","followup_in_flight","run_completed","snapshot_missing",diff --git a/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.py b/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.pyindex 78a9dfacbb27..7c500a158f4d 100644--- a/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.py+++ b/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.py@@ -100,6 +100,7 @@ SEND_FOLLOWUP_MAX_ATTEMPTS = 3# 1-minute timeout both callers set gives a 15-second interval.SEND_FOLLOWUP_HEARTBEAT_FACTOR = 4STEER_DECLINED_OUTCOME = "steer_declined"+TURN_IN_FLIGHT_OUTCOME = "turn_in_flight"STEER_DECLINE_REASON_UNREPORTED = "unreported"STEER_DECLINE_REASON_ACTOR_MISMATCH = "actor_mismatch"@@ -501,6 +502,7 @@ def _deliver_followup(input: SendFollowupToSandboxInput) -> str | None:run_id=input.run_id,timeout_seconds=FOLLOWUP_TIMEOUT_SECONDS,)+ return TURN_IN_FLIGHT_OUTCOMEelif result.retryable and input.message_id:if _is_denied_permission_stop(input.run_id, result.error, steer=input.steer):observe_followup_denied_permission_stop(task_run)@@ -695,7 +697,7 @@ def _deliver_peer_message(input: SendFollowupToSandboxInput, task_run: TaskRun,# The read timeout means the message reached the sandbox and the turn is# simply still running (see the user path for why this is not a failure)._mark_peer_delivery_outcome(peer_message_id, AgentPeerMessage.Outcome.DELIVERED)- return None+ return TURN_IN_FLIGHT_OUTCOMEif result.retryable and input.message_id and _current_attempt() < input.max_attempts:# Row stays signaled; a retried delivery is deduped by message_id and the# final attempt terminalizes below.diff --git a/products/tasks/backend/temporal/process_task/tests/test_send_followup_to_sandbox.py b/products/tasks/backend/temporal/process_task/tests/test_send_followup_to_sandbox.pyindex f5aafa7541ee..6ef2e74b8165 100644--- a/products/tasks/backend/temporal/process_task/tests/test_send_followup_to_sandbox.py+++ b/products/tasks/backend/temporal/process_task/tests/test_send_followup_to_sandbox.py@@ -16,6 +16,7 @@ from products.tasks.backend.temporal.process_task.activities.send_followup_to_saSANDBOX_STOPPED_MESSAGE,SEND_FOLLOWUP_MAX_ATTEMPTS,STEER_DECLINED_OUTCOME,+ TURN_IN_FLIGHT_OUTCOME,LiveSandboxLookup,SandboxRebindFailure,SendFollowupToSandboxInput,@@ -966,8 +967,9 @@ class TestSendFollowupTurnTimeout:success=False, status_code=504, error="Sandbox request timed out", retryable=True, turn_in_flight=True)- _run_activity(SendFollowupToSandboxInput(run_id="run-1", message="hi"))+ outcome = _run_activity(SendFollowupToSandboxInput(run_id="run-1", message="hi"))+ assert outcome == TURN_IN_FLIGHT_OUTCOME_patches["error"].assert_not_called()_patches["turn_complete"].assert_not_called()@@ -1405,20 +1407,29 @@ class TestPeerDeliveryMode:assert _patches["mark"].call_args.args == (self._PEER_ID, "delivery_failed")assert _patches["mark"].call_args.kwargs["failure_phase"] == "sandbox_delivery"- def test_duplicate_delivery_marks_row_delivered_without_turn_complete(self, _patches):- # duplicate:true means a prior attempt already delivered this message_id,- # so the audit outcome is delivered; that attempt owns the turn bookkeeping.+ @pytest.mark.parametrize(+ "result, expected_outcome",+ [+ (CommandResult(success=True, status_code=200, data={"result": {"duplicate": True}}), None),+ (+ CommandResult(success=False, status_code=504, turn_in_flight=True),+ TURN_IN_FLIGHT_OUTCOME,+ ),+ ],+ )+ def test_accepted_delivery_marks_row_delivered_without_turn_complete(+ self, _patches, result: CommandResult, expected_outcome: str | None+ ) -> None:_patches["bound_actor"].return_value = (MagicMock(id=42, distinct_id="u42"), "")- _patches["user_msg"].return_value = CommandResult(- success=True, status_code=200, data={"result": {"duplicate": True}}- )+ _patches["user_msg"].return_value = result- _run_activity(+ outcome = _run_activity(SendFollowupToSandboxInput(run_id="run-1", message="peer ping", message_id="m-1", context=self._peer_context()))+ assert outcome == expected_outcomeassert _patches["mark"].call_args.args == (self._PEER_ID, "delivered")_patches["turn_complete"].assert_not_called()diff --git a/products/tasks/backend/temporal/process_task/tests/test_workflow.py b/products/tasks/backend/temporal/process_task/tests/test_workflow.pyindex 36198eb271af..cb0e57678859 100644--- a/products/tasks/backend/temporal/process_task/tests/test_workflow.py+++ b/products/tasks/backend/temporal/process_task/tests/test_workflow.py@@ -80,7 +80,10 @@ from products.tasks.backend.temporal.process_task.activities.refresh_sandbox_creRefreshSandboxCredentialsOutput,refresh_sandbox_credentials,)-from products.tasks.backend.temporal.process_task.activities.send_followup_to_sandbox import SendFollowupToSandboxInput+from products.tasks.backend.temporal.process_task.activities.send_followup_to_sandbox import (+ TURN_IN_FLIGHT_OUTCOME,+ SendFollowupToSandboxInput,+)from products.tasks.backend.temporal.process_task.activities.update_task_run_status import (SANDBOX_GONE_STATE_KEY,TIMED_OUT_WALL_CLOCK_STATE_KEY,@@ -584,12 +587,18 @@ class TestSandboxRotation:@parameterized.expand([- ("idle_with_flag_on", {}, True),- ("flag_off", {"rotation_enabled": False}, False),- ("agent_mid_turn", {"agent_active": True}, False),- ("run_finishing", {"task_completed": True}, False),- ("followup_in_flight", {"followup_running": True}, False),- ("followup_finished", {"followup_running": False, "followup_present": True}, True),+ ("idle_with_flag_on", {"end_of_turn_received": True}, True),+ ("flag_off", {"rotation_enabled": False, "end_of_turn_received": True}, False),+ ("agent_mid_turn", {"agent_active": True, "end_of_turn_received": False}, False),+ ("turn_open_after_followup_reset", {"agent_active": None, "end_of_turn_received": False}, False),+ ("turn_closed", {"agent_active": False, "end_of_turn_received": True}, True),+ ("run_finishing", {"task_completed": True, "end_of_turn_received": True}, False),+ ("followup_in_flight", {"followup_running": True, "end_of_turn_received": True}, False),+ (+ "followup_finished",+ {"followup_running": False, "followup_present": True, "end_of_turn_received": True},+ True,+ ),])def test_only_an_idle_run_with_the_flag_on_may_rotate(self, _name, overrides, expected):@@ -597,6 +606,7 @@ class TestSandboxRotation:wf._context = _build_context(github_integration_id=123, state={"mode": "interactive"})wf._context.sandbox_rotation_enabled = overrides.get("rotation_enabled", True)wf._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)if overrides.get("followup_running") or overrides.get("followup_present"):followup = Mock()@@ -605,6 +615,19 @@ class TestSandboxRotation:assert (wf._sandbox_rotation_block_reason() is None) is expected+ def test_open_turn_guard_preserves_pre_patch_rotation(self, monkeypatch):+ wf = ProcessTaskWorkflow()+ wf._context = _build_context(github_integration_id=123, state={"mode": "interactive"})+ wf._context.sandbox_rotation_enabled = True+ wf._agent_active = None+ wf._end_of_turn_received = False+ monkeypatch.setattr(process_task_workflow_module.workflow, "in_workflow", Mock(return_value=True))+ patched = Mock(return_value=False)+ 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")+async def test_the_credential_refresh_loop_follows_the_run_to_the_new_sandbox(self, monkeypatch):wf = self._workflow(monkeypatch)monkeypatch.setattr(wf, "_create_resume_snapshot_output", AsyncMock(return_value=self._snapshot()))@@ -1897,6 +1920,77 @@ class TestProcessTaskWorkflowUnit:assert workflow._end_of_turn_received is expectedassert workflow._agent_active is (None if outcome is None else False)+ @pytest.mark.parametrize(+ "outcome, completes_after_delivery, expected_status",+ [+ (None, False, "completed"),+ (TURN_IN_FLIGHT_OUTCOME, False, "failed"),+ (TURN_IN_FLIGHT_OUTCOME, True, "completed"),+ ],+ )+ async def test_followup_delivery_distinguishes_an_open_turn_from_an_earlier_completion(+ self,+ monkeypatch: pytest.MonkeyPatch,+ outcome: str | None,+ completes_after_delivery: bool,+ expected_status: str,+ ) -> None:+ workflow = ProcessTaskWorkflow()+ workflow._context = _build_context(github_integration_id=123, origin_product="workflow")+ workflow._context.sandbox_rotation_enabled = True+ workflow._end_of_turn_received = True+ workflow._agent_active = False++ async def deliver_after_turn_completes(*_args: object, **_kwargs: object) -> str | None:+ await workflow.agent_state_changed(False)+ await workflow.agent_turn_completed(True)+ await workflow.heartbeat(True)+ return outcome++ monkeypatch.setattr(process_task_workflow_module.workflow, "logger", Mock())+ monkeypatch.setattr(process_task_workflow_module.workflow, "patched", Mock(return_value=True))+ monkeypatch.setattr(process_task_workflow_module.workflow, "uuid4", Mock(return_value="uuid"))+ monkeypatch.setattr(process_task_workflow_module.workflow, "now", Mock(return_value=datetime.now(UTC)))+ monkeypatch.setattr(process_task_workflow_module.workflow, "execute_activity", deliver_after_turn_completes)++ await workflow._send_followup_to_sandbox("go", [])++ if outcome == TURN_IN_FLIGHT_OUTCOME:+ assert workflow._sandbox_rotation_block_reason() == "turn_open"+ if completes_after_delivery:+ await workflow.agent_state_changed(False)+ await workflow.agent_turn_completed(True)++ await workflow._mark_sandbox_gone()++ assert workflow._completion_status == expected_status+ assert workflow._end_of_turn_received is (expected_status == "completed")+ assert workflow._agent_active is (False if expected_status == "completed" else None)++ async def test_followup_delivery_preserves_the_pre_patch_turn_reset(self, monkeypatch):+ workflow = ProcessTaskWorkflow()+ workflow._context = _build_context(github_integration_id=123)+ workflow._end_of_turn_received = True+ workflow._agent_active = False++ async def deliver_after_turn_completes(*_args, **_kwargs):+ await workflow.agent_state_changed(False)+ return None++ def patched(patch_id: str) -> bool:+ return patch_id == process_task_workflow_module._PATCH_ID_TURN_OPENS_ON_DISPATCH++ monkeypatch.setattr(process_task_workflow_module.workflow, "in_workflow", Mock(return_value=True))+ monkeypatch.setattr(process_task_workflow_module.workflow, "patched", patched)+ monkeypatch.setattr(process_task_workflow_module.workflow, "logger", Mock())+ monkeypatch.setattr(process_task_workflow_module.workflow, "uuid4", Mock(return_value="uuid"))+ monkeypatch.setattr(process_task_workflow_module.workflow, "execute_activity", deliver_after_turn_completes)++ await workflow._send_followup_to_sandbox("go", [])++ assert workflow._end_of_turn_received is False+ assert workflow._agent_active is None+async def test_credential_refresh_exit_marks_sandbox_gone(self, monkeypatch):workflow = ProcessTaskWorkflow()workflow._context = _build_context(github_integration_id=123)diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.pyindex a025a98e1726..e95e9fbf7bd8 100644--- a/products/tasks/backend/temporal/process_task/workflow.py+++ b/products/tasks/backend/temporal/process_task/workflow.py@@ -110,6 +110,7 @@ from .activities.run_wizard import RunWizardInput, run_wizardfrom .activities.send_followup_to_sandbox import (SEND_FOLLOWUP_MAX_ATTEMPTS,STEER_DECLINED_OUTCOME,+ TURN_IN_FLIGHT_OUTCOME,SendFollowupToSandboxInput,send_followup_to_sandbox,)@@ -432,6 +433,14 @@ AGENT_LOST_ERROR_MESSAGE = "The agent stopped before finishing its turn"# Replays of pre-rollout histories must keep recording an idle exit as completed._PATCH_ID_TURN_OPENS_ON_DISPATCH = "tasks-turn-opens-on-dispatch"+# Changing the deadline branch changes the activities it schedules, so pre-rollout histories+# must retain the old rotation decision when replayed.+_PATCH_ID_BLOCK_ROTATION_ON_OPEN_TURN = "tasks-block-rotation-on-open-turn"++# Preserving a completion signal can enable later command-producing branches, so histories that+# already recorded the post-delivery reset must retain it during replay.+_PATCH_ID_PRESERVE_COMPLETION_DURING_DELIVERY = "tasks-preserve-completion-during-delivery"+def _turn_opens_on_dispatch() -> bool:if not workflow.in_workflow():@@ -439,6 +448,18 @@ def _turn_opens_on_dispatch() -> bool:return workflow.patched(_PATCH_ID_TURN_OPENS_ON_DISPATCH)+def _block_rotation_on_open_turn() -> bool:+ if not workflow.in_workflow():+ return True+ return workflow.patched(_PATCH_ID_BLOCK_ROTATION_ON_OPEN_TURN)+++def _preserve_completion_during_delivery() -> bool:+ if not workflow.in_workflow():+ return True+ return workflow.patched(_PATCH_ID_PRESERVE_COMPLETION_DURING_DELIVERY)++# 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.@@ -523,6 +544,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):self._end_of_turn_received: Optional[bool] = Noneself._last_turn_succeeded = Falseself._turn_ended_received = False+ self._turn_completion_signal_count = 0self._last_agent_heartbeat_at: Optional[datetime] = Noneself._prewarmed: bool = Falseself._first_user_message_received: bool = False@@ -830,6 +852,11 @@ class ProcessTaskWorkflow(PostHogWorkflow):not yet produced an active-state signal counts as in flight too, which is why thefollow-up task is checked alongside the agent's own state.+ An open turn blocks rotation even when `_agent_active` is None. A delivered follow-up+ resets `_agent_active` to None, and the relay only re-signals active on its own+ False-to-True transition, so a follow-up delivered while the agent already works+ leaves `_agent_active` at None for the rest of that turn.+The reason is what tells a rollout whether rotation is idle-gated out of the runs thatneed it most, so it is a metric label rather than a log line."""@@ -837,6 +864,8 @@ class ProcessTaskWorkflow(PostHogWorkflow):return "flag_disabled"if self._agent_active:return "agent_active"+ if self._end_of_turn_received is False and _block_rotation_on_open_turn():+ return "turn_open"if self._active_followup_task is not None and not self._active_followup_task.done():return "followup_in_flight"if self._task_completed:@@ -3553,8 +3582,10 @@ class ProcessTaskWorkflow(PostHogWorkflow):self._agent_active = agent_activeself._end_of_turn_received = not agent_activeself._last_turn_succeeded = False- if not agent_active and _turn_opens_on_dispatch():- self._turn_ended_received = True+ if not agent_active:+ self._turn_completion_signal_count += 1+ if _turn_opens_on_dispatch():+ self._turn_ended_received = True@temporalio.workflow.signalasync def agent_turn_completed(self, succeeded: bool = False) -> None:@@ -3736,6 +3767,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):)try:max_attempts = 1 if self.context.task_runtime == "pi" else SEND_FOLLOWUP_MAX_ATTEMPTS+ turn_completion_count = self._turn_completion_signal_countoutcome = await workflow.execute_activity(send_followup_to_sandbox,SendFollowupToSandboxInput(@@ -3757,12 +3789,18 @@ class ProcessTaskWorkflow(PostHogWorkflow):),)# A delivered message opens a turn: the first heartbeat may lag or be throttled away.- if outcome != STEER_DECLINED_OUTCOME and _turn_opens_on_dispatch():- self._end_of_turn_received = False- # The ingest plane never reports a turn active, only inactive at its close, so a- # stale `False` from the turn that just ended must not carry into this one — it- # would permanently hide a lost agent for every later turn of the run.- self._agent_active = None+ if outcome != STEER_DECLINED_OUTCOME:+ turn_opens_on_dispatch = _turn_opens_on_dispatch()+ preserve_completion = _preserve_completion_during_delivery()+ completion_arrived = self._turn_completion_signal_count != turn_completion_count+ if turn_opens_on_dispatch and (+ outcome == TURN_IN_FLIGHT_OUTCOME or not completion_arrived or not preserve_completion+ ):+ self._end_of_turn_received = False+ # The ingest plane never reports a turn active, only inactive at its close, so a+ # stale `False` from the turn that just ended must not carry into this one — it+ # would permanently hide a lost agent for every later turn of the run.+ self._agent_active = Nonereturn outcomeexcept Exception as e:error_properties = self._activity_error_properties(e)diff --git a/products/tasks/backend/tests/test_task_run_metrics.py b/products/tasks/backend/tests/test_task_run_metrics.pyindex edb7a684a50d..a32e153d47e8 100644--- a/products/tasks/backend/tests/test_task_run_metrics.py+++ b/products/tasks/backend/tests/test_task_run_metrics.py@@ -7,7 +7,7 @@ from prometheus_client import REGISTRYfrom posthog.models import Organization, Team, User-from products.tasks.backend.metrics import CustomImageBuildOutcome, observe_custom_image_build+from products.tasks.backend.metrics import CustomImageBuildOutcome, observe_custom_image_build, observe_sandbox_deadlinefrom products.tasks.backend.models import Task, TaskRunfrom products.tasks.backend.temporal.client import execute_task_processing_workflowfrom products.tasks.backend.temporal.process_task.activities.track_workflow_event import (@@ -35,6 +35,16 @@ class TestCustomImageBuildMetrics:observe_custom_image_build("succeeded")+class TestSandboxDeadlineMetrics:+ def test_turn_open_reason_is_preserved(self) -> None:+ labels = {"outcome": "snapshot_only", "reason": "turn_open", "origin_product": "workflow"}+ before = _sample_value("posthog_tasks_sandbox_deadline_total", labels)++ observe_sandbox_deadline(dict[str, object](labels))++ assert _sample_value("posthog_tasks_sandbox_deadline_total", labels) == before + 1++class TestTaskRunMetrics(TestCase):def setUp(self) -> None:self.organization = Organization.objects.create(name="Test Org")