: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): stop silent and canceling runs promptly (#92954)
Dylan Martin0783265879f6
diff --git a/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py b/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.pyindex f6dc184371cb..76d53b749ea8 100644--- a/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py+++ b/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py@@ -346,15 +346,12 @@ def _should_signal_workflow_heartbeat(return Falseif last_workflow_signal is not None and (now - last_workflow_signal[0]) < HEARTBEAT_INTERVAL_SECONDS:return False- # An in-flight turn can be legitimately quiet for minutes (a long tool call- # emits no session events), so a short per-run idle window (loop runs: 2- # minutes) must not starve keep-alives mid-turn and let the workflow tear- # the sandbox down under the agent. Floor the freshness guard at the- # background default; that still bounds how long a turn that hung without- # an end_of_turn can pin the sandbox, and the short window keeps applying- # to post-turn idleness because agent_active is false there.- event_freshness_seconds = max(inactivity_timeout_seconds, INACTIVITY_TIMEOUT_DEFAULT_SECONDS)- return (now - last_event_time[0]) < event_freshness_seconds+ # The workflow starts a full inactivity timer after the final heartbeat.+ # Subtract that timer so event silence never exceeds the larger idle window.+ heartbeat_budget_seconds = (+ max(inactivity_timeout_seconds, INACTIVITY_TIMEOUT_DEFAULT_SECONDS) - inactivity_timeout_seconds+ )+ return heartbeat_budget_seconds > 0 and (now - last_event_time[0]) < heartbeat_budget_secondsasync def _relay_loop(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 3b44cbd99bfd..c955a2d057a7 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@@ -83,6 +83,7 @@ REFRESH_RETRY_DELAY_SECONDS = 0.5SANDBOX_STOPPED_MESSAGE = ("This run's sandbox has stopped, so your message wasn't delivered. Start a new run to continue.")+RUN_STOPPING_MESSAGE = "This run is stopping, so your message wasn't delivered. Start a new run to continue."PEER_SANDBOX_STOPPED_MESSAGE = "The recipient run's sandbox has stopped"DENIED_PERMISSION_STOP_MESSAGE = ("Stopped after the denied action. Send a new message to continue with a different approach."@@ -306,6 +307,18 @@ def _deliver_followup(input: SendFollowupToSandboxInput) -> str | None:# background-mode runs hang until the inactivity timeout becauseraise ApplicationError(f"send_followup failed: {error_msg}", non_retryable=True)+ # Reject the marker written by user-initiated cancel, and the bare CANCELLED status that+ # loop overlap and lifecycle cancellation set without that marker (loop_runs.py,+ # loop_lifecycle.py). Either means the run is winding down, so no follow-up should rebind+ # credentials or reach the sandbox.+ if (task_run.state or {}).get("cancel_requested_at") or task_run.status == TaskRun.Status.CANCELLED:+ if peer_message_id is not None:+ _mark_peer_delivery_outcome(+ peer_message_id, AgentPeerMessage.Outcome.DELIVERY_FAILED, "run_stopping", RUN_STOPPING_MESSAGE+ )+ raise ApplicationError(f"peer message delivery failed: {RUN_STOPPING_MESSAGE}", non_retryable=True)+ raise ApplicationError(RUN_STOPPING_MESSAGE, non_retryable=True)+if peer_message_id is not None:return _deliver_peer_message(input, task_run, peer_message_id)diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.py b/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.pyindex d8bd78f51eab..b3b4a4464e80 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.py@@ -1293,20 +1293,22 @@ class TestShouldSignalWorkflowHeartbeat:# Loop runs carry a 2-minute idle window; a quiet in-flight turn past that# window must still keep the workflow alive (the mid-turn teardown bug).("mid_turn_quiet_past_short_run_window", True, 300.0, 120.0, True),- # The floor is the background default, not unbounded: a turn that hung- # without an end_of_turn stops pinning the sandbox past that window.+ # Leave the workflow's short inactivity timer enough time to expire at+ # the background default instead of after another full short window.(- "mid_turn_quiet_past_default_window",+ "mid_turn_quiet_past_heartbeat_budget",True,- float(INACTIVITY_TIMEOUT_DEFAULT_SECONDS) + 60.0,+ float(INACTIVITY_TIMEOUT_DEFAULT_SECONDS) - 60.0,120.0,False,),# Idle after end_of_turn: the short loop window applies and the run winds down.("idle_agent_stale_events", False, 300.0, 120.0, False),("mid_turn_fresh_events", True, 30.0, 120.0, True),- # Runs with a window above the default keep their longer window mid-turn.- ("mid_turn_long_window_still_fresh", True, float(INACTIVITY_TIMEOUT_DEFAULT_SECONDS) + 60.0, 3600.0, True),+ # Default and longer windows rely on the event-driven heartbeat, then+ # let their own inactivity timer measure the full silence window.+ ("mid_turn_default_window_uses_event_heartbeat", True, 30.0, 1800.0, False),+ ("mid_turn_long_window_uses_event_heartbeat", True, 30.0, 3600.0, False),])def test_freshness_gating(diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_send_followup_to_sandbox.py b/products/tasks/backend/temporal/process_task/activities/tests/test_send_followup_to_sandbox.pyindex 564a661bfdb2..24ee99c03e2e 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_send_followup_to_sandbox.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_send_followup_to_sandbox.py@@ -89,6 +89,7 @@ class TestSendFollowupToSandbox(BaseTest):self, mock_task_run_objects, mock_send_user_message, mock_publish):task_run = MagicMock()+ task_run.state = {}task_run.task.created_by = Nonemock_task_run_objects.select_related.return_value.get.return_value = task_runmock_send_user_message.return_value = MagicMock(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 35189e18b8a7..18f8ca4bcfaf 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@@ -11,6 +11,7 @@ from products.tasks.backend.logic.services.agent_command import CommandResultfrom products.tasks.backend.temporal.process_task.activities.send_followup_to_sandbox import (DENIED_PERMISSION_STOP_MESSAGE,REFRESH_RETRY_DELAY_SECONDS,+ RUN_STOPPING_MESSAGE,SANDBOX_STOPPED_MESSAGE,SEND_FOLLOWUP_MAX_ATTEMPTS,STEER_DECLINED_OUTCOME,@@ -763,6 +764,35 @@ class TestSendFollowupActivityRefreshOrdering:_patches["refresh"].assert_not_called()_patches["user_msg"].assert_not_called()+ def test_a_stopping_run_rejects_before_rebinding_credentials(self, _patches):+ _patches["task_run"].state = {"cancel_requested_at": "2026-01-01T00:00:00+00:00"}++ with pytest.raises(ApplicationError) as excinfo:+ send_followup_to_sandbox(SendFollowupToSandboxInput(run_id="run-1", message="hi"))++ assert str(excinfo.value) == RUN_STOPPING_MESSAGE+ assert excinfo.value.non_retryable+ _patches["conn_token"].assert_not_called()+ _patches["refresh"].assert_not_called()+ _patches["refresh_github"].assert_not_called()+ _patches["user_msg"].assert_not_called()++ def test_a_cancelled_status_run_rejects_before_rebinding_credentials(self, _patches):+ # Loop overlap and lifecycle cancellation set CANCELLED without the cancel marker,+ # so the status alone must reject the follow-up.+ _patches["task_run"].state = {}+ _patches["task_run"].status = _patches["task_run_cls"].Status.CANCELLED++ with pytest.raises(ApplicationError) as excinfo:+ send_followup_to_sandbox(SendFollowupToSandboxInput(run_id="run-1", message="hi"))++ assert str(excinfo.value) == RUN_STOPPING_MESSAGE+ assert excinfo.value.non_retryable+ _patches["conn_token"].assert_not_called()+ _patches["refresh"].assert_not_called()+ _patches["refresh_github"].assert_not_called()+ _patches["user_msg"].assert_not_called()+def test_stopped_sandbox_says_so_once_instead_of_retrying(self, _patches):_patches["refresh_github"].return_value = SandboxRebindFailure.SANDBOX_NOT_RUNNING@@ -1299,6 +1329,24 @@ class TestPeerDeliveryMode:assert _patches["mark"].call_args.args == (self._PEER_ID, "delivery_failed")assert _patches["mark"].call_args.kwargs["failure_phase"] == "credential_identity"+ def test_stopping_run_rejects_before_peer_delivery(self, _patches):+ _patches["task_run"].state = {"cancel_requested_at": "2026-01-01T00:00:00+00:00"}++ with pytest.raises(ApplicationError) as excinfo:+ send_followup_to_sandbox(+ SendFollowupToSandboxInput(+ run_id="run-1", message="peer ping", message_id="m-1", context=self._peer_context()+ )+ )++ assert excinfo.value.non_retryable is True+ _patches["conn_token"].assert_not_called()+ _patches["refresh_mcp"].assert_not_called()+ _patches["refresh_github"].assert_not_called()+ _patches["user_msg"].assert_not_called()+ assert _patches["mark"].call_args.args == (self._PEER_ID, "delivery_failed")+ assert _patches["mark"].call_args.kwargs["failure_phase"] == "run_stopping"+@pytest.mark.parametrize("refresh_key", ["refresh_mcp", "refresh_github"])def test_refresh_failure_marks_row_without_stream_sentinels(self, _patches, refresh_key):_patches["bound_actor"].return_value = (MagicMock(id=42, distinct_id="u42"), "")