: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 writing error_message onto runs completed by inactivity timeout (#70051)
Alessandro Pogliaghidb700b4dff63
diff --git a/products/tasks/backend/temporal/process_task/activities/post_slack_update.py b/products/tasks/backend/temporal/process_task/activities/post_slack_update.pyindex c9886a752dd5..7a6862aa4d47 100644--- a/products/tasks/backend/temporal/process_task/activities/post_slack_update.py+++ b/products/tasks/backend/temporal/process_task/activities/post_slack_update.py@@ -10,6 +10,9 @@ from posthog.temporal.common.logger import get_loggerfrom posthog.temporal.common.utils import close_db_connectionsfrom products.tasks.backend.access import has_tasks_access+from products.tasks.backend.temporal.process_task.activities.update_task_run_status import (+ TIMED_OUT_INACTIVITY_STATE_KEY,+)logger = get_logger(__name__)@@ -135,7 +138,7 @@ def post_slack_update(input: PostSlackUpdateInput) -> None:if task_run.status == TaskRun.Status.COMPLETED:handler.update_reaction("hedgehog")- if task_run.error_message and "timed out" in task_run.error_message:+ if _is_timed_out_completion(task_run):handler.delete_progress()returnif pr_url:@@ -160,6 +163,14 @@ def post_slack_update(input: PostSlackUpdateInput) -> None:logger.exception("post_slack_update_failed", run_id=input.run_id)+def _is_timed_out_completion(task_run: Any) -> bool:+ """The error_message check covers runs finalized before the state marker existed."""+ state = task_run.state if isinstance(task_run.state, dict) else {}+ if state.get(TIMED_OUT_INACTIVITY_STATE_KEY):+ return True+ return bool(task_run.error_message and "timed out" in task_run.error_message)++def _get_stage_from_status(status: str, stage: str | None = None) -> str:"""Map task run status to human-readable stage. Uses the run's stage field when available."""if stage:diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_update_task_run_status.py b/products/tasks/backend/temporal/process_task/activities/tests/test_update_task_run_status.pyindex be9550c329ea..98fb72894b88 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_update_task_run_status.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_update_task_run_status.py@@ -48,6 +48,25 @@ class TestUpdateTaskRunStatusActivity:test_task_run.refresh_from_db()assert test_task_run.error_message == error_msg+ @pytest.mark.django_db(transaction=True)+ def test_timed_out_inactivity_sets_state_marker_without_error_message(self, activity_environment, test_task_run):+ test_task_run.state = {**(test_task_run.state or {}), "existing_key": "kept"}+ test_task_run.save(update_fields=["state"])++ input_data = UpdateTaskRunStatusInput(+ run_id=str(test_task_run.id),+ status=TaskRun.Status.COMPLETED,+ timed_out_inactivity=True,+ )+ async_to_sync(activity_environment.run)(update_task_run_status, input_data)++ test_task_run.refresh_from_db()+ assert test_task_run.status == TaskRun.Status.COMPLETED+ assert test_task_run.error_message is None+ assert test_task_run.state.get("timed_out_inactivity") is True+ # Merge, not replace: pre-existing state keys survive the marker write.+ assert test_task_run.state.get("existing_key") == "kept"+@pytest.mark.django_db(transaction=True)@patch("products.tasks.backend.models.TaskRun.publish_stream_state_event")def test_publishes_stream_state_event(self, mock_publish_stream_state_event, activity_environment, test_task_run):diff --git a/products/tasks/backend/temporal/process_task/activities/update_task_run_status.py b/products/tasks/backend/temporal/process_task/activities/update_task_run_status.pyindex 594573e02542..d93fcd36ddee 100644--- a/products/tasks/backend/temporal/process_task/activities/update_task_run_status.py+++ b/products/tasks/backend/temporal/process_task/activities/update_task_run_status.py@@ -12,12 +12,17 @@ from products.tasks.backend.models import TaskRunfrom products.tasks.backend.temporal.metrics import record_run_token_usagefrom products.tasks.backend.temporal.observability import log_with_activity_context+# TaskRun.state marker for runs completed by the inactivity timeout; kept out of+# error_message so a normal completion never reads as a failure.+TIMED_OUT_INACTIVITY_STATE_KEY = "timed_out_inactivity"+@dataclassclass UpdateTaskRunStatusInput:run_id: strstatus: strerror_message: Optional[str] = None+ timed_out_inactivity: bool = False@activity.defn@@ -44,6 +49,10 @@ def update_task_run_status(input: UpdateTaskRunStatusInput) -> None:if input.error_message:task_run.error_message = input.error_message+ if input.timed_out_inactivity:+ # Atomic merge so concurrent state writers aren't clobbered; reassigned so reads below see it.+ task_run.state = TaskRun.update_state_atomic(task_run.id, updates={TIMED_OUT_INACTIVITY_STATE_KEY: True})+if input.status in [TaskRun.Status.COMPLETED, TaskRun.Status.FAILED]:task_run.completed_at = timezone.now()diff --git a/products/tasks/backend/temporal/process_task/tests/test_followup.py b/products/tasks/backend/temporal/process_task/tests/test_followup.pyindex b21a21d7c396..b45a4546e9b8 100644--- a/products/tasks/backend/temporal/process_task/tests/test_followup.py+++ b/products/tasks/backend/temporal/process_task/tests/test_followup.py@@ -27,7 +27,7 @@ from products.tasks.backend.temporal.process_task.workflow import (ProcessTaskWorkflow,)-_status_updates: list[tuple[str, str | None]] = []+_status_updates: list[tuple[str, str | None, bool]] = []@activity.defn(name="get_task_processing_context")@@ -46,7 +46,7 @@ def _mock_get_context(_input) -> TaskProcessingContext:@activity.defn(name="update_task_run_status")def _mock_update_status(input: UpdateTaskRunStatusInput) -> None:- _status_updates.append((input.status, input.error_message))+ _status_updates.append((input.status, input.error_message, input.timed_out_inactivity))@activity.defn(name="prepare_sandbox_for_repository")@@ -162,7 +162,7 @@ class TestFollowupDeliveryFailure:assert result.success is True- failed_updates = [(s, e) for s, e in _status_updates if s == "failed"]+ failed_updates = [(s, e) for s, e, _ in _status_updates if s == "failed"]assert len(failed_updates) == 1assert failed_updates[0][1] == "Follow-up delivery failed: RuntimeError: Sandbox session is dead"@@ -290,8 +290,9 @@ class TestCIFollowUpLoop:assert result.success is Trueassert len(_ci_followup_calls) == MAX_CI_REPETITIONSassert all(msg == DEFAULT_CI_MESSAGE for msg in _ci_followup_calls)- timeout_updates = [(s, e) for s, e in _status_updates if "timed out" in (e or "")]+ timeout_updates = [(s, e) for s, e, timed_out in _status_updates if timed_out]assert timeout_updates, f"expected an inactivity-timeout completion, got {_status_updates}"+ assert timeout_updates == [("completed", None)]@pytest.mark.timeout(60, func_only=True)async def test_uses_ci_prompt_override_when_set(self):@@ -347,7 +348,7 @@ class TestCIFollowUpLoop:await handle.result()assert _ci_followup_calls == []- timeout_updates = [(s, e) for s, e in _status_updates if "timed out" in (e or "")]+ timeout_updates = [(s, e) for s, e, timed_out in _status_updates if timed_out]assert timeout_updates, f"expected an inactivity-timeout completion, got {_status_updates}"@pytest.mark.timeout(60, func_only=True)@@ -372,7 +373,7 @@ class TestCIFollowUpLoop:assert result.success is Trueassert _ci_followup_calls == []- completed_updates = [(s, e) for s, e in _status_updates if s == "completed" and e is None]+ completed_updates = [(s, e) for s, e, _ in _status_updates if s == "completed" and e is None]assert len(completed_updates) >= 1@pytest.mark.timeout(90, func_only=True)diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.pyindex fc8fa299448a..f94a960c7627 100644--- a/products/tasks/backend/temporal/process_task/workflow.py+++ b/products/tasks/backend/temporal/process_task/workflow.py@@ -686,7 +686,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):if self._task_completed:await self._update_task_run_status(self._completion_status, error_message=self._completion_error)elif timed_out:- await self._update_task_run_status("completed", error_message="Run timed out due to inactivity")+ await self._update_task_run_status("completed", timed_out_inactivity=True)# Close out the keep-it-green step so a finished run doesn't show a still-spinning CI step.if self._pr_progress_emitted:@@ -1292,7 +1292,11 @@ class ProcessTaskWorkflow(PostHogWorkflow):)async def _update_task_run_status(- self, status: str, error_message: Optional[str] = None, run_id: Optional[str] = None+ self,+ status: str,+ error_message: Optional[str] = None,+ run_id: Optional[str] = None,+ timed_out_inactivity: bool = False,) -> None:await workflow.execute_activity(update_task_run_status,@@ -1300,6 +1304,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):run_id=run_id if run_id is not None else self.context.run_id,status=status,error_message=error_message,+ timed_out_inactivity=timed_out_inactivity,),start_to_close_timeout=timedelta(minutes=1),retry_policy=RetryPolicy(maximum_attempts=3),diff --git a/products/tasks/backend/tests/test_post_slack_update.py b/products/tasks/backend/tests/test_post_slack_update.pyindex 254283f1813d..10ae514a7a0c 100644--- a/products/tasks/backend/tests/test_post_slack_update.py+++ b/products/tasks/backend/tests/test_post_slack_update.py@@ -4,6 +4,8 @@ from unittest.mock import MagicMock, patchfrom django.test import TestCase, override_settings+from parameterized import parameterized+from products.slack_app.backend.slack_thread import SlackThreadHandler_post_slack_update_module = importlib.import_module(@@ -220,18 +222,31 @@ class TestPostSlackUpdate(TestCase):mock_run.task.mark_slack_pr_notified.assert_called_once_with("https://github.com/org/repo/pull/1")mock_run.save.assert_not_called()+ @parameterized.expand(+ [+ ({"state": {"timed_out_inactivity": True}, "error_message": None},),+ # Runs finalized before the state marker existed carry the signal in error_message.+ ({"error_message": "Run timed out due to inactivity"},),+ ]+ )@patch.object(SlackThreadHandler, "post_completion")@patch.object(SlackThreadHandler, "delete_progress")@patch.object(SlackThreadHandler, "update_reaction")@patch.object(SlackThreadHandler, "__init__", return_value=None)@patch("products.tasks.backend.models.TaskRun")def test_timed_out_run_silently_deletes_progress(- self, mock_task_run_class, mock_handler_init, mock_update_reaction, mock_delete_progress, mock_post_completion+ self,+ run_kwargs,+ mock_task_run_class,+ mock_handler_init,+ mock_update_reaction,+ mock_delete_progress,+ mock_post_completion,):mock_run = self._make_mock_run(mock_task_run_class.Status.COMPLETED,- error_message="Run timed out due to inactivity",output={},+ **run_kwargs,)mock_task_run_class.objects.select_related.return_value.get.return_value = mock_run