: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): retry transient agent stream errors (#72291)
Alessandro Pogliaghif45e81318a5d
diff --git a/products/tasks/backend/logic/services/agent_command.py b/products/tasks/backend/logic/services/agent_command.pyindex b70e3bc2783d..b32fde4aa3d0 100644--- a/products/tasks/backend/logic/services/agent_command.py+++ b/products/tasks/backend/logic/services/agent_command.py@@ -39,6 +39,18 @@ BLOCKED_IP_RANGES = []NO_ACTIVE_SESSION_ERROR = "No active session for this run"+CONTENT_BLOCK_STREAM_ERROR = "API Error: Content block not found"+CONTENT_BLOCK_STREAM_USER_ERROR = "The model response could not be completed. Please retry the task."+++def is_retryable_agent_rpc_error(error: str) -> bool:+ return CONTENT_BLOCK_STREAM_ERROR in error+++def user_facing_agent_error(error: str | None) -> str:+ if error and is_retryable_agent_rpc_error(error):+ return CONTENT_BLOCK_STREAM_USER_ERROR+ return error or "Failed to send message to sandbox"@dataclass@@ -247,13 +259,14 @@ def send_agent_command(if isinstance(data, dict) and "error" in data and "result" not in data:rpc_error = data["error"]- error_msg = rpc_error.get("message", "Unknown agent error") if isinstance(rpc_error, dict) else str(rpc_error)+ raw_error_msg = rpc_error.get("message") if isinstance(rpc_error, dict) else rpc_error+ error_msg = raw_error_msg if isinstance(raw_error_msg, str) and raw_error_msg else "Unknown agent error"return CommandResult(success=False,status_code=resp.status_code,data=data,error=error_msg,- retryable=False,+ retryable=is_retryable_agent_rpc_error(error_msg),)return CommandResult(diff --git a/products/tasks/backend/logic/services/tests/test_agent_command.py b/products/tasks/backend/logic/services/tests/test_agent_command.pyindex 5ac25bafb0fa..8b08f9827c5a 100644--- a/products/tasks/backend/logic/services/tests/test_agent_command.py+++ b/products/tasks/backend/logic/services/tests/test_agent_command.py@@ -320,6 +320,44 @@ class TestSendAgentCommand:assert "content filtering" in (result.error or "")assert not result.retryable+ @patch("products.tasks.backend.logic.services.agent_command.validate_sandbox_url", return_value=None)+ @patch("products.tasks.backend.logic.services.agent_command.requests.post")+ def test_content_block_stream_error_is_retryable(self, mock_post, mock_validate):+ mock_resp = MagicMock()+ mock_resp.status_code = 200+ mock_resp.json.return_value = {+ "jsonrpc": "2.0",+ "id": 1,+ "error": {"code": -32603, "message": "Internal error: API Error: Content block not found"},+ }+ mock_post.return_value = mock_resp++ task_run = self._make_task_run(sandbox_url="https://sandbox.modal.run/rpc")+ result = send_agent_command(task_run, "user_message", params={"content": "hi"})++ assert not result.success+ assert result.retryable++ @patch("products.tasks.backend.logic.services.agent_command.validate_sandbox_url", return_value=None)+ @patch("products.tasks.backend.logic.services.agent_command.requests.post")+ @pytest.mark.parametrize("message", [None, {}, []])+ def test_malformed_jsonrpc_error_message_is_normalized(self, mock_post, mock_validate, message):+ mock_resp = MagicMock()+ mock_resp.status_code = 200+ mock_resp.json.return_value = {+ "jsonrpc": "2.0",+ "id": 1,+ "error": {"code": -32603, "message": message},+ }+ mock_post.return_value = mock_resp++ task_run = self._make_task_run(sandbox_url="https://sandbox.modal.run/rpc")+ result = send_agent_command(task_run, "user_message", params={"content": "hi"})++ assert not result.success+ assert result.error == "Unknown agent error"+ assert not result.retryable+class TestSendUserMessage:@patch("products.tasks.backend.logic.services.agent_command.send_agent_command")diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.pyindex ccc9f97f7fdd..f97136e00db0 100644--- a/products/tasks/backend/models.py+++ b/products/tasks/backend/models.py@@ -1213,6 +1213,7 @@ class TaskRun(models.Model):state["handoff_resumed"] = Truestate["mode"] = "interactive"state.pop("pending_user_message", None)+ state.pop("pending_user_message_id", None)state.pop("pending_user_message_ts", None)self.state = statediff --git a/products/tasks/backend/temporal/process_task/activities/create_resume_snapshot.py b/products/tasks/backend/temporal/process_task/activities/create_resume_snapshot.pyindex 0112235d6477..404ff217aac3 100644--- a/products/tasks/backend/temporal/process_task/activities/create_resume_snapshot.py+++ b/products/tasks/backend/temporal/process_task/activities/create_resume_snapshot.py@@ -19,7 +19,12 @@ from products.tasks.backend.temporal.metrics import increment_snapshot_create, rlogger = structlog.get_logger(__name__)-PENDING_USER_STATE_KEYS = ["pending_user_message", "pending_user_artifact_ids", "pending_user_message_ts"]+PENDING_USER_STATE_KEYS = [+ "pending_user_message",+ "pending_user_artifact_ids",+ "pending_user_message_id",+ "pending_user_message_ts",+]@dataclassdiff --git a/products/tasks/backend/temporal/process_task/activities/forward_pending_message.py b/products/tasks/backend/temporal/process_task/activities/forward_pending_message.pyindex fddebe288710..f6b6825b5bcc 100644--- a/products/tasks/backend/temporal/process_task/activities/forward_pending_message.py+++ b/products/tasks/backend/temporal/process_task/activities/forward_pending_message.py@@ -1,8 +1,10 @@import json+import uuidfrom datetime import UTC, datetime, timedeltafrom typing import Anyfrom temporalio import activity+from temporalio.exceptions import ApplicationErrorfrom posthog.temporal.common.logger import get_loggerfrom posthog.temporal.common.utils import close_db_connections@@ -79,12 +81,23 @@ def forward_pending_user_message(run_id: str) -> None:activity_failure=activity_failure,**_task_run_log_context(task_run),):- state = task_run.state or {}++ def _ensure_pending_message_id(state: dict[str, Any]) -> None:+ if not state.get("pending_user_message") and not state.get("pending_user_artifact_ids"):+ return+ pending_message_id = state.get("pending_user_message_id")+ if not isinstance(pending_message_id, str) or not pending_message_id:+ state["pending_user_message_id"] = str(uuid.uuid4())++ state = TaskRun.mutate_state_atomic(run_id, _ensure_pending_message_id)pending_message = state.get("pending_user_message")pending_user_artifact_ids = state.get("pending_user_artifact_ids") or []if not pending_message and not pending_user_artifact_ids:return+ pending_message_id = state.get("pending_user_message_id")+ assert isinstance(pending_message_id, str) and pending_message_id+pending_artifacts: list[dict[str, Any]] = []if pending_user_artifact_ids:pending_artifacts, missing_artifact_ids = get_task_run_artifacts_by_id(task_run, pending_user_artifact_ids)@@ -112,6 +125,7 @@ def forward_pending_user_message(run_id: str) -> None:artifacts=pending_artifacts or None,auth_token=auth_token,timeout=90,+ message_id=pending_message_id,)logger.info("forward_pending_message_attempted",@@ -126,9 +140,12 @@ def forward_pending_user_message(run_id: str) -> None:artifacts=pending_artifacts or None,auth_token=auth_token,timeout=90,+ message_id=pending_message_id,)if not result.success and result.retryable:+ from products.tasks.backend.logic.services.agent_command import user_facing_agent_error+retryable_delivery_error = result.error or "Retryable pending message delivery failed"observe_followup_delivery_failed(task_run, retryable=True)logger.warning(@@ -136,7 +153,12 @@ def forward_pending_user_message(run_id: str) -> None:run_id=run_id,error=result.error,)- return+ if state.get("interaction_origin") == "slack":+ _enqueue_pending_delivery_failure_relay(task_run, state.get("pending_user_message_ts"), result.error)+ raise ApplicationError(+ f"forward pending message failed: {user_facing_agent_error(result.error)}",+ non_retryable=True,+ )pending_message_ts = state.get("pending_user_message_ts")@@ -148,7 +170,12 @@ def forward_pending_user_message(run_id: str) -> None:TaskRun.update_state_atomic(run_id,- remove_keys=["pending_user_message", "pending_user_artifact_ids", "pending_user_message_ts"],+ remove_keys=[+ "pending_user_message",+ "pending_user_artifact_ids",+ "pending_user_message_id",+ "pending_user_message_ts",+ ],)if result.success:@@ -163,9 +190,10 @@ def forward_pending_user_message(run_id: str) -> None:def _enqueue_pending_delivery_failure_relay(task_run: Any, user_message_ts: str | None, error: str | None) -> None:+ from products.tasks.backend.logic.services.agent_command import user_facing_agent_errorfrom products.tasks.backend.temporal.client import execute_posthog_code_agent_relay_workflow- error_suffix = f" ({error})" if error else ""+ error_suffix = f" ({user_facing_agent_error(error)})" if error else ""try:execute_posthog_code_agent_relay_workflow(run_id=str(task_run.id),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 9751babef63b..28f40d3e9cb1 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@@ -18,6 +18,7 @@ from products.tasks.backend.logic.services.agent_command import (CommandResult,send_refresh_session,send_user_message,+ user_facing_agent_error,)from products.tasks.backend.logic.services.connection_token import create_sandbox_connection_tokenfrom products.tasks.backend.logic.services.run_actor import slack_actor_state_updates@@ -217,25 +218,26 @@ def _deliver_followup(input: SendFollowupToSandboxInput) -> None:run_id=input.run_id,timeout_seconds=FOLLOWUP_TIMEOUT_SECONDS,)- elif result.status_code == 504:- # A 504 *response* (Modal tunnel gateway timeout) leaves delivery- # unknown: the message may or may not have reached the agent-server.- # The message_id idempotency key makes redelivery safe, so retry- # instead of guessing; only the final attempt writes the sentinel.+ elif result.retryable and input.message_id:+ # Retry transport failures and known transient agent errors. message_id+ # prevents duplicate turns when delivery is uncertain, and the agent-server+ # releases the id when a delivered turn fails before completion.attempt = _current_attempt()+ failure_kind = "delivery unknown" if result.status_code == 504 else "retryable failure"if attempt < SEND_FOLLOWUP_MAX_ATTEMPTS:logger.warning(- "send_followup_delivery_unknown_retrying",+ "send_followup_retrying",run_id=input.run_id,attempt=attempt,error=result.error,+ status_code=result.status_code,)- raise ApplicationError(f"send_followup delivery unknown: {result.error}")- error_msg = result.error or "Failed to send message to sandbox"+ raise ApplicationError(f"send_followup {failure_kind}: {result.error}")+ error_msg = user_facing_agent_error(result.error)logger.warning("send_followup_failed",run_id=input.run_id,- error=error_msg,+ error=result.error,status_code=result.status_code,)_write_error_and_complete(input.run_id, error_msg, run_uses_dedicated_stream(task_run.state))@@ -247,7 +249,7 @@ def _deliver_followup(input: SendFollowupToSandboxInput) -> None:error=result.error,status_code=result.status_code,)- error_msg = result.error or "Failed to send message to sandbox"+ error_msg = user_facing_agent_error(result.error)_write_error_and_complete(input.run_id, error_msg, run_uses_dedicated_stream(task_run.state))# Propagate failure to the workflow.raise ApplicationError(f"send_followup failed: {error_msg}", non_retryable=True)diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_create_resume_snapshot.py b/products/tasks/backend/temporal/process_task/activities/tests/test_create_resume_snapshot.pyindex 8265b2c1650a..918895996add 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_create_resume_snapshot.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_create_resume_snapshot.py@@ -39,7 +39,12 @@ def test_create_directory_resume_snapshot_uses_tmp_mount_path(activity_environme"snapshot_kind": SNAPSHOT_KIND_DIRECTORY,"snapshot_mount_path": DEFAULT_DIRECTORY_RESUME_SNAPSHOT_MOUNT_PATH,},- remove_keys=["pending_user_message", "pending_user_artifact_ids", "pending_user_message_ts"],+ remove_keys=[+ "pending_user_message",+ "pending_user_artifact_ids",+ "pending_user_message_id",+ "pending_user_message_ts",+ ],)assert output.external_id == "im-dir"assert output.snapshot_kind == SNAPSHOT_KIND_DIRECTORYdiff --git a/products/tasks/backend/temporal/process_task/tests/test_forward_pending_message.py b/products/tasks/backend/temporal/process_task/tests/test_forward_pending_message.pyindex 11c803556644..8d1135c121db 100644--- a/products/tasks/backend/temporal/process_task/tests/test_forward_pending_message.py+++ b/products/tasks/backend/temporal/process_task/tests/test_forward_pending_message.py@@ -9,6 +9,7 @@ from django.test import TestCasefrom parameterized import parameterizedfrom prometheus_client import REGISTRY+from temporalio.exceptions import ApplicationErrorfrom posthog.models.integration import Integrationfrom posthog.models.organization import Organization@@ -94,8 +95,10 @@ class TestForwardPendingUserMessage(TestCase):mock_send.assert_called_once()assert mock_send.call_args[0][1] == "fix the tests"+ assert mock_send.call_args.kwargs["message_id"]run.refresh_from_db()assert "pending_user_message" not in run.state+ assert "pending_user_message_id" not in run.state@patch("products.tasks.backend.logic.services.connection_token.create_sandbox_connection_token", return_value="jwt")@patch("products.tasks.backend.temporal.observability.posthoganalytics.capture")@@ -109,14 +112,17 @@ class TestForwardPendingUserMessage(TestCase):)mock_send.return_value = _command_result(success=False, status_code=504, error="timeout", retryable=True)- forward_pending_user_message(str(run.id))+ with self.assertRaises(ApplicationError) as error_context:+ forward_pending_user_message(str(run.id))+ assert error_context.exception.non_retryable is Truemock_send.assert_called_once()captured_events = [call.kwargs["event"] for call in mock_capture.call_args_list]assert "process_task_activity_failed" in captured_eventsassert "process_task_activity_completed" not in captured_eventsrun.refresh_from_db()assert run.state.get("pending_user_message") == "fix the tests"+ assert run.state.get("pending_user_message_id")@patch("products.tasks.backend.logic.services.connection_token.create_sandbox_connection_token", return_value="jwt")@patch("products.tasks.backend.logic.services.agent_command.send_user_message")@@ -132,12 +138,18 @@ class TestForwardPendingUserMessage(TestCase):)before = _delivery_failed_sample("true")- forward_pending_user_message(str(run.id))+ with self.assertRaises(ApplicationError) as error_context:+ forward_pending_user_message(str(run.id))+ assert error_context.exception.non_retryable is Trueassert mock_send.call_count == 2+ message_ids = [call.kwargs["message_id"] for call in mock_send.call_args_list]+ assert message_ids[0]+ assert message_ids[0] == message_ids[1]assert _delivery_failed_sample("true") == before + 1run.refresh_from_db()assert run.state.get("pending_user_message") == "fix the tests"+ assert run.state.get("pending_user_message_id") == message_ids[0]@patch("products.tasks.backend.logic.services.connection_token.create_sandbox_connection_token", return_value="jwt")@patch("products.tasks.backend.logic.services.agent_command.send_user_message")@@ -157,6 +169,7 @@ class TestForwardPendingUserMessage(TestCase):assert _delivery_failed_sample("false") == before + 1run.refresh_from_db()assert "pending_user_message" not in run.state+ assert "pending_user_message_id" not in run.state@patch("products.tasks.backend.logic.services.staged_artifacts.get_task_run_artifacts_by_id",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 adca99b8e9ab..c8abef3520fa 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@@ -520,18 +520,41 @@ class TestSendFollowupTurnTimeout:_patches["error"].assert_not_called()_patches["turn_complete"].assert_not_called()- def test_undelivered_message_stays_fatal(self, _patches):- # The non-fatal carve-out must stay scoped to delivered-but-running —- # a connection failure means the user's message never arrived.+ def test_retryable_failure_retries_without_sentinel(self, _patches):_patches["user_msg"].return_value = CommandResult(success=False, status_code=502, error="Connection to sandbox failed", retryable=True)- with pytest.raises(ApplicationError, match="Connection to sandbox failed") as exc_info:- send_followup_to_sandbox(SendFollowupToSandboxInput(run_id="run-1", message="hi"))+ with pytest.raises(ApplicationError, match="retryable failure") as exc_info:+ send_followup_to_sandbox(SendFollowupToSandboxInput(run_id="run-1", message="hi", message_id="m-1"))++ assert exc_info.value.non_retryable is False+ _patches["error"].assert_not_called()+ _patches["turn_complete"].assert_not_called()++ def test_retryable_stream_error_final_attempt_writes_actionable_sentinel(self, _patches):+ _patches["user_msg"].return_value = CommandResult(+ success=False,+ status_code=200,+ error="Internal error: API Error: Content block not found",+ retryable=True,+ )++ with (+ patch(+ "products.tasks.backend.temporal.process_task.activities.send_followup_to_sandbox._current_attempt",+ return_value=SEND_FOLLOWUP_MAX_ATTEMPTS,+ ),+ pytest.raises(ApplicationError, match="The model response could not be completed") as exc_info,+ ):+ send_followup_to_sandbox(SendFollowupToSandboxInput(run_id="run-1", message="hi", message_id="m-1"))assert exc_info.value.non_retryable is True- _patches["error"].assert_called_once()+ _patches["error"].assert_called_once_with(+ "run-1",+ "The model response could not be completed. Please retry the task.",+ False,+ )_patches["turn_complete"].assert_not_called()def test_response_504_retries_without_sentinel(self, _patches):@@ -543,7 +566,7 @@ class TestSendFollowupTurnTimeout:)with pytest.raises(ApplicationError, match="delivery unknown") as exc_info:- send_followup_to_sandbox(SendFollowupToSandboxInput(run_id="run-1", message="hi"))+ send_followup_to_sandbox(SendFollowupToSandboxInput(run_id="run-1", message="hi", message_id="m-1"))assert exc_info.value.non_retryable is False_patches["error"].assert_not_called()@@ -561,7 +584,7 @@ class TestSendFollowupTurnTimeout:),pytest.raises(ApplicationError, match="send_followup failed") as exc_info,):- send_followup_to_sandbox(SendFollowupToSandboxInput(run_id="run-1", message="hi"))+ send_followup_to_sandbox(SendFollowupToSandboxInput(run_id="run-1", message="hi", message_id="m-1"))assert exc_info.value.non_retryable is True_patches["error"].assert_called_once()