: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): keep resume startup updates from aborting rotation (#118628)
Alessandro Pogliaghif608b2c2fd4d
diff --git a/products/tasks/backend/logic/stream/event_ingest.py b/products/tasks/backend/logic/stream/event_ingest.pyindex 395640fbd27b..02b57f643202 100644--- a/products/tasks/backend/logic/stream/event_ingest.py+++ b/products/tasks/backend/logic/stream/event_ingest.py@@ -616,7 +616,7 @@ async def _heartbeat_workflow_if_needed(redis_stream: TaskRunRedisStream, run_idreturnactivity_started = False- if _is_session_update(event) or is_agent_generation_event(event):+ if is_agent_generation_event(event):activity_started = not await redis_stream.set_agent_active(True)agent_active = Trueelse:diff --git a/products/tasks/backend/metrics.py b/products/tasks/backend/metrics.pyindex d649f28a2508..3b1c99a24859 100644--- a/products/tasks/backend/metrics.py+++ b/products/tasks/backend/metrics.py@@ -741,6 +741,9 @@ _SANDBOX_DEADLINE_REASONS = {"snapshot_missing","provision_failed","snapshot_unused",+ "agent_activity",+ "activity_during_snapshot",+ "activity_during_handoff",}diff --git a/products/tasks/backend/tests/test_event_ingest.py b/products/tasks/backend/tests/test_event_ingest.pyindex d3a050604ad6..c70355e01db4 100644--- a/products/tasks/backend/tests/test_event_ingest.py+++ b/products/tasks/backend/tests/test_event_ingest.py@@ -289,6 +289,41 @@ class TestTaskRunEventIngest(TestCase):self.assertEqual(body["accepted"], len(events))self.assertEqual(heartbeat_workflow.call_args_list, [call(agent_active=True, force=True)] * 2)+ @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)+ def test_resumed_sandbox_startup_does_not_heartbeat_workflow(self) -> None:+ token = self._create_token()+ events = [+ {"type": "notification", "notification": {"method": "session/update", "params": {"update": update}}}+ for update in (+ {"sessionUpdate": "plan", "entries": []},+ {"sessionUpdate": "available_commands_update", "availableCommands": []},+ {"sessionUpdate": "usage_update"},+ )+ ] + [+ {"type": "notification", "notification": {"method": "_posthog/run_started", "params": {}}},+ {+ "type": "notification",+ "notification": {"method": "_posthog/turn_complete", "params": {"stopReason": "idle_resume"}},+ },+ {"type": "notification", "notification": {"method": "_posthog/console", "params": {}}},+ ]++ with (+ patch.object(TaskRun, "heartbeat_workflow") as heartbeat_workflow,+ patch.object(TaskRun, "signal_agent_turn_completed"),+ ):+ status, body = self._call_ingest(+ token, [{"seq": index, "event": event} for index, event in enumerate(events, start=1)]+ )++ async def agent_active() -> bool:+ return await TaskRunRedisStream(get_task_run_stream_key(str(self.task_run.id))).get_agent_active()++ self.assertEqual(status, 200)+ self.assertEqual(body["accepted"], len(events))+ heartbeat_workflow.assert_not_called()+ self.assertFalse(asyncio.run(agent_active()))+@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)def test_streaming_ingest_releases_failed_activity_claim(self) -> None:token = self._create_token()@@ -694,7 +729,13 @@ class TestTaskRunEventIngest(TestCase):json.dumps({"seq": 1,- "event": {"type": "notification", "notification": {"method": "session/update"}},+ "event": {+ "type": "notification",+ "notification": {+ "method": "session/update",+ "params": {"update": {"sessionUpdate": "agent_message_chunk"}},+ },+ },})+ "\n"diff --git a/products/tasks/backend/tests/test_task_run_metrics.py b/products/tasks/backend/tests/test_task_run_metrics.pyindex eb12a9b8b2f8..b9e0ebf63933 100644--- a/products/tasks/backend/tests/test_task_run_metrics.py+++ b/products/tasks/backend/tests/test_task_run_metrics.py@@ -43,8 +43,9 @@ class TestCustomImageBuildMetrics:class TestSandboxDeadlineMetrics:- def test_turn_open_reason_is_preserved(self) -> None:- labels = {"outcome": "snapshot_only", "reason": "turn_open", "origin_product": "workflow"}+ @parameterized.expand(["turn_open", "agent_activity", "activity_during_snapshot", "activity_during_handoff"])+ def test_reason_is_preserved(self, reason: str) -> None:+ labels = {"outcome": "snapshot_only", "reason": reason, "origin_product": "workflow"}before = _sample_value("posthog_tasks_sandbox_deadline_total", labels)observe_sandbox_deadline(dict[str, object](labels))diff --git a/services/agent-proxy/src/lib/side-effects.ts b/services/agent-proxy/src/lib/side-effects.tsindex 558a6efe791f..2dab320ce6d9 100644--- a/services/agent-proxy/src/lib/side-effects.ts+++ b/services/agent-proxy/src/lib/side-effects.ts@@ -466,7 +466,7 @@ export async function heartbeatWorkflowIfNeeded(let agentActive: booleanlet activityStarted = false- if (isSessionUpdate(event) || isAgentGenerationEvent(event)) {+ if (isAgentGenerationEvent(event)) {activityStarted = !(await redisStream.setAgentActive(true))agentActive = true} else {diff --git a/services/agent-proxy/tests/hono/ingest-handler.test.ts b/services/agent-proxy/tests/hono/ingest-handler.test.tsindex 5daf00592305..2b2825426b64 100644--- a/services/agent-proxy/tests/hono/ingest-handler.test.ts+++ b/services/agent-proxy/tests/hono/ingest-handler.test.ts@@ -1327,8 +1327,8 @@ describe('ingest-handler', () => {params: { update: { sessionUpdate: 'user_message_chunk' } },},},- expectedKinds: ['heartbeat'],- expectedActive: true,+ expectedKinds: [],+ expectedActive: false,},{name: 'agent output',@@ -1351,8 +1351,29 @@ describe('ingest-handler', () => {params: { update: { sessionUpdate: 'plan' } },},},- expectedKinds: ['heartbeat'],- expectedActive: true,+ expectedKinds: [],+ expectedActive: false,+ },+ {+ name: 'resumed session commands',+ event: {+ type: 'notification',+ notification: {+ method: 'session/update',+ params: { update: { sessionUpdate: 'available_commands_update' } },+ },+ },+ expectedKinds: [],+ expectedActive: false,+ },+ {+ name: 'idle resume turn complete',+ event: {+ type: 'notification',+ notification: { method: '_posthog/turn_complete', params: { stopReason: 'idle_resume' } },+ },+ expectedKinds: ['awaiting_input'],+ expectedActive: false,},{name: 'command dispatch',@@ -1575,7 +1596,10 @@ describe('ingest-handler', () => {const turnComplete = { type: 'notification', notification: { method: '_posthog/turn_complete' } }const piTurnError = { type: 'pi_event', event: { type: 'turn_completed', stopReason: 'error' } }- const sessionUpdate = { type: 'notification', notification: { method: 'session/update', params: {} } }+ const sessionUpdate = {+ type: 'notification',+ notification: { method: 'session/update', params: { update: { sessionUpdate: 'agent_message_chunk' } } },+ }const networkFailure = Object.assign(new TypeError('fetch failed'), { cause: { code: 'ECONNRESET' } })it.each([@@ -1599,6 +1623,7 @@ describe('ingest-handler', () => {.mockResolvedValue(new Response('{"dispatched": true}', { status: 200 }))global.fetch = fetchMock as typeof fetch+ await redisStream.claimFirstAgentActivity()const config = makeConfig({ djangoCallbackBaseUrl: 'http://django' })await heartbeatWorkflowIfNeeded(redisStream, RUN_ID, event, TASK_ID, TEAM_ID, 'tok', config)await vi.advanceTimersByTimeAsync(2000)@@ -1612,7 +1637,13 @@ describe('ingest-handler', () => {)it.each([- { type: 'notification', notification: { method: 'session/update' } },+ {+ type: 'notification',+ notification: {+ method: 'session/update',+ params: { update: { sessionUpdate: 'agent_message_chunk' } },+ },+ },...['assistant_message_chunk', 'assistant_thought_chunk', 'tool_call_started', 'tool_call_updated'].map((type) => ({ type: 'pi_event', event: { type } })),