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 a late heartbeat from reopening an ended turn (#100356)

posthog[bot]fb0435a33411
diff --git a/ee/hogai/sandbox/__init__.py b/ee/hogai/sandbox/__init__.py
index 6442452116c6..ccca8487aa51 100644
--- a/ee/hogai/sandbox/__init__.py
+++ b/ee/hogai/sandbox/__init__.py
@@ -1,3 +1,17 @@
-from ee.hogai.sandbox.types import STOP_REASON_END_TURN, TURN_COMPLETE_METHOD, is_turn_complete, turn_complete_trace_id
+from ee.hogai.sandbox.types import (
+ PI_RUNTIME_ERROR_MESSAGE,
+ STOP_REASON_END_TURN,
+ TURN_COMPLETE_METHOD,
+ is_turn_complete,
+ pi_turn_error,
+ turn_complete_trace_id,
+)
-__all__ = ["STOP_REASON_END_TURN", "TURN_COMPLETE_METHOD", "is_turn_complete", "turn_complete_trace_id"]
+__all__ = [
+ "PI_RUNTIME_ERROR_MESSAGE",
+ "STOP_REASON_END_TURN",
+ "TURN_COMPLETE_METHOD",
+ "is_turn_complete",
+ "pi_turn_error",
+ "turn_complete_trace_id",
+]
diff --git a/ee/hogai/sandbox/types.py b/ee/hogai/sandbox/types.py
index 3fe46cea76ac..208ac28628bd 100644
--- a/ee/hogai/sandbox/types.py
+++ b/ee/hogai/sandbox/types.py
@@ -14,13 +14,27 @@ TURN_COMPLETE_METHOD = "_posthog/turn_complete"
# Stop reasons
STOP_REASON_END_TURN = "end_turn"
+# pi agent event shapes
+PI_EVENT_TYPE = "pi_event"
+PI_TURN_COMPLETED_TYPE = "turn_completed"
+PI_STOP_REASON_ERROR = "error"
+
+PI_RUNTIME_ERROR_MESSAGE = "The agent stopped with a runtime error"
+
def is_turn_complete(event: dict) -> bool:
- """Check if an ACP event signals the agent finished a turn.
+ """Check if a sandbox event signals the agent finished a turn.
+
+ Matches the raw ACP prompt response (``result.stopReason == "end_turn"``), the synthetic
+ ``_posthog/turn_complete`` notification, and the pi-shaped ``turn_completed`` event. Every
+ plane that closes a turn shares this predicate, so a run ends on the same event everywhere.
- Matches both the raw ACP prompt response (``result.stopReason == "end_turn"``)
- and the synthetic ``_posthog/turn_complete`` notification.
+ True for a pi turn that ended in a runtime error too — the turn is over either way. Check
+ `pi_turn_error` to tell the two apart before treating this as a successful completion.
"""
+ if event.get("type") == PI_EVENT_TYPE:
+ pi_event = event.get("event")
+ return isinstance(pi_event, dict) and pi_event.get("type") == PI_TURN_COMPLETED_TYPE
if event.get("type") != ACP_NOTIFICATION_TYPE:
return False
notification = event.get("notification", {})
@@ -30,6 +44,21 @@ def is_turn_complete(event: dict) -> bool:
return isinstance(result, dict) and result.get("stopReason") == STOP_REASON_END_TURN
+def pi_turn_error(event: dict) -> bool:
+ """True when a pi ``turn_completed`` event reports a terminal runtime failure.
+
+ Pi keeps the same event shape for a normal end and a fatal error; only `stopReason`
+ tells them apart. A caller must check this before signalling `is_turn_complete` as a
+ successful completion, or a failed run gets recorded as one.
+ """
+ if event.get("type") != PI_EVENT_TYPE:
+ return False
+ pi_event = event.get("event")
+ if not isinstance(pi_event, dict) or pi_event.get("type") != PI_TURN_COMPLETED_TYPE:
+ return False
+ return pi_event.get("stopReason") == PI_STOP_REASON_ERROR
+
+
def turn_complete_trace_id(event: dict) -> str | None:
"""The finished turn's gateway trace id, when the agent reported one.
diff --git a/products/tasks/backend/agent_proxy_callback.py b/products/tasks/backend/agent_proxy_callback.py
index 0526fb6cd24b..dcde203390f9 100644
--- a/products/tasks/backend/agent_proxy_callback.py
+++ b/products/tasks/backend/agent_proxy_callback.py
@@ -8,6 +8,7 @@ from django.http import JsonResponse
from drf_spectacular.utils import OpenApiResponse, extend_schema
from jwt import PyJWTError
+from products.tasks.backend.facade.api import signal_workflow_completion
from products.tasks.backend.models import TaskRun
from products.tasks.backend.presentation.serializers import (
AgentProxyCallbackRequestSerializer,
@@ -16,6 +17,8 @@ from products.tasks.backend.presentation.serializers import (
)
from products.tasks.backend.push_dispatcher import notify_task_run_turn_completed
+from ee.hogai.sandbox import PI_RUNTIME_ERROR_MESSAGE
+
logger = logging.getLogger(__name__)
@@ -42,7 +45,7 @@ logger = logging.getLogger(__name__)
description=(
"Internal endpoint called by the standalone Node agent-proxy after accepting an ingest event "
"that requires a Django-side side effect. Dispatches a Temporal heartbeat, a boot milestone, "
- "or an awaiting-input mobile push notification depending on `kind`. "
+ "an awaiting-input mobile push notification, or a failed-run completion depending on `kind`. "
"Authenticated with the forwarded sandbox event ingest JWT plus the X-Agent-Proxy-Secret "
"shared secret (required outside local dev/test) — no session or API key involved. "
"Best-effort: always returns 200 when auth passes; side-effect failures are logged, not surfaced."
@@ -151,4 +154,14 @@ def agent_proxy_callback(request, run_id: str) -> JsonResponse:
except Exception:
logger.exception("agent_proxy_callback.awaiting_input_failed", extra={"run_id": run_id})
+ elif kind == "turn_failed":
+ try:
+ if TaskRun.objects.filter(id=run_id, task_id=task_id, team_id=team_id).exists():
+ signal_workflow_completion(run_id, "failed", PI_RUNTIME_ERROR_MESSAGE)
+ dispatched = True
+ else:
+ logger.warning("agent_proxy_callback.run_not_found", extra={"run_id": run_id})
+ except Exception:
+ logger.exception("agent_proxy_callback.turn_failed_failed", extra={"run_id": run_id})
+
return JsonResponse(AgentProxyCallbackResponseSerializer({"dispatched": dispatched}).data)
diff --git a/products/tasks/backend/logic/stream/event_ingest.py b/products/tasks/backend/logic/stream/event_ingest.py
index 3454c3c21535..730aaae15814 100644
--- a/products/tasks/backend/logic/stream/event_ingest.py
+++ b/products/tasks/backend/logic/stream/event_ingest.py
@@ -17,6 +17,7 @@ from jwt import PyJWTError
from posthog.ph_client import ph_scoped_capture
+from products.tasks.backend.facade.api import signal_workflow_completion
from products.tasks.backend.logic.services.connection_token import (
SandboxEventIngestTokenPayload,
validate_sandbox_event_ingest_token,
@@ -33,7 +34,7 @@ from products.tasks.backend.metrics import observe_stream_write_skipped
from products.tasks.backend.models import TaskRun
from products.tasks.backend.push_dispatcher import notify_task_run_turn_completed
-from ee.hogai.sandbox import is_turn_complete
+from ee.hogai.sandbox import PI_RUNTIME_ERROR_MESSAGE, is_turn_complete, pi_turn_error
logger = structlog.get_logger(__name__)
@@ -394,7 +395,10 @@ async def _heartbeat_workflow_if_needed(redis_stream: TaskRunRedisStream, run_id
if is_turn_complete(event):
await redis_stream.set_agent_active(False)
- await _dispatch_turn_completed(run_id)
+ if pi_turn_error(event):
+ await _dispatch_turn_failed(run_id)
+ else:
+ await _dispatch_turn_completed(run_id)
return
if _is_session_update(event):
@@ -466,6 +470,17 @@ def _dispatch_turn_completed_sync(run_id: str) -> None:
notify_task_run_turn_completed(task_run)
+async def _dispatch_turn_failed(run_id: str) -> None:
+ await sync_to_async(_dispatch_turn_failed_sync, thread_sensitive=True)(run_id)
+
+
+def _dispatch_turn_failed_sync(run_id: str) -> None:
+ if not settings.TEST:
+ close_old_connections()
+
+ signal_workflow_completion(run_id, "failed", PI_RUNTIME_ERROR_MESSAGE)
+
+
def _is_session_update(event: dict) -> bool:
if event.get("type") != "notification":
return False
diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.py
index 7758e2524ff2..046cdaca8793 100644
--- a/products/tasks/backend/presentation/serializers.py
+++ b/products/tasks/backend/presentation/serializers.py
@@ -4511,11 +4511,12 @@ class AgentProxyCallbackRequestSerializer(serializers.Serializer):
"""
kind = serializers.ChoiceField(
- choices=["heartbeat", "awaiting_input", "command_dispatched", "agent_activity"],
+ choices=["heartbeat", "awaiting_input", "turn_failed", "command_dispatched", "agent_activity"],
help_text=(
"Side effect to dispatch. 'heartbeat' signals the Temporal workflow to reset its "
"inactivity timer. 'awaiting_input' fires a mobile push notification when an "
- "interactive run finishes a turn and is waiting for user input. 'command_dispatched' "
+ "interactive run finishes a turn and is waiting for user input. 'turn_failed' fails "
+ "the run outright when a pi turn ends in a runtime error. 'command_dispatched' "
"and 'agent_activity' record boot milestones."
),
)
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 ac0404dd8740..221a45ccb1d1 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
@@ -46,7 +46,7 @@ from products.tasks.backend.temporal.process_task.utils import (
is_slack_interaction_state,
)
-from ee.hogai.sandbox import is_turn_complete, turn_complete_trace_id
+from ee.hogai.sandbox import PI_RUNTIME_ERROR_MESSAGE, is_turn_complete, pi_turn_error, turn_complete_trace_id
logger = structlog.get_logger(__name__)
@@ -524,19 +524,33 @@ async def _relay_loop(
final_message_tracker.collect(event_data)
_track_tool_call(event_data, open_tool_calls)
- if _is_end_of_turn(event_data):
+ if is_turn_complete(event_data):
+ turn_failed = pi_turn_error(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 turn_failed:
+ # A pi runtime error ends the turn but is not a
+ # successful completion — fail the run outright rather
+ # than reporting the turn as answered.
+ await _signal_safely(
+ workflow_handle, "complete_task", args=["failed", PI_RUNTIME_ERROR_MESSAGE]
+ )
+ else:
+ await _signal_safely(workflow_handle, "agent_state_changed", arg=False)
if sandbox_id and background_logs_enabled:
asyncio.create_task(_emit_agentsh_events(sandbox_id, run_id, last_audit_ts_ns))
- if task_run is not None and task_run.mode == "interactive":
+ if not turn_failed and task_run is not None and task_run.mode == "interactive":
# Hop off the event loop because the turn-completion dispatcher
# performs sync Redis I/O and a potential network call to
# the feature-flag service.
asyncio.create_task(asyncio.to_thread(_safe_dispatch_turn_completed, task_run))
- if is_agent_design_enabled and slack_turn_active[0] and workflow_handle is not None:
+ if (
+ not turn_failed
+ and is_agent_design_enabled
+ and slack_turn_active[0]
+ and workflow_handle is not None
+ ):
slack_turn_active[0] = False
# Awaited in order: the final prose must be recorded before
# turn_completed, which clears the parent's relay id and would
@@ -904,10 +918,13 @@ async def _signal_safely(
workflow_handle: temporalio.client.WorkflowHandle,
signal_name: str,
arg: Any = None,
+ args: list[Any] | None = None,
) -> bool:
"""Fire-and-forget signal — failures must never break the relay loop."""
try:
- if arg is None:
+ if args is not None:
+ await workflow_handle.signal(signal_name, args=args)
+ elif arg is None:
await workflow_handle.signal(signal_name)
else:
await workflow_handle.signal(signal_name, arg=arg)
@@ -921,13 +938,6 @@ def _is_keepalive_event(event_data: dict) -> bool:
return event_data.get("type") == "keepalive"
-def _is_end_of_turn(event_data: dict) -> bool:
- pi_event = _pi_conversation_event(event_data)
- if pi_event is not None:
- return pi_event.get("type") == "turn_completed"
- return is_turn_complete(event_data)
-
-
async def _emit_agentsh_events(sandbox_id: str, run_id: str, last_ts_ns: list[int]) -> None:
"""Read recent agentsh network events and emit as debug console logs."""
from products.tasks.backend.logic.services.agentsh import build_audit_query_command
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 cb31036b1220..121d6d5ffe50 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
@@ -27,7 +27,6 @@ from products.tasks.backend.temporal.process_task.activities.relay_sandbox_event
_background_heartbeat,
_flush_pending_text,
_is_active_agent_update,
- _is_end_of_turn,
_is_keepalive_event,
_is_session_update,
_mark_error_unless_run_is_terminal,
@@ -44,14 +43,14 @@ from products.tasks.backend.temporal.process_task.workflow import (
ProcessTaskWorkflow,
)
-from ee.hogai.sandbox import TURN_COMPLETE_METHOD
+from ee.hogai.sandbox import PI_RUNTIME_ERROR_MESSAGE, TURN_COMPLETE_METHOD, is_turn_complete, pi_turn_error
relay_sandbox_events_module = importlib.import_module(
"products.tasks.backend.temporal.process_task.activities.relay_sandbox_events"
)
-class TestIsEndOfTurn:
+class TestIsTurnComplete:
@parameterized.expand(
[
(
@@ -79,10 +78,44 @@ class TestIsEndOfTurn:
{"type": "pi_event", "event": {"type": "turn_completed"}},
True,
),
+ (
+ "pi_turn_complete_with_a_runtime_error",
+ {"type": "pi_event", "event": {"type": "turn_completed", "stopReason": "error"}},
+ True,
+ ),
+ ]
+ )
+ def test_is_turn_complete(self, _name: str, event_data: dict, expected: bool):
+ assert is_turn_complete(event_data) == expected
+
+
+class TestPiTurnError:
+ @parameterized.expand(
+ [
+ (
+ "normal_pi_turn_complete",
+ {"type": "pi_event", "event": {"type": "turn_completed"}},
+ False,
+ ),
+ (
+ "pi_turn_complete_with_a_runtime_error",
+ {"type": "pi_event", "event": {"type": "turn_completed", "stopReason": "error"}},
+ True,
+ ),
+ (
+ "pi_turn_complete_with_a_non_error_stop_reason",
+ {"type": "pi_event", "event": {"type": "turn_completed", "stopReason": "cancelled"}},
+ False,
+ ),
+ (
+ "acp_end_turn_is_not_a_pi_error",
+ {"type": "notification", "notification": {"result": {"stopReason": "error"}}},
+ False,
+ ),
]
)
- def test_is_end_of_turn(self, _name: str, event_data: dict, expected: bool):
- assert _is_end_of_turn(event_data) == expected
+ def test_pi_turn_error(self, _name: str, event_data: dict, expected: bool):
+ assert pi_turn_error(event_data) == expected
class TestIsSessionUpdate:
@@ -329,7 +362,7 @@ class TestAgentActiveReactivation:
def _simulate_reactivation(event_data: dict, agent_active: bool) -> bool:
"""Replicate the inline re-activation logic from _relay_loop."""
active = [agent_active]
- if _is_end_of_turn(event_data):
+ if is_turn_complete(event_data):
active[0] = False
elif not active[0] and _is_session_update(event_data):
active[0] = True
@@ -360,7 +393,7 @@ class TestAgentActiveReactivation:
# Agent finishes turn
end_turn = {"type": "notification", "notification": {"result": {"stopReason": "end_turn"}}}
- if _is_end_of_turn(end_turn):
+ if is_turn_complete(end_turn):
active[0] = False
assert active[0] is False
@@ -824,6 +857,60 @@ class TestRelaySandboxEventsErrorHandling:
redis_stream.release_first_agent_activity.assert_not_awaited()
assert redis_stream.claim_first_agent_activity.await_count == 2
+ async def test_relay_fails_the_run_instead_of_completing_it_on_a_pi_runtime_error(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> 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(),
+ )
+ events = [
+ {"type": "pi_event", "event": {"type": "turn_completed", "stopReason": "error"}},
+ {"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 events:
+ yield SimpleNamespace(data=json.dumps(event))
+
+ handle = SimpleNamespace(signal=AsyncMock())
+ client = SimpleNamespace(get_workflow_handle=MagicMock(return_value=handle))
+
+ monkeypatch.setattr(
+ relay_sandbox_events_module.httpx_sse, "aconnect_sse", lambda *_args, **_kwargs: SuccessfulEventSource()
+ )
+ monkeypatch.setattr(relay_sandbox_events_module, "_background_heartbeat", AsyncMock())
+ 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 call("complete_task", args=["failed", PI_RUNTIME_ERROR_MESSAGE]) in handle.signal.await_args_list
+ assert call("agent_state_changed", arg=False) not in handle.signal.await_args_list
+
@parameterized.expand(
[
("unfinished_tool_call_stays_open", [_acp("tool_call", {"toolCallId": "c1"})], {"c1"}),
diff --git a/products/tasks/backend/temporal/process_task/tests/test_workflow.py b/products/tasks/backend/temporal/process_task/tests/test_workflow.py
index 7d351fa03c68..275dbaae7180 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_workflow.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_workflow.py
@@ -1745,6 +1745,29 @@ class TestProcessTaskWorkflowUnit:
await workflow._wait_for_task_external_event() == process_task_workflow_module.TaskEvent.SIGNAL_RECEIVED
)
+ async def test_a_late_heartbeat_does_not_reopen_an_ended_turn(self, monkeypatch):
+ workflow = ProcessTaskWorkflow()
+ workflow._context = _build_context(github_integration_id=123)
+ monkeypatch.setattr(process_task_workflow_module.workflow, "wait_condition", AsyncMock())
+ monkeypatch.setattr(process_task_workflow_module.workflow, "now", Mock(return_value=datetime.now(UTC)))
+
+ await workflow.agent_state_changed(False)
+ await workflow.heartbeat(agent_active=True)
+
+ assert workflow._end_of_turn_received is True
+ assert workflow._agent_lost_mid_turn() is False
+
+ @pytest.mark.parametrize(
+ "agent_active, expected",
+ [(True, True), (None, True), (False, False)],
+ )
+ async def test_an_open_turn_is_a_lost_agent_only_with_evidence(self, agent_active, expected):
+ workflow = ProcessTaskWorkflow()
+ workflow._end_of_turn_received = False
+ workflow._agent_active = agent_active
+
+ assert workflow._agent_lost_mid_turn() is expected
+
@pytest.mark.parametrize(
"outcome, expected",
[(None, False), (STEER_DECLINED_OUTCOME, True), (RuntimeError("Sandbox session is dead"), True)],
@@ -1753,6 +1776,9 @@ class TestProcessTaskWorkflowUnit:
workflow = ProcessTaskWorkflow()
workflow._context = _build_context(github_integration_id=123)
workflow._end_of_turn_received = True
+ # Stale evidence from the turn that just closed — a second turn opening on an
+ # ingest-only run must not inherit it, or a lost agent later this turn is hidden.
+ workflow._agent_active = False
monkeypatch.setattr(process_task_workflow_module.workflow, "logger", Mock())
monkeypatch.setattr(process_task_workflow_module.workflow, "patched", Mock(return_value=True))
monkeypatch.setattr(process_task_workflow_module.workflow, "uuid4", Mock(return_value="uuid"))
@@ -1763,6 +1789,7 @@ class TestProcessTaskWorkflowUnit:
await workflow._send_followup_to_sandbox("go", [])
assert workflow._end_of_turn_received is expected
+ assert workflow._agent_active is (None if outcome is None else False)
async def test_credential_refresh_exit_marks_sandbox_gone(self, monkeypatch):
workflow = ProcessTaskWorkflow()
diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.py
index 51bd5dc19b65..bde714c86d95 100644
--- a/products/tasks/backend/temporal/process_task/workflow.py
+++ b/products/tasks/backend/temporal/process_task/workflow.py
@@ -1519,8 +1519,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):
# A run that outlived the hard cap is a failure, not a completion, and the
# state marker carries the reason so error_message stays empty.
await self._update_task_run_status("failed", timeout_marker=TIMED_OUT_WALL_CLOCK_STATE_KEY)
- elif timeout_event is not None and self._end_of_turn_received is False:
- # A turn still open at the timeout means the agent died, not that it finished.
+ elif timeout_event is not None and self._agent_lost_mid_turn():
await self._update_task_run_status(
"failed", error_message=AGENT_LOST_ERROR_MESSAGE, timed_out_inactivity=True
)
@@ -2783,10 +2782,18 @@ class ProcessTaskWorkflow(PostHogWorkflow):
return False
return not self.context.create_pr or self._ci_repetitions > 0
+ def _agent_lost_mid_turn(self) -> bool:
+ """True only when an open turn is backed by evidence the agent was still working.
+
+ `agent_state_changed(False)` is the only report that a turn ended, so a run that sent
+ one has finished even if a later signal reopened the turn.
+ """
+ return self._end_of_turn_received is False and self._agent_active is not False
+
def _mark_sandbox_gone(self) -> None:
# A sandbox that vanished mid-turn took the agent's work with it. Mid-setup it is a failed
# setup for onboarding; see _onboarding_exit_is_failure for the open-PR exemption.
- agent_lost = self._end_of_turn_received is False
+ agent_lost = self._agent_lost_mid_turn()
self._completion_status = "failed" if agent_lost or self._onboarding_exit_is_failure() else "completed"
self._completion_error = SANDBOX_GONE_ERROR_MESSAGE
self._completion_timeout_marker = SANDBOX_GONE_STATE_KEY
@@ -3279,7 +3286,6 @@ class ProcessTaskWorkflow(PostHogWorkflow):
self._heartbeat_received = True
self._last_active_time = now
self._last_agent_heartbeat_at = now
- self._end_of_turn_received = False
@temporalio.workflow.signal
async def client_activity(self) -> None:
@@ -3492,6 +3498,10 @@ class ProcessTaskWorkflow(PostHogWorkflow):
# A delivered message opens a turn: the first heartbeat may lag or be throttled away.
if outcome != STEER_DECLINED_OUTCOME and _turn_opens_on_dispatch():
self._end_of_turn_received = False
+ # The ingest plane never reports a turn active, only inactive at its close, so a
+ # stale `False` from the turn that just ended must not carry into this one — it
+ # would permanently hide a lost agent for every later turn of the run.
+ self._agent_active = None
return outcome
except Exception as e:
error_properties = self._activity_error_properties(e)
diff --git a/products/tasks/backend/tests/test_agent_proxy_callback.py b/products/tasks/backend/tests/test_agent_proxy_callback.py
index b331f70850ab..e4d862813d94 100644
--- a/products/tasks/backend/tests/test_agent_proxy_callback.py
+++ b/products/tasks/backend/tests/test_agent_proxy_callback.py
@@ -16,6 +16,8 @@ from products.tasks.backend.logic.services.connection_token import (
from products.tasks.backend.models import Task, TaskRun
from products.tasks.backend.tests.test_api import TEST_RSA_PRIVATE_KEY
+from ee.hogai.sandbox import PI_RUNTIME_ERROR_MESSAGE
+
@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
class TestAgentProxyCallback(TestCase):
@@ -181,6 +183,28 @@ class TestAgentProxyCallback(TestCase):
notify.assert_not_called()
signal_turn_completed.assert_called_once()
+ def test_turn_failed_signals_workflow_completion_as_failed(self) -> None:
+ with patch(
+ "products.tasks.backend.agent_proxy_callback.signal_workflow_completion"
+ ) as signal_workflow_completion:
+ response = self._post(self._body(kind="turn_failed", agent_active=False), token=self._token())
+ self.assertEqual(response.status_code, 200)
+ self.assertTrue(response.json()["dispatched"])
+ signal_workflow_completion.assert_called_once_with(str(self.task_run.id), "failed", PI_RUNTIME_ERROR_MESSAGE)
+
+ def test_turn_failed_not_dispatched_for_unknown_run(self) -> None:
+ run = self.task.create_run()
+ run_id = str(run.id)
+ token = self._token(run)
+ TaskRun.objects.filter(id=run_id).delete()
+ with patch(
+ "products.tasks.backend.agent_proxy_callback.signal_workflow_completion"
+ ) as signal_workflow_completion:
+ response = self._post(self._body(kind="turn_failed", agent_active=False), token=token, run_id=run_id)
+ self.assertEqual(response.status_code, 200)
+ self.assertFalse(response.json()["dispatched"])
+ signal_workflow_completion.assert_not_called()
+
def test_unknown_run_returns_200_not_dispatched(self) -> None:
run = self.task.create_run()
run_id = str(run.id)
diff --git a/products/tasks/backend/tests/test_event_ingest.py b/products/tasks/backend/tests/test_event_ingest.py
index b5e18db390b3..ef420ab679d8 100644
--- a/products/tasks/backend/tests/test_event_ingest.py
+++ b/products/tasks/backend/tests/test_event_ingest.py
@@ -40,6 +40,8 @@ from products.tasks.backend.logic.stream.redis_stream import (
from products.tasks.backend.models import Task, TaskRun
from products.tasks.backend.tests.test_api import TEST_RSA_PRIVATE_KEY
+from ee.hogai.sandbox import PI_RUNTIME_ERROR_MESSAGE
+
SKIP_COUNTER_SAMPLE = "posthog_tasks_task_run_stream_write_skipped_total"
@@ -420,17 +422,40 @@ class TestTaskRunEventIngest(TestCase):
notify_turn_completed.assert_called_once()
self.assertEqual(notify_turn_completed.call_args.args[0].id, self.task_run.id)
- def test_turn_complete_ingest_signals_the_workflow_for_a_background_run(self) -> None:
+ @parameterized.expand(
+ [
+ ("acp", {"type": "notification", "notification": {"method": "_posthog/turn_complete"}}),
+ ("pi", {"type": "pi_event", "event": {"type": "turn_completed"}}),
+ ]
+ )
+ @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
+ def test_turn_complete_ingest_signals_the_workflow_for_a_background_run(self, _name: str, event: dict) -> None:
token = self._create_token()
with patch.object(TaskRun, "signal_agent_turn_completed") as signal_turn_completed:
+ status, _ = self._call_ingest(token, [{"seq": 1, "event": event}])
+
+ self.assertEqual(status, 200)
+ signal_turn_completed.assert_called_once()
+
+ @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
+ def test_pi_turn_completed_with_a_runtime_error_fails_the_run_instead_of_completing_it(self) -> None:
+ token = self._create_token()
+
+ with (
+ patch.object(TaskRun, "signal_agent_turn_completed") as signal_turn_completed,
+ patch(
+ "products.tasks.backend.logic.stream.event_ingest.signal_workflow_completion"
+ ) as signal_workflow_completion,
+ ):
status, _ = self._call_ingest(
token,
- [{"seq": 1, "event": {"type": "notification", "notification": {"method": "_posthog/turn_complete"}}}],
+ [{"seq": 1, "event": {"type": "pi_event", "event": {"type": "turn_completed", "stopReason": "error"}}}],
)
self.assertEqual(status, 200)
- signal_turn_completed.assert_called_once()
+ signal_turn_completed.assert_not_called()
+ signal_workflow_completion.assert_called_once_with(str(self.task_run.id), "failed", PI_RUNTIME_ERROR_MESSAGE)
@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
def test_workflow_heartbeat_does_not_block_event_loop(self) -> None:
diff --git a/services/agent-proxy/src/lib/side-effects.ts b/services/agent-proxy/src/lib/side-effects.ts
index 62797aff60c0..7040272ffc2f 100644
--- a/services/agent-proxy/src/lib/side-effects.ts
+++ b/services/agent-proxy/src/lib/side-effects.ts
@@ -37,10 +37,33 @@ const PI_GENERATION_EVENTS = new Set([
'tool_call_updated',
])
+// pi agent event shapes (byte-identical to ee/hogai/sandbox/types.py)
+const PI_EVENT_TYPE = 'pi_event'
+const PI_TURN_COMPLETED_TYPE = 'turn_completed'
+const PI_STOP_REASON_ERROR = 'error'
+
+function asPiTurnCompletedEvent(event: Record<string, unknown>): Record<string, unknown> | null {
+ if (event['type'] !== PI_EVENT_TYPE) {
+ return null
+ }
+ const piEvent = event['event']
+ if (typeof piEvent !== 'object' || piEvent === null) {
+ return null
+ }
+ const inner = piEvent as Record<string, unknown>
+ return inner['type'] === PI_TURN_COMPLETED_TYPE ? inner : null
+}
+
// isTurnComplete mirrors ee/hogai/sandbox/types.py:is_turn_complete exactly.
-// Matches both the raw ACP prompt response (result.stopReason == "end_turn")
-// and the synthetic _posthog/turn_complete notification.
+// Matches the raw ACP prompt response (result.stopReason == "end_turn"), the synthetic
+// _posthog/turn_complete notification, and the pi-shaped turn_completed event.
+//
+// True for a pi turn that ended in a runtime error too — the turn is over either way. Check
+// isPiTurnError to tell the two apart before treating this as a successful completion.
export function isTurnComplete(event: Record<string, unknown>): boolean {
+ if (event['type'] === PI_EVENT_TYPE) {
+ return asPiTurnCompletedEvent(event) !== null
+ }
if (event['type'] !== ACP_NOTIFICATION_TYPE) {
return false
}
@@ -60,6 +83,14 @@ export function isTurnComplete(event: Record<string, unknown>): boolean {
)
}
+// isPiTurnError mirrors ee/hogai/sandbox/types.py:pi_turn_error exactly.
+// True when a pi turn_completed event reports a terminal runtime failure, so the caller
+// can route it to a failed run instead of a successful turn completion.
+export function isPiTurnError(event: Record<string, unknown>): boolean {
+ const piTurnCompleted = asPiTurnCompletedEvent(event)
+ return piTurnCompleted !== null && piTurnCompleted['stopReason'] === PI_STOP_REASON_ERROR
+}
+
// isSessionUpdate mirrors event_ingest.py:_is_session_update exactly.
export function isSessionUpdate(event: Record<string, unknown>): boolean {
if (event['type'] !== ACP_NOTIFICATION_TYPE) {
@@ -111,7 +142,7 @@ export function isAgentGenerationEvent(event: Record<string, unknown>): boolean
const CALLBACK_TIMEOUT_MS = 10_000
const RETRY_DELAY_MS = 1000
-const RETRYABLE_KINDS: ReadonlySet<SideEffectKind> = new Set(['awaiting_input'])
+const RETRYABLE_KINDS: ReadonlySet<SideEffectKind> = new Set(['awaiting_input', 'turn_failed'])
function fetchErrorCode(err: unknown): string | undefined {
if (!(err instanceof Error)) {
@@ -227,7 +258,8 @@ async function releaseMilestoneClaim(
// and mirrors event_ingest.py:_heartbeat_workflow_if_needed exactly.
//
// Decision tree:
-// 1. isTurnComplete -> setAgentActive(false), fire awaiting_input callback, return.
+// 1. isTurnComplete -> setAgentActive(false), fire awaiting_input callback (or turn_failed
+// for a pi runtime error), return.
// 2. isSessionUpdate -> setAgentActive(true), set agentActive=true.
// 3. else -> agentActive = getAgentActive().
// 4. if !agentActive -> return.
@@ -257,9 +289,15 @@ export async function heartbeatWorkflowIfNeeded(
if (isTurnComplete(event)) {
await redisStream.setAgentActive(false)
- // Let Django decide whether the run is interactive; it will only
- // dispatch the push notification for interactive mode runs.
- fireCallback(runId, 'awaiting_input', false, taskId, teamId, originalToken, config)
+ if (isPiTurnError(event)) {
+ // A pi runtime error ends the turn but is not a successful completion —
+ // fail the run outright rather than reporting the turn as answered.
+ fireCallback(runId, 'turn_failed', false, taskId, teamId, originalToken, config)
+ } else {
+ // Let Django decide whether the run is interactive; it will only
+ // dispatch the push notification for interactive mode runs.
+ fireCallback(runId, 'awaiting_input', false, taskId, teamId, originalToken, config)
+ }
return
}
diff --git a/services/agent-proxy/src/lib/types.ts b/services/agent-proxy/src/lib/types.ts
index 2c285d48fb4c..159a757049e6 100644
--- a/services/agent-proxy/src/lib/types.ts
+++ b/services/agent-proxy/src/lib/types.ts
@@ -163,7 +163,7 @@ export type IngestLine = IngestEventLine | IngestCompleteLine
// Side-effect callback kind (matches Python callback contract in docs/DESIGN.md)
// ---------------------------------------------------------------------------
-export type SideEffectKind = 'heartbeat' | 'awaiting_input' | 'command_dispatched' | 'agent_activity'
+export type SideEffectKind = 'heartbeat' | 'awaiting_input' | 'turn_failed' | 'command_dispatched' | 'agent_activity'
// ---------------------------------------------------------------------------
// TaskRunRedisStream method interface
diff --git a/services/agent-proxy/tests/hono/ingest-handler.test.ts b/services/agent-proxy/tests/hono/ingest-handler.test.ts
index 7170bb8f8d37..5f66376cd5a8 100644
--- a/services/agent-proxy/tests/hono/ingest-handler.test.ts
+++ b/services/agent-proxy/tests/hono/ingest-handler.test.ts
@@ -1348,7 +1348,33 @@ describe('ingest-handler', () => {
global.fetch = originalFetch
})
+ it.each([
+ ['a normal pi turn_completed', { type: 'pi_event', event: { type: 'turn_completed' } }, 'awaiting_input'],
+ [
+ 'a pi turn_completed with stopReason "error"',
+ { type: 'pi_event', event: { type: 'turn_completed', stopReason: 'error' } },
+ 'turn_failed',
+ ],
+ ])('fires %s as %s', async (_label, event, expectedKind) => {
+ const fired: { kind: string }[] = []
+ const originalFetch = global.fetch
+ global.fetch = vi.fn(async (_, init) => {
+ fired.push(JSON.parse(String((init as RequestInit).body)))
+ return new Response('', { status: 200 })
+ }) as typeof fetch
+
+ const config = makeConfig({ djangoCallbackBaseUrl: 'http://django' })
+ await heartbeatWorkflowIfNeeded(redisStream, RUN_ID, event, TASK_ID, TEAM_ID, 'tok', config)
+
+ expect(await redisStream.getAgentActive()).toBe(false)
+ await new Promise((r) => setTimeout(r, 0))
+ expect(fired.some((f) => f.kind === expectedKind)).toBe(true)
+
+ global.fetch = originalFetch
+ })
+
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 networkFailure = Object.assign(new TypeError('fetch failed'), { cause: { code: 'ECONNRESET' } })
@@ -1356,6 +1382,8 @@ describe('ingest-handler', () => {
['awaiting_input', turnComplete, 'network failure', networkFailure, 2],
['awaiting_input', turnComplete, '503', new Response('', { status: 503 }), 2],
['awaiting_input', turnComplete, '400', new Response('', { status: 400 }), 1],
+ ['turn_failed', piTurnError, 'network failure', networkFailure, 2],
+ ['turn_failed', piTurnError, '503', new Response('', { status: 503 }), 2],
['heartbeat', sessionUpdate, 'network failure', networkFailure, 1],
['heartbeat', sessionUpdate, '503', new Response('', { status: 503 }), 1],
])(