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): keep a run alive while a tool call is still running (#100007)

Alessandro Pogliaghi78cc3289ebb5
diff --git a/products/tasks/backend/temporal/metrics.py b/products/tasks/backend/temporal/metrics.py
index a43615eeadae..2f9fea3b0866 100644
--- a/products/tasks/backend/temporal/metrics.py
+++ b/products/tasks/backend/temporal/metrics.py
@@ -286,6 +286,16 @@ def increment_sandbox_wedge_probe(verdict: str, write_stage: str) -> None:
pass
+def increment_tool_call_only_heartbeat() -> None:
+ try:
+ _metric_meter().create_counter(
+ "tasks_tool_call_only_heartbeat",
+ "Run keep-alives carried only by an unfinished tool call through a long event silence",
+ ).add(1)
+ except Exception:
+ pass
+
+
def increment_pr_babysit_decision(decision: str) -> None:
try:
meter = workflow.metric_meter().with_additional_attributes({"decision": decision})
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 775fb9f66b3e..ac0404dd8740 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
@@ -39,6 +39,7 @@ from products.tasks.backend.models import (
)
from products.tasks.backend.redis import run_uses_dedicated_stream
from products.tasks.backend.temporal.constants import INACTIVITY_TIMEOUT_DEFAULT_SECONDS, resolve_inactivity_timeout
+from products.tasks.backend.temporal.metrics import increment_tool_call_only_heartbeat
from products.tasks.backend.temporal.process_task.utils import (
get_actor_distinct_id,
get_task_run_credential_user,
@@ -50,6 +51,7 @@ from ee.hogai.sandbox import is_turn_complete, turn_complete_trace_id
logger = structlog.get_logger(__name__)
HEARTBEAT_INTERVAL_SECONDS = 30
+TOOL_CALL_ONLY_HEARTBEAT_REPORT_SECONDS = 45 * 60
SSE_CONNECT_TIMEOUT_SECONDS = 30
SSE_READ_TIMEOUT_SECONDS = 300 # 5 min per chunk
MAX_RECONNECT_ATTEMPTS = 5
@@ -64,6 +66,8 @@ TERMINAL_NOTIFICATION_METHODS = frozenset(
}
)
+_TERMINAL_TOOL_CALL_STATUSES = frozenset({"completed", "failed"})
+
FINAL_MESSAGE_MAX_CHARS = 20_000
@@ -306,13 +310,20 @@ async def _background_heartbeat(
last_workflow_signal: list[float] | None = None,
agent_active: list[bool] | None = None,
inactivity_timeout_seconds: float = INACTIVITY_TIMEOUT_DEFAULT_SECONDS,
+ open_tool_calls: set[str] | None = None,
+ run_id: str | None = None,
) -> None:
"""Heartbeat to Temporal periodically, independent of event flow.
- Also signals the workflow heartbeat when events have been received
- recently and the inline mechanism hasn't signaled recently, preventing
- the inactivity timeout from firing while the agent is actively working.
+ Also signals the workflow heartbeat while the agent has work in flight,
+ preventing the inactivity timeout from firing during the event silence a
+ long-running tool call produces.
"""
+ # An empty set is falsy, so this must test for None: rebinding would detach the
+ # caller's set and leave the heartbeat blind to every later tool call.
+ if open_tool_calls is None:
+ open_tool_calls = set()
+ reported_long_tool_call = False
while not stop_event.is_set():
try:
await asyncio.wait_for(stop_event.wait(), timeout=HEARTBEAT_INTERVAL_SECONDS)
@@ -320,23 +331,44 @@ async def _background_heartbeat(
except TimeoutError:
activity.heartbeat()
now = time.monotonic()
+ if not open_tool_calls:
+ reported_long_tool_call = False
if workflow_handle is not None and _should_signal_workflow_heartbeat(
now=now,
last_event_time=last_event_time,
last_workflow_signal=last_workflow_signal,
agent_active=agent_active,
inactivity_timeout_seconds=inactivity_timeout_seconds,
+ open_tool_calls=open_tool_calls,
):
if last_workflow_signal is not None:
last_workflow_signal[0] = now
+ silence_seconds = now - last_event_time[0] if last_event_time is not None else 0.0
+ if (
+ open_tool_calls
+ and not reported_long_tool_call
+ and silence_seconds >= TOOL_CALL_ONLY_HEARTBEAT_REPORT_SECONDS
+ ):
+ reported_long_tool_call = True
+ logger.warning(
+ "relay_tool_call_only_heartbeat",
+ run_id=run_id,
+ silence_seconds=round(silence_seconds),
+ open_tool_calls=len(open_tool_calls),
+ )
+ increment_tool_call_only_heartbeat()
try:
await workflow_handle.signal(
- "heartbeat", arg=agent_active[0] if agent_active is not None else False
+ "heartbeat", arg=_agent_has_work_in_flight(agent_active, open_tool_calls)
)
except Exception as e:
logger.warning("relay_workflow_heartbeat_signal_failed", error=str(e))
+def _agent_has_work_in_flight(agent_active: list[bool] | None, open_tool_calls: set[str] | None) -> bool:
+ return bool((agent_active is not None and agent_active[0]) or open_tool_calls)
+
+
def _should_signal_workflow_heartbeat(
*,
now: float,
@@ -344,14 +376,17 @@ def _should_signal_workflow_heartbeat(
last_workflow_signal: list[float] | None,
agent_active: list[bool] | None,
inactivity_timeout_seconds: float,
+ open_tool_calls: set[str] | None = None,
) -> bool:
"""Gate for the periodic workflow keep-alive signal sent by _background_heartbeat."""
if last_event_time is None or last_event_time[0] <= 0:
return False
- if agent_active is not None and not agent_active[0]:
+ if not _agent_has_work_in_flight(agent_active, open_tool_calls):
return False
if last_workflow_signal is not None and (now - last_workflow_signal[0]) < HEARTBEAT_INTERVAL_SECONDS:
return False
+ if open_tool_calls:
+ return True
# The workflow starts a full inactivity timer after the final heartbeat.
# Subtract that timer so event silence never exceeds the larger idle window.
heartbeat_budget_seconds = (
@@ -402,6 +437,7 @@ async def _relay_loop(
# 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]
+ open_tool_calls: set[str] = set()
last_audit_ts_ns: list[int] = [0] # track last agentsh audit timestamp
# Brackets turn_started / turn_completed signals to the parent.
slack_turn_active: list[bool] = [False]
@@ -420,6 +456,8 @@ async def _relay_loop(
last_workflow_signal,
agent_active,
inactivity_timeout_seconds=inactivity_timeout_seconds,
+ open_tool_calls=open_tool_calls,
+ run_id=run_id,
)
)
@@ -484,9 +522,11 @@ async def _relay_loop(
last_event_time[0] = time.monotonic()
final_message_tracker.collect(event_data)
+ _track_tool_call(event_data, open_tool_calls)
if _is_end_of_turn(event_data):
agent_active[0] = False
+ open_tool_calls.clear()
if workflow_handle is not None:
await _signal_safely(workflow_handle, "agent_state_changed", arg=False)
if sandbox_id and background_logs_enabled:
@@ -549,7 +589,7 @@ async def _relay_loop(
now = time.monotonic()
if (
workflow_handle is not None
- and agent_active[0]
+ and _agent_has_work_in_flight(agent_active, open_tool_calls)
and (now - last_workflow_signal[0]) >= HEARTBEAT_INTERVAL_SECONDS
):
last_workflow_signal[0] = now
@@ -570,6 +610,7 @@ async def _relay_loop(
# declaring it gone; proxies and agent-server restarts can close a healthy stream.
reconnect_count += 1
agent_active[0] = False
+ open_tool_calls.clear()
pending_text_parts.clear()
final_message_tracker.reset()
logger.warning(
@@ -584,6 +625,7 @@ async def _relay_loop(
reconnect_count += 1
# May have missed an end_of_turn on the dropped stream — assume idle until re-confirmed.
agent_active[0] = False
+ open_tool_calls.clear()
# Drop un-flushed partial prose — the agent replays events on reconnect.
pending_text_parts.clear()
final_message_tracker.reset()
@@ -608,6 +650,7 @@ async def _relay_loop(
# 5xx — transient server error, worth retrying
reconnect_count += 1
agent_active[0] = False # missed-end_of_turn guard (see ReadTimeout above)
+ open_tool_calls.clear()
# Drop un-flushed partial prose — the agent replays events on reconnect.
pending_text_parts.clear()
final_message_tracker.reset()
@@ -623,6 +666,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)
+ open_tool_calls.clear()
# Drop un-flushed partial prose — the agent replays events on reconnect.
pending_text_parts.clear()
final_message_tracker.reset()
@@ -694,6 +738,32 @@ def _pi_conversation_event(event_data: dict) -> dict | None:
return event if isinstance(event, dict) else None
+def _track_tool_call(event_data: dict, open_tool_calls: set[str]) -> None:
+ """Maintain the set of tool calls the agent started and has not finished."""
+ pi_event = _pi_conversation_event(event_data)
+ if pi_event is not None:
+ tool_call = pi_event.get("toolCall")
+ if not isinstance(tool_call, dict):
+ return
+ kind, tool_call_id, status = pi_event.get("type"), tool_call.get("id"), tool_call.get("status")
+ started, updated = "tool_call_started", "tool_call_updated"
+ elif _is_session_update(event_data):
+ update = (event_data.get("notification", {}).get("params") or {}).get("update") or {}
+ kind, tool_call_id, status = update.get("sessionUpdate"), update.get("toolCallId"), update.get("status")
+ started, updated = "tool_call", "tool_call_update"
+ else:
+ return
+
+ if not isinstance(tool_call_id, str) or kind not in (started, updated):
+ return
+ # A start can already carry a terminal status — history replay and memory recall both
+ # emit one — and no later update follows it, so status decides before the event kind.
+ if status in _TERMINAL_TOOL_CALL_STATUSES:
+ open_tool_calls.discard(tool_call_id)
+ elif kind == started:
+ open_tool_calls.add(tool_call_id)
+
+
def _is_active_agent_update(event_data: dict) -> bool:
"""True only for events where the agent is actively generating."""
pi_event = _pi_conversation_event(event_data)
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 61062d041003..cb31036b1220 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
@@ -1,4 +1,5 @@
import json
+import time
import asyncio
import importlib
from types import SimpleNamespace
@@ -9,6 +10,7 @@ from unittest.mock import AsyncMock, MagicMock, call
import httpx
import httpx_sse
+import temporalio.client
from parameterized import parameterized
from temporalio.exceptions import ApplicationError
@@ -22,6 +24,7 @@ from products.tasks.backend.temporal.process_task.activities.relay_sandbox_event
FinalMessageTracker,
RelaySandboxEventsInput,
TaskRunRedisStream,
+ _background_heartbeat,
_flush_pending_text,
_is_active_agent_update,
_is_end_of_turn,
@@ -33,6 +36,7 @@ from products.tasks.backend.temporal.process_task.activities.relay_sandbox_event
_relay_loop,
_sanitize_httpx_error,
_should_signal_workflow_heartbeat,
+ _track_tool_call,
relay_sandbox_events,
)
from products.tasks.backend.temporal.process_task.workflow import (
@@ -181,6 +185,104 @@ class TestIsActiveAgentUpdate:
)
+def _pi(event_type: str, tool_call: object) -> dict:
+ return {"type": "pi_event", "event": {"type": event_type, "toolCall": tool_call}}
+
+
+def _acp(sub_type: str, update: dict) -> dict:
+ return {
+ "type": "notification",
+ "notification": {"method": "session/update", "params": {"update": {"sessionUpdate": sub_type, **update}}},
+ }
+
+
+class TestTrackToolCall:
+ @parameterized.expand(
+ [
+ ("pi_started_opens", [_pi("tool_call_started", {"id": "c1", "status": "pending"})], {"c1"}),
+ (
+ "pi_completed_closes",
+ [
+ _pi("tool_call_started", {"id": "c1", "status": "pending"}),
+ _pi("tool_call_updated", {"id": "c1", "status": "completed"}),
+ ],
+ set(),
+ ),
+ (
+ "pi_failed_closes",
+ [
+ _pi("tool_call_started", {"id": "c1", "status": "pending"}),
+ _pi("tool_call_updated", {"id": "c1", "status": "failed"}),
+ ],
+ set(),
+ ),
+ (
+ "pi_non_terminal_update_keeps_open",
+ [
+ _pi("tool_call_started", {"id": "c1", "status": "pending"}),
+ _pi("tool_call_updated", {"id": "c1", "status": "in_progress"}),
+ ],
+ {"c1"},
+ ),
+ (
+ "pi_repeated_start_is_one_entry",
+ [
+ _pi("tool_call_started", {"id": "c1", "status": "pending"}),
+ _pi("tool_call_started", {"id": "c1", "status": "pending"}),
+ ],
+ {"c1"},
+ ),
+ (
+ "pi_sibling_call_stays_open",
+ [
+ _pi("tool_call_started", {"id": "c1", "status": "pending"}),
+ _pi("tool_call_started", {"id": "c2", "status": "pending"}),
+ _pi("tool_call_updated", {"id": "c1", "status": "completed"}),
+ ],
+ {"c2"},
+ ),
+ ("acp_started_opens", [_acp("tool_call", {"toolCallId": "c1"})], {"c1"}),
+ (
+ "acp_completed_closes",
+ [
+ _acp("tool_call", {"toolCallId": "c1"}),
+ _acp("tool_call_update", {"toolCallId": "c1", "status": "completed"}),
+ ],
+ set(),
+ ),
+ (
+ "acp_non_terminal_update_keeps_open",
+ [
+ _acp("tool_call", {"toolCallId": "c1"}),
+ _acp("tool_call_update", {"toolCallId": "c1", "status": "in_progress"}),
+ ],
+ {"c1"},
+ ),
+ # History replay and memory recall emit a start that is already terminal, with no
+ # update to follow. Opening it would keep the run alive for the rest of the turn.
+ (
+ "acp_start_already_terminal_never_opens",
+ [_acp("tool_call", {"toolCallId": "c1", "status": "completed"})],
+ set(),
+ ),
+ (
+ "pi_start_already_terminal_never_opens",
+ [_pi("tool_call_started", {"id": "c1", "status": "failed"})],
+ set(),
+ ),
+ ("pi_missing_tool_call", [_pi("tool_call_started", None)], set()),
+ ("pi_non_string_id", [_pi("tool_call_started", {"id": 7})], set()),
+ ("acp_missing_id", [_acp("tool_call", {})], set()),
+ ("unrelated_event", [{"type": "notification", "notification": {"method": "_posthog/console"}}], set()),
+ ],
+ )
+ def test_open_tool_calls(self, _name: str, events: list[dict], expected: set[str]) -> None:
+ open_tool_calls: set[str] = set()
+ for event in events:
+ _track_tool_call(event, open_tool_calls)
+ assert open_tool_calls == expected
+
+
class TestIsKeepaliveEvent:
@parameterized.expand(
[
@@ -722,6 +824,84 @@ class TestRelaySandboxEventsErrorHandling:
redis_stream.release_first_agent_activity.assert_not_awaited()
assert redis_stream.claim_first_agent_activity.await_count == 2
+ @parameterized.expand(
+ [
+ ("unfinished_tool_call_stays_open", [_acp("tool_call", {"toolCallId": "c1"})], {"c1"}),
+ (
+ "terminal_status_closes",
+ [
+ _acp("tool_call", {"toolCallId": "c1"}),
+ _acp("tool_call_update", {"toolCallId": "c1", "status": "completed"}),
+ ],
+ set(),
+ ),
+ (
+ "end_of_turn_closes",
+ [
+ _acp("tool_call", {"toolCallId": "c1"}),
+ {"type": "notification", "notification": {"result": {"stopReason": "end_turn"}}},
+ ],
+ set(),
+ ),
+ ],
+ )
+ async def test_relay_loop_shares_open_tool_calls_with_the_heartbeat(
+ self,
+ _name: str,
+ events: list[dict],
+ expected: set[str],
+ ) -> None:
+ redis_stream = SimpleNamespace(
+ write_event=AsyncMock(),
+ mark_complete=AsyncMock(),
+ mark_error=AsyncMock(),
+ claim_first_agent_command=AsyncMock(return_value=False),
+ release_first_agent_command=AsyncMock(),
+ claim_first_agent_activity=AsyncMock(return_value=False),
+ release_first_agent_activity=AsyncMock(),
+ )
+ stream_events = [*events, {"type": "notification", "notification": {"method": "_posthog/task_complete"}}]
+
+ class SuccessfulEventSource:
+ response = SimpleNamespace(raise_for_status=lambda: None)
+
+ async def __aenter__(self) -> "SuccessfulEventSource":
+ return self
+
+ async def __aexit__(self, *_args: object) -> None:
+ return None
+
+ async def aiter_sse(self):
+ for event in stream_events:
+ yield SimpleNamespace(data=json.dumps(event))
+
+ handle = SimpleNamespace(signal=AsyncMock())
+ client = SimpleNamespace(get_workflow_handle=MagicMock(return_value=handle))
+ background_heartbeat = AsyncMock()
+
+ with pytest.MonkeyPatch.context() as monkeypatch:
+ monkeypatch.setattr(
+ relay_sandbox_events_module.httpx_sse,
+ "aconnect_sse",
+ lambda *_args, **_kwargs: SuccessfulEventSource(),
+ )
+ monkeypatch.setattr(relay_sandbox_events_module, "_background_heartbeat", background_heartbeat)
+ monkeypatch.setattr(
+ relay_sandbox_events_module.activity, "info", lambda: SimpleNamespace(workflow_id="workflow-1")
+ )
+ monkeypatch.setattr("posthog.temporal.common.client.async_connect", AsyncMock(return_value=client))
+
+ await _relay_loop(
+ events_url="https://sandbox.example/events",
+ headers={"Authorization": "Bearer token"},
+ params={},
+ redis_stream=cast(TaskRunRedisStream, redis_stream),
+ run_id="run-id",
+ task_id="task-id",
+ )
+
+ assert background_heartbeat.call_args.kwargs["open_tool_calls"] == expected
+
async def test_permission_request_dispatches_to_broker(self, monkeypatch: pytest.MonkeyPatch) -> None:
redis_stream = SimpleNamespace(
write_event=AsyncMock(),
@@ -1297,7 +1477,7 @@ class TestShouldSignalWorkflowHeartbeat:
[
# Loop runs carry a 2-minute idle window; a quiet in-flight turn past that
# window must still keep the workflow alive (the mid-turn teardown bug).
- ("mid_turn_quiet_past_short_run_window", True, 300.0, 120.0, True),
+ ("mid_turn_quiet_past_short_run_window", True, 300.0, 120.0, set(), True),
# Leave the workflow's short inactivity timer enough time to expire at
# the background default instead of after another full short window.
(
@@ -1305,15 +1485,20 @@ class TestShouldSignalWorkflowHeartbeat:
True,
float(INACTIVITY_TIMEOUT_DEFAULT_SECONDS) - 60.0,
120.0,
+ set(),
False,
),
# Idle after end_of_turn: the short loop window applies and the run winds down.
- ("idle_agent_stale_events", False, 300.0, 120.0, False),
- ("mid_turn_fresh_events", True, 30.0, 120.0, True),
- # Default and longer windows rely on the event-driven heartbeat, then
- # let their own inactivity timer measure the full silence window.
- ("mid_turn_default_window_uses_event_heartbeat", True, 30.0, 1800.0, False),
- ("mid_turn_long_window_uses_event_heartbeat", True, 30.0, 3600.0, False),
+ ("idle_agent_stale_events", False, 300.0, 120.0, set(), False),
+ ("mid_turn_fresh_events", True, 30.0, 120.0, set(), True),
+ # With no tool call in flight, the default and longer windows rely on the
+ # event-driven heartbeat, then let their own inactivity timer measure the
+ # full silence window.
+ ("mid_turn_default_window_uses_event_heartbeat", True, 30.0, 1800.0, set(), False),
+ ("mid_turn_long_window_uses_event_heartbeat", True, 30.0, 3600.0, set(), False),
+ # An unfinished tool call is evidence of work, so it keeps the run alive past
+ # the silence budget that reaped runs mid-subagent, whatever the window.
+ ("tool_call_in_flight_bypasses_budget", False, 1_500.0, 3600.0, {"call-1"}, True),
]
)
def test_freshness_gating(
@@ -1322,6 +1507,7 @@ class TestShouldSignalWorkflowHeartbeat:
agent_active: bool,
event_age_seconds: float,
inactivity_timeout_seconds: float,
+ open_tool_calls: set[str],
expected: bool,
) -> None:
now = 100_000.0
@@ -1332,6 +1518,7 @@ class TestShouldSignalWorkflowHeartbeat:
last_workflow_signal=[now - HEARTBEAT_INTERVAL_SECONDS - 1.0],
agent_active=[agent_active],
inactivity_timeout_seconds=inactivity_timeout_seconds,
+ open_tool_calls=open_tool_calls,
)
is expected
)
@@ -1360,3 +1547,36 @@ class TestShouldSignalWorkflowHeartbeat:
)
is expected
)
+
+
+class TestBackgroundHeartbeat:
+ async def test_signals_for_a_tool_call_opened_after_it_started(self) -> None:
+ # The relay hands over an empty set and fills it later, so the coroutine has to keep
+ # the caller's object. Rebinding it leaves the heartbeat blind for the whole run.
+ open_tool_calls: set[str] = set()
+ handle = SimpleNamespace(signal=AsyncMock())
+ stop_event = asyncio.Event()
+
+ with pytest.MonkeyPatch.context() as monkeypatch:
+ monkeypatch.setattr(relay_sandbox_events_module, "HEARTBEAT_INTERVAL_SECONDS", 0.01)
+ monkeypatch.setattr(relay_sandbox_events_module.activity, "heartbeat", lambda *_args: None)
+ heartbeat = asyncio.create_task(
+ _background_heartbeat(
+ stop_event,
+ cast(temporalio.client.WorkflowHandle, handle),
+ [time.monotonic() - 100.0],
+ [0.0],
+ [False],
+ inactivity_timeout_seconds=3600.0,
+ open_tool_calls=open_tool_calls,
+ )
+ )
+ # Let the coroutine reach its first await, so the set is still empty when it
+ # normalises its arguments. That is the moment a falsy check detaches it.
+ await asyncio.sleep(0)
+ open_tool_calls.add("call-1")
+ await asyncio.sleep(0.05)
+ stop_event.set()
+ await heartbeat
+
+ assert call("heartbeat", arg=True) in handle.signal.await_args_list