Skip to content

: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.

fix(tasks): stop idle cloud-run heartbeat storm from lifecycle updates (#65262)

Alessandro Pogliaghice2db02b5d1a
diff --git a/products/tasks/backend/temporal/process_task/activities/refresh_sandbox_credentials.py b/products/tasks/backend/temporal/process_task/activities/refresh_sandbox_credentials.py
index d556fe26c0ce..630efff02a8a 100644
--- a/products/tasks/backend/temporal/process_task/activities/refresh_sandbox_credentials.py
+++ b/products/tasks/backend/temporal/process_task/activities/refresh_sandbox_credentials.py
@@ -53,6 +53,8 @@ class RefreshSandboxCredentialsOutput:
# shortest-lived credential so the loop tracks the tightest TTL.
next_refresh_seconds: float
refreshed_kinds: list[str]
+ # Sandbox is gone/stopped and won't refresh again — the loop should stop, not keep skipping.
+ sandbox_gone: bool = False
@activity.defn
@@ -87,37 +89,43 @@ def refresh_sandbox_credentials(input: RefreshSandboxCredentialsInput) -> Refres
try:
sandbox = Sandbox.get_by_id(input.sandbox_id)
except SandboxNotFoundError:
- # Skip this cycle instead
+ # Reaped by Modal — gone for good, signal the loop to stop.
for credential in credentials:
increment_credential_refresh(credential.kind, "skipped")
logger.info(
- "sandbox_credentials_refresh_skipped_sandbox_unreachable",
+ "sandbox_credentials_refresh_stopped_sandbox_gone",
sandbox_id=input.sandbox_id,
run_id=ctx.run_id,
)
- return RefreshSandboxCredentialsOutput(next_refresh_seconds=next_refresh, refreshed_kinds=[])
+ return RefreshSandboxCredentialsOutput(
+ next_refresh_seconds=next_refresh, refreshed_kinds=[], sandbox_gone=True
+ )
if not sandbox.is_running():
for credential in credentials:
increment_credential_refresh(credential.kind, "skipped")
logger.info(
- "sandbox_credentials_refresh_skipped_not_running",
+ "sandbox_credentials_refresh_stopped_not_running",
sandbox_id=input.sandbox_id,
run_id=ctx.run_id,
)
- return RefreshSandboxCredentialsOutput(next_refresh_seconds=next_refresh, refreshed_kinds=[])
+ return RefreshSandboxCredentialsOutput(
+ next_refresh_seconds=next_refresh, refreshed_kinds=[], sandbox_gone=True
+ )
+ sandbox_gone = False
for index, credential in enumerate(credentials):
try:
outcome = credential.refresh(sandbox, ctx, task)
except SandboxNotRunningError:
logger.info(
- "sandbox_credentials_refresh_skipped_not_running",
+ "sandbox_credentials_refresh_stopped_not_running",
sandbox_id=input.sandbox_id,
run_id=ctx.run_id,
)
for skipped in credentials[index:]:
increment_credential_refresh(skipped.kind, "skipped")
+ sandbox_gone = True
break
except Exception:
logger.warning(
@@ -154,4 +162,6 @@ def refresh_sandbox_credentials(input: RefreshSandboxCredentialsInput) -> Refres
groups={"organization": ctx.organization_id, "project": ctx.team_uuid},
)
- return RefreshSandboxCredentialsOutput(next_refresh_seconds=next_refresh, refreshed_kinds=refreshed_kinds)
+ return RefreshSandboxCredentialsOutput(
+ next_refresh_seconds=next_refresh, refreshed_kinds=refreshed_kinds, sandbox_gone=sandbox_gone
+ )
diff --git a/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py b/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py
index 46ba983a34c6..a383db039345 100644
--- a/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py
+++ b/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py
@@ -259,7 +259,10 @@ async def _relay_loop(
# The background heartbeat reads this to decide whether the agent is active.
last_event_time: list[float] = [0.0] # list used as mutable container
last_workflow_signal: list[float] = [0.0] # shared with background heartbeat
- agent_active: list[bool] = [True] # agent is working; False after end_turn
+ # Whether the agent is mid-turn. Starts False (idle until a generating
+ # session_update) and resets to False on reconnect so a dropped end_of_turn
+ # can't leave it stuck True and emit phantom heartbeats.
+ agent_active: list[bool] = [False]
last_audit_ts_ns: list[int] = [0] # track last agentsh audit timestamp
stop_heartbeat = asyncio.Event()
@@ -326,7 +329,7 @@ async def _relay_loop(
# does sync Redis (cache.add) and a potential network call to
# the feature-flag service.
asyncio.create_task(asyncio.to_thread(_safe_dispatch_awaiting_input, task_run))
- elif not agent_active[0] and _is_session_update(event_data):
+ elif not agent_active[0] and _is_active_agent_update(event_data):
agent_active[0] = True
now = time.monotonic()
@@ -354,6 +357,8 @@ async def _relay_loop(
except httpx.ReadTimeout:
reconnect_count += 1
+ # May have missed an end_of_turn on the dropped stream — assume idle until re-confirmed.
+ agent_active[0] = False
logger.warning(
"relay_sandbox_events_read_timeout",
run_id=run_id,
@@ -374,6 +379,7 @@ async def _relay_loop(
return
# 5xx — transient server error, worth retrying
reconnect_count += 1
+ agent_active[0] = False # missed-end_of_turn guard (see ReadTimeout above)
logger.warning(
"relay_sandbox_events_http_error",
run_id=run_id,
@@ -385,6 +391,7 @@ async def _relay_loop(
except (httpx.TransportError, httpx_sse.SSEError) as e:
reconnect_count += 1
+ agent_active[0] = False # missed-end_of_turn guard (see ReadTimeout above)
logger.warning(
"relay_sandbox_events_connection_error",
run_id=run_id,
@@ -407,13 +414,39 @@ async def _relay_loop(
def _is_session_update(event_data: dict) -> bool:
- """Check if an event is a session/update notification (active agent processing)."""
+ """Check if an event is a session/update notification."""
if event_data.get("type") != "notification":
return False
notification = event_data.get("notification", {})
return notification.get("method") == "session/update"
+# session/update sub-types that mean the agent is actively generating. Allowlist
+# (not denylist) so an unknown/missing sub-type — a future ACP lifecycle event,
+# or a malformed payload — fails safe to "not active" rather than re-latching
+# agent_active and reviving the idle heartbeat storm.
+_GENERATION_SESSION_UPDATE_SUBTYPES = frozenset(
+ {
+ "agent_message",
+ "agent_message_chunk",
+ "agent_thought_chunk",
+ "tool_call",
+ "tool_call_update",
+ "plan",
+ "user_message",
+ "user_message_chunk",
+ }
+)
+
+
+def _is_active_agent_update(event_data: dict) -> bool:
+ """True only for session/update events where the agent is actively generating."""
+ if not _is_session_update(event_data):
+ return False
+ update = (event_data.get("notification", {}).get("params") or {}).get("update") or {}
+ return update.get("sessionUpdate") in _GENERATION_SESSION_UPDATE_SUBTYPES
+
+
def _is_keepalive_event(event_data: dict) -> bool:
return event_data.get("type") == "keepalive"
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_refresh_sandbox_credentials.py b/products/tasks/backend/temporal/process_task/activities/tests/test_refresh_sandbox_credentials.py
index d019ea8ca5cb..7d270d26190f 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_refresh_sandbox_credentials.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_refresh_sandbox_credentials.py
@@ -45,6 +45,7 @@ class TestRefreshSandboxCredentialsActivity:
assert output.refreshed_kinds == ["github"]
assert output.next_refresh_seconds == 20 * 60
+ assert output.sandbox_gone is False
# git remote rewrite + env-file read both ran against the sandbox.
assert any("git remote set-url origin" in str(c.args[0]) for c in sandbox.execute.call_args_list)
@@ -76,6 +77,7 @@ class TestRefreshSandboxCredentialsActivity:
assert output.refreshed_kinds == []
# All credentials failed -> no per-token interval, so fall back to the default cadence.
assert output.next_refresh_seconds == DEFAULT_REFRESH_INTERVAL_SECONDS
+ assert output.sandbox_gone is False
def test_skips_refresh_when_sandbox_not_running(self, activity_environment, task_context, test_task, sandbox):
sandbox.is_running.return_value = False
@@ -99,6 +101,7 @@ class TestRefreshSandboxCredentialsActivity:
assert output.refreshed_kinds == []
assert output.next_refresh_seconds == DEFAULT_REFRESH_INTERVAL_SECONDS
+ assert output.sandbox_gone is True
get_token.assert_not_called()
sandbox.execute.assert_not_called()
increment.assert_called_once_with("github", "skipped")
@@ -134,6 +137,7 @@ class TestRefreshSandboxCredentialsActivity:
assert output.refreshed_kinds == []
assert output.next_refresh_seconds == DEFAULT_REFRESH_INTERVAL_SECONDS
+ assert output.sandbox_gone is True
get_token.assert_not_called()
increment.assert_called_once_with("github", "skipped")
track_event.assert_not_called()
@@ -164,6 +168,7 @@ class TestRefreshSandboxCredentialsActivity:
)
assert output.refreshed_kinds == []
+ assert output.sandbox_gone is True
increment.assert_called_once_with("github", "skipped")
def test_genuine_execution_error_counts_as_failed(self, activity_environment, task_context, test_task, sandbox):
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.py b/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.py
index bf6180b961b8..94aa323ee75e 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.py
@@ -16,6 +16,7 @@ from products.tasks.backend.temporal.process_task.activities.get_task_processing
from products.tasks.backend.temporal.process_task.activities.relay_sandbox_events import (
RelaySandboxEventsInput,
TaskRunRedisStream,
+ _is_active_agent_update,
_is_end_of_turn,
_is_keepalive_event,
_is_session_update,
@@ -114,6 +115,54 @@ class TestIsSessionUpdate:
assert _is_session_update(event_data) == expected
+class TestIsActiveAgentUpdate:
+ @staticmethod
+ def _su(sub_type: str) -> dict:
+ return {
+ "type": "notification",
+ "notification": {"method": "session/update", "params": {"update": {"sessionUpdate": sub_type}}},
+ }
+
+ @parameterized.expand(
+ [
+ # Generation updates -> active.
+ ("agent_message", "agent_message", True),
+ ("agent_message_chunk", "agent_message_chunk", True),
+ ("agent_thought_chunk", "agent_thought_chunk", True),
+ ("tool_call", "tool_call", True),
+ ("tool_call_update", "tool_call_update", True),
+ ("plan", "plan", True),
+ ("user_message_chunk", "user_message_chunk", True),
+ # Lifecycle updates -> not active.
+ ("available_commands_update", "available_commands_update", False),
+ ("current_mode_update", "current_mode_update", False),
+ ("config_option_update", "config_option_update", False),
+ ("usage_update", "usage_update", False),
+ # Allowlist fails safe: an unknown/future sub-type is not active.
+ ("unknown_future_subtype", "some_new_lifecycle_event", False),
+ ],
+ )
+ def test_session_update_sub_types(self, _name: str, sub_type: str, expected: bool) -> None:
+ assert _is_active_agent_update(self._su(sub_type)) is expected
+
+ @parameterized.expand(
+ [
+ ("missing_session_update_key", {"update": {}}),
+ ("missing_update_key", {}),
+ ("null_params", None),
+ ],
+ )
+ def test_missing_session_update_is_not_active(self, _name: str, params: dict | None) -> None:
+ # A session/update with no sessionUpdate sub-type must not mark the agent active.
+ event = {"type": "notification", "notification": {"method": "session/update", "params": params}}
+ assert _is_active_agent_update(event) is False
+
+ def test_non_session_update_is_not_active(self) -> None:
+ assert (
+ _is_active_agent_update({"type": "notification", "notification": {"method": "_posthog/console"}}) is False
+ )
+
+
class TestIsKeepaliveEvent:
@parameterized.expand(
[
diff --git a/products/tasks/backend/temporal/process_task/credential_refresh.py b/products/tasks/backend/temporal/process_task/credential_refresh.py
index 1ff3ce5d5d35..50b363e53e41 100644
--- a/products/tasks/backend/temporal/process_task/credential_refresh.py
+++ b/products/tasks/backend/temporal/process_task/credential_refresh.py
@@ -29,6 +29,9 @@ async def run_credential_refresh_loop(context: TaskProcessingContext, sandbox_id
start_to_close_timeout=timedelta(minutes=2),
retry_policy=RetryPolicy(maximum_attempts=2),
)
+ if result.sandbox_gone:
+ workflow.logger.info("Stopping credential refresh loop: sandbox is gone")
+ return
next_refresh_seconds = result.next_refresh_seconds
except Exception as e:
# Non-fatal: keep the run alive and retry on the default cadence.
diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.py
index 4de266ce77e8..4f18fde02184 100644
--- a/products/tasks/backend/temporal/process_task/workflow.py
+++ b/products/tasks/backend/temporal/process_task/workflow.py
@@ -508,8 +508,13 @@ class ProcessTaskWorkflow(PostHogWorkflow):
case _:
raise ValueError(f"Unknown event type: {event}")
+ # Cancel background loops as soon as the run ends, not just in `finally` —
+ # a hang in the cleanup path below must not leave credential refresh running.
if relay_task is not None:
await self._cancel_relay(relay_task)
+ if credential_refresh_task is not None:
+ await self._cancel_relay(credential_refresh_task)
+ credential_refresh_task = None
if self._task_completed:
await self._update_task_run_status(self._completion_status, error_message=self._completion_error)