: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 failing runs when a turn outlives the followup timeout (#67747)
Alessandro Pogliaghi7e71a4d0035a
diff --git a/products/tasks/backend/logic/services/agent_command.py b/products/tasks/backend/logic/services/agent_command.pyindex 543943480513..b70e3bc2783d 100644--- a/products/tasks/backend/logic/services/agent_command.py+++ b/products/tasks/backend/logic/services/agent_command.py@@ -48,6 +48,10 @@ class CommandResult:data: dict[str, Any] | None = Noneerror: str | None = Noneretryable: bool = False+ # True only when the request body was fully sent and the agent is still+ # processing it (local read timeout). A 504 *response* (e.g. from the+ # Modal tunnel) leaves this False — there delivery is unknown.+ turn_in_flight: bool = Falsedef validate_sandbox_url(url: str) -> str | None:@@ -171,6 +175,20 @@ def send_agent_command(timeout=timeout,params=query_params or None,)+ except requests.ReadTimeout:+ # The request body was already sent — the sandbox has the command and+ # is still processing it. Callers rely on turn_in_flight meaning+ # "delivered but not finished" (e.g. a long agent turn), as opposed to+ # the connection failures below where the command never arrived.+ # ConnectTimeout subclasses both Timeout and ConnectionError; catching+ # ReadTimeout first keeps it in the 502 bucket.+ return CommandResult(+ success=False,+ status_code=504,+ error="Sandbox request timed out",+ retryable=True,+ turn_in_flight=True,+ )except requests.ConnectionError:return CommandResult(success=False,@@ -252,13 +270,21 @@ def send_user_message(artifacts: list[dict[str, Any]] | None = None,auth_token: str | None = None,timeout: int = COMMAND_TIMEOUT_SECONDS,+ message_id: str | None = None,) -> CommandResult:- """Send a user_message command to the sandbox agent."""+ """Send a user_message command to the sandbox agent.++ ``message_id`` is an idempotency key: the agent-server ignores a+ redelivery carrying an id it has already accepted, which makes retrying+ delivery after an attempt-level death (worker restart) safe.+ """params: dict[str, Any] = {}if message:params["content"] = messageif artifacts:params["artifacts"] = artifacts+ if message_id:+ params["messageId"] = message_idreturn send_agent_command(task_run,method="user_message",diff --git a/products/tasks/backend/logic/services/tests/test_agent_command.py b/products/tasks/backend/logic/services/tests/test_agent_command.pyindex 47ca0a97f9f3..5ac25bafb0fa 100644--- a/products/tasks/backend/logic/services/tests/test_agent_command.py+++ b/products/tasks/backend/logic/services/tests/test_agent_command.py@@ -224,6 +224,46 @@ class TestSendAgentCommand:assert result.status_code == 504assert result.retryable+ @pytest.mark.parametrize(+ "exception,expected_status,expected_turn_in_flight",+ [+ # turn_in_flight means "request delivered, sandbox still+ # processing" — callers (send_followup_to_sandbox) treat it as a+ # still-running turn, so a ConnectTimeout (never delivered) must+ # never set it.+ (requests.ReadTimeout("read timed out"), 504, True),+ (requests.ConnectTimeout("connect timed out"), 502, False),+ ],+ ids=["read_timeout_maps_to_504_in_flight", "connect_timeout_maps_to_502"],+ )+ @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_timeout_kind_disambiguates_delivery(+ self, mock_post, mock_validate, exception, expected_status, expected_turn_in_flight+ ):+ mock_post.side_effect = exception+ task_run = self._make_task_run(sandbox_url="https://sandbox.modal.run/rpc")+ result = send_agent_command(task_run, "cancel")+ assert not result.success+ assert result.status_code == expected_status+ assert result.turn_in_flight is expected_turn_in_flight++ @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_response_504_is_not_turn_in_flight(self, mock_post, mock_validate):+ # A 504 HTTP *response* (e.g. Modal tunnel gateway timeout) leaves+ # delivery unknown — it must never be conflated with the read-timeout+ # "delivered, still running" case.+ mock_resp = MagicMock()+ mock_resp.status_code = 504+ 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, "cancel")+ assert not result.success+ assert result.status_code == 504+ assert result.turn_in_flight is False+@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_5xx_is_retryable(self, mock_post, mock_validate):diff --git a/products/tasks/backend/temporal/execute_sandbox/workflow.py b/products/tasks/backend/temporal/execute_sandbox/workflow.pyindex c2deac20dce8..d56329c4f750 100644--- a/products/tasks/backend/temporal/execute_sandbox/workflow.py+++ b/products/tasks/backend/temporal/execute_sandbox/workflow.py@@ -78,6 +78,7 @@ from products.tasks.backend.temporal.process_task.activities.relay_sandbox_eventrelay_sandbox_events,)from products.tasks.backend.temporal.process_task.activities.send_followup_to_sandbox import (+ SEND_FOLLOWUP_MAX_ATTEMPTS,SendFollowupToSandboxInput,send_followup_to_sandbox,)@@ -1177,7 +1178,14 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):message=message,posthog_mcp_scopes=self._posthog_mcp_scopes,artifact_ids=artifact_ids,+ message_id=str(workflow.uuid4()),),start_to_close_timeout=timedelta(minutes=35),- retry_policy=RetryPolicy(maximum_attempts=1),+ # See process_task: heartbeat detects worker restarts, message_id+ # makes redelivery idempotent, sentinel failures are non-retryable.+ heartbeat_timeout=timedelta(minutes=1),+ retry_policy=RetryPolicy(+ initial_interval=timedelta(seconds=5),+ maximum_attempts=SEND_FOLLOWUP_MAX_ATTEMPTS,+ ),)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 b808b931c8ef..6aed39ff3aaa 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@@ -1,10 +1,13 @@import jsonimport time+import threading+import contextvarsfrom dataclasses import dataclassfrom typing import Anyimport structlogfrom temporalio import activity+from temporalio.exceptions import ApplicationErrorfrom posthog.temporal.common.utils import close_db_connectionsfrom posthog.temporal.oauth import PosthogMcpScopes@@ -35,6 +38,12 @@ logger = structlog.get_logger(__name__)REFRESH_RETRY_DELAY_SECONDS = 0.5+# Retries exist for attempt-level deaths (worker restart kills the in-flight+# attempt, detected via heartbeat timeout) and for delivery-unknown failures.+# Application failures that write an error sentinel raise non-retryable.+SEND_FOLLOWUP_MAX_ATTEMPTS = 3+SEND_FOLLOWUP_HEARTBEAT_INTERVAL_SECONDS = 15+@dataclassclass SendFollowupToSandboxInput:@@ -42,6 +51,9 @@ class SendFollowupToSandboxInput:message: str | None = Noneposthog_mcp_scopes: PosthogMcpScopes = "read_only"artifact_ids: list[str] | None = None+ # Workflow-generated idempotency key. Stable across activity retries, so+ # the agent-server can drop a redelivery of a message it already accepted.+ message_id: str | None = None@activity.defn@@ -52,7 +64,46 @@ def send_followup_to_sandbox(input: SendFollowupToSandboxInput) -> None:Called by the workflow when it receives a send_followup_message signal from theweb layer. Writes turn_complete on success or an error event on failure so theSSE stream terminates cleanly.++ Heartbeats from a side thread while the delivery call blocks (the sync+ /command response can legitimately take up to FOLLOWUP_TIMEOUT_SECONDS),+ so a worker restart is detected within the heartbeat timeout instead of+ the 35-minute start_to_close."""+ stop_heartbeat = threading.Event()+ heartbeat_ctx = contextvars.copy_context()++ def _heartbeat_loop() -> None:+ while not stop_heartbeat.wait(SEND_FOLLOWUP_HEARTBEAT_INTERVAL_SECONDS):+ try:+ activity.heartbeat()+ except Exception:+ return++ heartbeat_thread = threading.Thread(target=lambda: heartbeat_ctx.run(_heartbeat_loop), daemon=True)+ heartbeat_thread.start()+ try:+ _deliver_followup(input)+ finally:+ stop_heartbeat.set()+ heartbeat_thread.join(timeout=2)+++def _current_attempt() -> int:+ try:+ return activity.info().attempt+ except Exception:+ return 1+++def _is_duplicate_delivery(result_data: dict[str, Any] | None) -> bool:+ if not isinstance(result_data, dict):+ return False+ result = result_data.get("result")+ return isinstance(result, dict) and result.get("duplicate") is True+++def _deliver_followup(input: SendFollowupToSandboxInput) -> None:try:task_run = TaskRun.objects.select_related("task__created_by").get(id=input.run_id)except TaskRun.DoesNotExist:@@ -61,7 +112,7 @@ def send_followup_to_sandbox(input: SendFollowupToSandboxInput) -> None:_write_error_and_complete(input.run_id, error_msg)# Raise so the workflow can mark the run as failed. Without this,# background-mode runs hang until the inactivity timeout because- raise RuntimeError(f"send_followup failed: {error_msg}")+ raise ApplicationError(f"send_followup failed: {error_msg}", non_retryable=True)auth_token = Nonecreated_by = task_run.task.created_by@@ -80,7 +131,7 @@ def send_followup_to_sandbox(input: SendFollowupToSandboxInput) -> None:if missing_artifact_ids:error_msg = f"Artifacts not found on this run: {', '.join(missing_artifact_ids)}"_write_error_and_complete(input.run_id, error_msg, run_uses_dedicated_stream(task_run.state))- raise RuntimeError(f"send_followup failed: {error_msg}")+ raise ApplicationError(f"send_followup failed: {error_msg}", non_retryable=True)result = send_user_message(task_run,@@ -88,6 +139,7 @@ def send_followup_to_sandbox(input: SendFollowupToSandboxInput) -> None:artifacts=artifacts,auth_token=auth_token,timeout=FOLLOWUP_TIMEOUT_SECONDS,+ message_id=input.message_id,)logger.info("send_followup_to_sandbox_attempted",@@ -97,8 +149,52 @@ def send_followup_to_sandbox(input: SendFollowupToSandboxInput) -> None:)if result.success:+ if _is_duplicate_delivery(result.data):+ logger.info(+ "send_followup_duplicate_delivery",+ run_id=input.run_id,+ attempt=_current_attempt(),+ )+ return_write_turn_complete(input.run_id, _get_stop_reason(result.data), run_uses_dedicated_stream(task_run.state))logger.info("send_followup_delivered", run_id=input.run_id)+ elif result.turn_in_flight:+ # A read timeout means the message reached the sandbox and the turn is+ # simply still running — FOLLOWUP_TIMEOUT_SECONDS caps how long this+ # activity waits for the synchronous ack, not how long a turn may+ # take. Don't fail the run or write a sentinel: the sandbox broadcasts+ # _posthog/turn_complete through the event stream when the turn+ # actually ends, and run liveness stays governed by heartbeats plus the+ # workflow inactivity timeout. Failing here used to destroy healthy+ # sandboxes mid-work on any turn longer than 30 minutes.+ logger.info(+ "send_followup_turn_still_running",+ 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.+ attempt = _current_attempt()+ if attempt < SEND_FOLLOWUP_MAX_ATTEMPTS:+ logger.warning(+ "send_followup_delivery_unknown_retrying",+ run_id=input.run_id,+ attempt=attempt,+ error=result.error,+ )+ raise ApplicationError(f"send_followup delivery unknown: {result.error}")+ error_msg = result.error or "Failed to send message to sandbox"+ logger.warning(+ "send_followup_failed",+ run_id=input.run_id,+ error=error_msg,+ status_code=result.status_code,+ )+ _write_error_and_complete(input.run_id, error_msg, run_uses_dedicated_stream(task_run.state))+ raise ApplicationError(f"send_followup failed: {error_msg}", non_retryable=True)else:logger.warning("send_followup_failed",@@ -109,7 +205,7 @@ def send_followup_to_sandbox(input: SendFollowupToSandboxInput) -> None:error_msg = result.error or "Failed to send message to sandbox"_write_error_and_complete(input.run_id, error_msg, run_uses_dedicated_stream(task_run.state))# Propagate failure to the workflow.- raise RuntimeError(f"send_followup failed: {error_msg}")+ raise ApplicationError(f"send_followup failed: {error_msg}", non_retryable=True)def _refresh_sandbox_mcp(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 c0b48330b34f..08ede70f60f2 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@@ -3,9 +3,12 @@ from unittest.mock import MagicMock, patchfrom django.core.cache import cache+from temporalio.exceptions import ApplicationError+from products.tasks.backend.logic.services.agent_command import CommandResultfrom products.tasks.backend.temporal.process_task.activities.send_followup_to_sandbox import (REFRESH_RETRY_DELAY_SECONDS,+ SEND_FOLLOWUP_MAX_ATTEMPTS,SendFollowupToSandboxInput,_refresh_sandbox_mcp,send_followup_to_sandbox,@@ -367,3 +370,125 @@ class TestSendFollowupActivityRefreshOrdering:args, _kwargs = _patches["refresh"].call_argsassert args[1] == "read_only"+++class TestSendFollowupTurnTimeout:+ """A read timeout (turn_in_flight) means the message was delivered and the+ turn is still running — the activity must not fail the run or write stream+ markers. A 504 *response* leaves delivery unknown and must retry; any other+ delivery failure stays fatal."""++ @pytest.fixture+ def _patches(self):+ with (+ patch(+ "products.tasks.backend.temporal.process_task.activities.send_followup_to_sandbox.TaskRun"+ ) as mock_task_run_cls,+ patch(+ "products.tasks.backend.temporal.process_task.activities.send_followup_to_sandbox.create_sandbox_connection_token"+ ) as mock_conn_token,+ patch(+ "products.tasks.backend.temporal.process_task.activities.send_followup_to_sandbox._refresh_sandbox_mcp"+ ),+ patch(+ "products.tasks.backend.temporal.process_task.activities.send_followup_to_sandbox.send_user_message"+ ) as mock_user_msg,+ patch(+ "products.tasks.backend.temporal.process_task.activities.send_followup_to_sandbox._write_turn_complete"+ ) as mock_turn_complete,+ patch(+ "products.tasks.backend.temporal.process_task.activities.send_followup_to_sandbox._write_error_and_complete"+ ) as mock_error,+ ):+ task_run = _make_task_run_mock()+ task_run.task.created_by = MagicMock(id=42, distinct_id="u42")+ mock_task_run_cls.objects.select_related.return_value.get.return_value = task_run+ mock_conn_token.return_value = "jwt"++ yield {+ "user_msg": mock_user_msg,+ "turn_complete": mock_turn_complete,+ "error": mock_error,+ }++ def test_read_timeout_is_non_fatal_and_writes_no_markers(self, _patches):+ # Regression: a turn longer than FOLLOWUP_TIMEOUT_SECONDS used to fail+ # the run and destroy a healthy sandbox mid-work.+ _patches["user_msg"].return_value = CommandResult(+ success=False, status_code=504, error="Sandbox request timed out", retryable=True, turn_in_flight=True+ )++ send_followup_to_sandbox(SendFollowupToSandboxInput(run_id="run-1", message="hi"))++ _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.+ _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"))++ assert exc_info.value.non_retryable is True+ _patches["error"].assert_called_once()+ _patches["turn_complete"].assert_not_called()++ def test_response_504_retries_without_sentinel(self, _patches):+ # Regression: a genuine 504 *response* (tunnel gateway timeout,+ # delivery unknown) used to be conflated with the read-timeout case+ # and silently treated as delivered — losing the user's message.+ _patches["user_msg"].return_value = CommandResult(+ success=False, status_code=504, error="Sandbox returned 504", retryable=True+ )++ with pytest.raises(ApplicationError, match="delivery unknown") as exc_info:+ send_followup_to_sandbox(SendFollowupToSandboxInput(run_id="run-1", message="hi"))++ assert exc_info.value.non_retryable is False+ _patches["error"].assert_not_called()+ _patches["turn_complete"].assert_not_called()++ def test_response_504_final_attempt_writes_sentinel_and_fails(self, _patches):+ _patches["user_msg"].return_value = CommandResult(+ success=False, status_code=504, error="Sandbox returned 504", 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="send_followup failed") as exc_info,+ ):+ send_followup_to_sandbox(SendFollowupToSandboxInput(run_id="run-1", message="hi"))++ assert exc_info.value.non_retryable is True+ _patches["error"].assert_called_once()+ _patches["turn_complete"].assert_not_called()++ def test_duplicate_delivery_skips_markers(self, _patches):+ # A retried attempt whose message the agent-server already accepted+ # must not write a synthetic turn_complete — the turn is still running+ # and the event stream owns its completion.+ _patches["user_msg"].return_value = CommandResult(+ success=True,+ status_code=200,+ data={"result": {"duplicate": True, "stopReason": "duplicate_delivery"}},+ )++ send_followup_to_sandbox(SendFollowupToSandboxInput(run_id="run-1", message="hi", message_id="m-1"))++ _patches["error"].assert_not_called()+ _patches["turn_complete"].assert_not_called()++ def test_message_id_forwarded_to_sandbox(self, _patches):+ _patches["user_msg"].return_value = CommandResult(success=True, status_code=200)++ send_followup_to_sandbox(SendFollowupToSandboxInput(run_id="run-1", message="hi", message_id="m-1"))++ _, kwargs = _patches["user_msg"].call_args+ assert kwargs["message_id"] == "m-1"diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.pyindex 849c375c4bbf..d4a2be035216 100644--- a/products/tasks/backend/temporal/process_task/workflow.py+++ b/products/tasks/backend/temporal/process_task/workflow.py@@ -50,7 +50,11 @@ from .activities.provision_sandbox import (from .activities.read_sandbox_logs import ReadSandboxLogsInput, read_sandbox_logsfrom .activities.relay_sandbox_events import RelaySandboxEventsInput, relay_sandbox_eventsfrom .activities.run_wizard import RunWizardInput, run_wizard-from .activities.send_followup_to_sandbox import SendFollowupToSandboxInput, send_followup_to_sandbox+from .activities.send_followup_to_sandbox import (+ SEND_FOLLOWUP_MAX_ATTEMPTS,+ SendFollowupToSandboxInput,+ send_followup_to_sandbox,+)from .activities.start_agent_server import (MarkRepoReadyInput,StartAgentServerInput,@@ -1304,9 +1308,19 @@ class ProcessTaskWorkflow(PostHogWorkflow):message=message,posthog_mcp_scopes=self._posthog_mcp_scopes,artifact_ids=artifact_ids,+ message_id=str(workflow.uuid4()),),start_to_close_timeout=timedelta(minutes=35),- retry_policy=RetryPolicy(maximum_attempts=1),+ # The activity heartbeats while blocked on the sync delivery+ # call, so a worker restart is detected here instead of at+ # start_to_close. Retries are safe: message_id lets the+ # agent-server drop a redelivery it already accepted, and+ # sentinel-writing failures raise non-retryable.+ heartbeat_timeout=timedelta(minutes=1),+ retry_policy=RetryPolicy(+ initial_interval=timedelta(seconds=5),+ maximum_attempts=SEND_FOLLOWUP_MAX_ATTEMPTS,+ ),)except Exception as e:error_properties = self._activity_error_properties(e)