: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): surface real cause on follow-up delivery failure (#67686)
Alessandro Pogliaghiae374f59385f
diff --git a/posthog/temporal/common/base.py b/posthog/temporal/common/base.pyindex 85b6c34030d8..f970cd174eb4 100644--- a/posthog/temporal/common/base.py+++ b/posthog/temporal/common/base.py@@ -1,6 +1,8 @@import jsonimport typing+import temporalio.exceptions+class PostHogWorkflow:"""Base class for Temporal Workflows that can be executed in PostHog."""@@ -9,6 +11,31 @@ class PostHogWorkflow:inputs_cls: typing.ClassVar[type | None] = Noneinputs_optional: typing.ClassVar[bool] = False+ @staticmethod+ def _activity_error_properties(error: Exception) -> dict[str, typing.Any]:+ if not isinstance(error, temporalio.exceptions.ActivityError):+ return {}++ retry_state = error.retry_state+ properties: dict[str, typing.Any] = {+ "temporal_activity_id": error.activity_id,+ "temporal_activity_type": error.activity_type,+ "temporal_activity_identity": error.identity,+ "temporal_activity_retry_state": retry_state.name if retry_state else None,+ "temporal_activity_scheduled_event_id": error.scheduled_event_id,+ "temporal_activity_started_event_id": error.started_event_id,+ }++ if error.cause:+ properties.update(+ {+ "cause_error_type": type(error.cause).__name__,+ "cause_error_message": str(error.cause)[:500],+ }+ )++ return properties+@classmethoddef get_name(cls) -> str:"""Get workflow's name."""diff --git a/products/tasks/backend/temporal/execute_sandbox/tests/test_execute_sandbox_workflow.py b/products/tasks/backend/temporal/execute_sandbox/tests/test_execute_sandbox_workflow.pyindex 1c0a5bb1c0d9..128ef5c28064 100644--- a/products/tasks/backend/temporal/execute_sandbox/tests/test_execute_sandbox_workflow.py+++ b/products/tasks/backend/temporal/execute_sandbox/tests/test_execute_sandbox_workflow.py@@ -434,6 +434,34 @@ class TestHandleFollowup:assert ack.args[2] is Falseassert "sandbox is dead" in (ack.args[3] or "")+ async def test_dispatch_failure_unwraps_activity_error_cause(self, monkeypatch, silent_workflow_logger):+ workflow = ExecuteSandboxWorkflow()+ workflow._context = _build_context()+ workflow._parent_workflow_id = "parent-wf"++ activity_error = ActivityError(+ "Activity task failed",+ scheduled_event_id=1,+ started_event_id=2,+ identity="worker-1",+ activity_type="send_followup_to_sandbox",+ activity_id="activity-1",+ retry_state=RetryState.MAXIMUM_ATTEMPTS_REACHED,+ )+ activity_error.__cause__ = RuntimeError("send_followup failed: sandbox unreachable")++ send_mock = AsyncMock(side_effect=activity_error)+ monkeypatch.setattr(workflow, "_send_followup_to_sandbox", send_mock)+ monkeypatch.setattr(workflow, "_flush_pending_outbound", AsyncMock())++ await workflow._handle_followup(PendingFollowup(message="msg", artifact_ids=[], ack_id="ack-fail"))++ assert workflow._task_completed is True+ assert workflow._completion_status == "failed"+ assert workflow._completion_error == "Follow-up delivery failed: send_followup failed: sandbox unreachable"+ ack = workflow._pending_outbound[-1]+ assert ack.args[3] == "send_followup failed: sandbox unreachable"+class TestReapOrphanedSandbox:"""The reaper is one activity now: read + Modal destroy + clear-state alldiff --git a/products/tasks/backend/temporal/execute_sandbox/workflow.py b/products/tasks/backend/temporal/execute_sandbox/workflow.pyindex 86881d61cb6f..0e62a96e7ba7 100644--- a/products/tasks/backend/temporal/execute_sandbox/workflow.py+++ b/products/tasks/backend/temporal/execute_sandbox/workflow.py@@ -17,7 +17,6 @@ from enum import StrEnumfrom typing import Any, Optionalimport temporalio-import temporalio.exceptionsfrom temporalio import workflowfrom temporalio.common import RetryPolicy@@ -289,29 +288,6 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):posthog_mcp_scopes=loaded.get("posthog_mcp_scopes", "read_only"),)- @staticmethod- def _activity_error_properties(error: Exception) -> dict[str, Any]:- if not isinstance(error, temporalio.exceptions.ActivityError):- return {}-- retry_state = error.retry_state- properties: dict[str, Any] = {- "temporal_activity_id": error.activity_id,- "temporal_activity_type": error.activity_type,- "temporal_activity_identity": error.identity,- "temporal_activity_retry_state": retry_state.name if retry_state else None,- "temporal_activity_scheduled_event_id": error.scheduled_event_id,- "temporal_activity_started_event_id": error.started_event_id,- }- if error.cause:- properties.update(- {- "cause_error_type": type(error.cause).__name__,- "cause_error_message": str(error.cause)[:500],- }- )- return properties-@staticmethoddef _should_skip_followup(message: str | None, artifact_ids: list[str]) -> bool:return not message and not artifact_ids@@ -727,19 +703,22 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):# Mirror process_task: a failed follow-up dispatch is terminal.# Surface the failure to the parent via both the ACK and the# task-completion path so it can react immediately.+ error_properties = self._activity_error_properties(e)+ cause_message = error_properties.get("cause_error_message")workflow.logger.warning("execute_sandbox_send_followup_failed",run_id=self.context.run_id,error=str(e),+ **error_properties,)self._completion_status = "failed"- self._completion_error = f"Follow-up delivery failed: {e}"+ self._completion_error = f"Follow-up delivery failed: {cause_message or e}"self._task_completed = Trueself._enqueue_ack(signal_name=SEND_FOLLOWUP_SIGNAL,ack_id=followup.ack_id,accepted=False,- detail=str(e)[:200],+ detail=(cause_message or str(e))[:200],)finally:self._in_flight_followup_ack_ids.discard(followup.ack_id)diff --git a/products/tasks/backend/temporal/process_task/tests/test_followup.py b/products/tasks/backend/temporal/process_task/tests/test_followup.pyindex 59c478b50193..b21a21d7c396 100644--- a/products/tasks/backend/temporal/process_task/tests/test_followup.py+++ b/products/tasks/backend/temporal/process_task/tests/test_followup.py@@ -164,7 +164,7 @@ class TestFollowupDeliveryFailure:failed_updates = [(s, e) for s, e in _status_updates if s == "failed"]assert len(failed_updates) == 1- assert "Follow-up delivery failed" in (failed_updates[0][1] or "")+ assert failed_updates[0][1] == "Follow-up delivery failed: RuntimeError: Sandbox session is dead"_ci_context_overrides: dict = {}diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.pyindex 216b4f4c2029..4172a93cb0dd 100644--- a/products/tasks/backend/temporal/process_task/workflow.py+++ b/products/tasks/backend/temporal/process_task/workflow.py@@ -208,31 +208,6 @@ class ProcessTaskWorkflow(PostHogWorkflow):prewarmed=loaded.get("prewarmed", False),)- @staticmethod- def _activity_error_properties(error: Exception) -> dict[str, Any]:- if not isinstance(error, temporalio.exceptions.ActivityError):- return {}-- retry_state = error.retry_state- properties: dict[str, Any] = {- "temporal_activity_id": error.activity_id,- "temporal_activity_type": error.activity_type,- "temporal_activity_identity": error.identity,- "temporal_activity_retry_state": retry_state.name if retry_state else None,- "temporal_activity_scheduled_event_id": error.scheduled_event_id,- "temporal_activity_started_event_id": error.started_event_id,- }-- if error.cause:- properties.update(- {- "cause_error_type": type(error.cause).__name__,- "cause_error_message": str(error.cause)[:500],- }- )-- return properties-async def _wait_for_task_external_event(self):await workflow.wait_condition(lambda: (@@ -1301,15 +1276,18 @@ class ProcessTaskWorkflow(PostHogWorkflow):retry_policy=RetryPolicy(maximum_attempts=1),)except Exception as e:+ error_properties = self._activity_error_properties(e)+ cause_message = error_properties.get("cause_error_message")workflow.logger.warning("send_followup_to_sandbox_failed",extra={"run_id": self.context.run_id,"error": str(e),+ **error_properties,},)# Mark the run as failed so poll_for_turn sees a terminal status# immediately instead of waiting for the inactivity timeout.self._completion_status = "failed"- self._completion_error = f"Follow-up delivery failed: {e}"+ self._completion_error = f"Follow-up delivery failed: {cause_message or e}"self._task_completed = True