: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 infra log lines resetting the run inactivity timer (#74038)
Fernando Gomes397ebce4544c
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex 9d0c8d3eb462..91da06c3473c 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -2415,15 +2415,46 @@ def set_task_run_output(return _task_run_detail_to_dto(run)+def _entries_show_agent_activity(entries: list[dict]) -> bool:+ """Classify a log batch as agent activity, but only judge batches that speak ACP.++ Within an ACP batch, only ``session/*`` notifications count as the agent doing work.+ Infra frames (``_posthog/console``, credential-refresh notices, errors) must not reset+ the workflow's inactivity timeout: the workflow's own periodic credential refresh makes+ the sandbox log a line, so counting every frame lets a run whose agent went silent keep+ itself alive forever.++ Batches with no ACP frame at all are not sandbox chatter, they come from callers that+ only ever post generic ``{type, message}`` entries. Those runs have always relied on the+ append itself as their heartbeat, so they keep the old behaviour rather than silently+ losing their inactivity extension.+ """+ saw_acp_frame = False+ for entry in entries:+ notification = entry.get("notification")+ if not isinstance(notification, dict):+ continue+ saw_acp_frame = True+ method = notification.get("method")+ if isinstance(method, str) and method.startswith("session/"):+ return True+ return bool(entries) and not saw_acp_frame++def append_task_run_log(run_id: str | UUID, task_id: str | UUID, team_id: int, *, entries: list[dict]) -> contracts.TaskRunDetailDTO | None:- """Append log entries to a run's S3 log and heartbeat its workflow."""+ """Append log entries to a run's S3 log and heartbeat its workflow.++ The heartbeat only reports the agent as active when the entries show real agent+ activity; sandbox infra frames are still appended but heartbeat with+ ``agent_active=False``, which the workflow's signal handler ignores.+ """run = _get_visible_run(run_id, task_id, team_id)if run is None:return Nonerun.append_log(entries)- run.heartbeat_workflow(agent_active=True)+ run.heartbeat_workflow(agent_active=_entries_show_agent_activity(entries))return _task_run_detail_to_dto(run)diff --git a/products/tasks/backend/tests/test_facade.py b/products/tasks/backend/tests/test_facade.pyindex 8318bd5d7cee..3278bec6c261 100644--- a/products/tasks/backend/tests/test_facade.py+++ b/products/tasks/backend/tests/test_facade.py@@ -3,7 +3,7 @@ from datetime import timedeltafrom typing import ClassVarfrom uuid import uuid4-from unittest.mock import patch+from unittest.mock import MagicMock, patchfrom django.test import TestCasefrom django.utils import timezone as django_timezone@@ -750,6 +750,61 @@ class TestFacadeReadsAndMappers(TestCase):self.assertEqual(run.state.get("ai_stage"), "wizard_pr_agent")+class TestAppendLogAgentActivity(TestCase):+ # Guards the self-sustaining heartbeat loop: infra log lines (credential refresh ->+ # _posthog/console) heartbeating with agent_active=True reset the workflow's inactivity+ # timer on every write, so a run whose agent went silent could never time out.+ @parameterized.expand(+ [+ ("session_update", [{"notification": {"method": "session/update", "params": {}}}], True),+ ("session_request", [{"notification": {"method": "session/request_permission", "params": {}}}], True),+ ("console_only", [{"notification": {"method": "_posthog/console", "params": {"message": "x"}}}], False),+ ("error_only", [{"notification": {"method": "_posthog/error", "params": {}}}], False),+ # Non-ACP batches keep the old heartbeat behaviour: callers that only post generic+ # {type, message} entries have no session/* frame to offer and would otherwise lose+ # their inactivity extension while still working.+ ("no_notification", [{"message": "plain infra line"}], True),+ ("malformed_notification", [{"notification": "not-a-dict"}], True),+ ("non_string_method", [{"notification": {"method": 7}}], False),+ ("empty_entries", [], False),+ (+ "mixed_infra_and_session",+ [+ {"notification": {"method": "_posthog/console", "params": {}}},+ {"notification": {"method": "session/update", "params": {}}},+ ],+ True,+ ),+ # One ACP frame is enough to mark the batch as sandbox traffic, so the plain line+ # riding alongside it does not buy the credential-refresh batch a heartbeat.+ (+ "plain_line_alongside_infra_frame",+ [+ {"message": "plain infra line"},+ {"notification": {"method": "_posthog/console", "params": {}}},+ ],+ False,+ ),+ ]+ )+ def test_entries_show_agent_activity(self, _name, entries, expected):+ self.assertIs(facade._entries_show_agent_activity(entries), expected)++ def test_append_task_run_log_heartbeats_with_classified_activity(self):+ run = MagicMock()+ with (+ patch.object(facade, "_get_visible_run", return_value=run),+ patch.object(facade, "_task_run_detail_to_dto", return_value=None),+ ):+ facade.append_task_run_log(+ "r", "t", 1, entries=[{"notification": {"method": "_posthog/console", "params": {}}}]+ )+ run.heartbeat_workflow.assert_called_once_with(agent_active=False)+ run.reset_mock()+ facade.append_task_run_log("r", "t", 1, entries=[{"notification": {"method": "session/update"}}])+ run.heartbeat_workflow.assert_called_once_with(agent_active=True)++class TestRecentWizardCloudRunTimes(TestCase):organization: ClassVar[Organization]team: ClassVar[Team]