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): salvage agent turn when closing end_turn never arrives (#61903)

Andrew Maguiree0581987f5d9
diff --git a/products/tasks/backend/services/custom_prompt_internals.py b/products/tasks/backend/services/custom_prompt_internals.py
index 5a406f027a6a..e93fa603d23f 100644
--- a/products/tasks/backend/services/custom_prompt_internals.py
+++ b/products/tasks/backend/services/custom_prompt_internals.py
@@ -29,6 +29,12 @@ OutputFn = Callable[[str], object] | None
POLL_INTERVAL_SECONDS = 10
MAX_POLL_SECONDS = 30 * 60 # 30 minutes (matches sandbox TTL)
MAX_CONSECUTIVE_STORAGE_ERRORS = 3
+# After this many seconds of silence carrying the null-cost usage_update fingerprint, accept
+# the last message instead of polling to MAX_POLL_SECONDS and failing a run that completed.
+# Set to the relay's continuous-silence ceiling (relay_sandbox_events.py: MAX_RECONNECT_ATTEMPTS
+# * SSE_READ_TIMEOUT_SECONDS = 5 * 300) so we never cut off a turn the relay still treats as
+# active; past that the relay has given up and the run is terminal. Keep in sync if those change.
+STALE_TURN_SALVAGE_SECONDS = 1500
# Notification method the sandbox agent emits on a terminal failure. The agent
# classifies upstream failures (rate limits, stream/connection drops, provider
@@ -199,6 +205,23 @@ async def poll_for_turn(
total_lines=total_lines,
printed_lines=printed_lines,
)
+ # Salvage only the dropped-finalization case: we have the agent's final message, the
+ # log tail is the null-cost usage_update fingerprint, and it's been silent long enough
+ # to be conclusive. Requiring the tail (not just any cached text) keeps a mid-turn
+ # tool/model gap from being cut off early. See STALE_TURN_SALVAGE_SECONDS.
+ if (
+ latest_assistant_text is not None
+ and stale_seconds >= STALE_TURN_SALVAGE_SECONDS
+ and _ended_on_pending_finalization(full_log)
+ ):
+ logger.warning(
+ "custom_prompt - poll_for_turn: end_turn missing but turn-accounting tail present "
+ "and log stale for %ds — salvaging last message, run=%s total_lines=%d",
+ stale_seconds,
+ task_run.id,
+ total_lines,
+ )
+ return latest_assistant_text, full_log, total_lines, printed_lines
# Keep the cursor monotonic — S3 eventual-consistency can briefly return
# fewer lines than the prior poll; without the clamp we'd re-parse old lines.
skip_lines = max(skip_lines, total_lines)
@@ -448,6 +471,34 @@ def _check_logs(task_run, skip_lines: int = 0) -> tuple[bool, str | None, str |
return agent_finished, latest_text, log_content, total_lines, False
+def _ended_on_pending_finalization(full_log: str | None) -> bool:
+ """True when the log's last notification is a usage_update carrying an explicit null cost —
+ the sandbox ran turn accounting but the closing end_turn was dropped. The cost key must be
+ present and null: older usage_update lines omit it entirely and are not this fingerprint.
+ Any other trailing notification (an end_turn/result, a `_posthog/error`, a mid-turn update)
+ is decisive that this is not the dropped-finalization case, so we don't salvage and let the
+ normal completion / terminal-status drain handle it."""
+ if not full_log:
+ return False
+ for line in reversed(full_log.strip().split("\n")):
+ line = line.strip()
+ if not line:
+ continue
+ try:
+ notification = json.loads(line).get("notification")
+ except json.JSONDecodeError:
+ continue
+ if not isinstance(notification, dict):
+ continue
+ params = notification.get("params")
+ update = params.get("update") if isinstance(params, dict) else None
+ if not isinstance(update, dict):
+ # The last notification is a result/error/other — not a turn sitting on accounting.
+ return False
+ return update.get("sessionUpdate") == "usage_update" and "cost" in update and update["cost"] is None
+ return False
+
+
def _extract_text(update: dict) -> str | None:
content = update.get("content")
if isinstance(content, dict) and content.get("type") == "text" and isinstance(content.get("text"), str):
diff --git a/products/tasks/backend/tests/agent_log_fixtures.py b/products/tasks/backend/tests/agent_log_fixtures.py
index 723095463e11..bbc5a37a4b46 100644
--- a/products/tasks/backend/tests/agent_log_fixtures.py
+++ b/products/tasks/backend/tests/agent_log_fixtures.py
@@ -55,7 +55,9 @@ def _agent_error_line(message: str, category: str | None = None) -> str:
return json.dumps({"notification": {"method": "_posthog/error", "params": params}})
-def _usage_update_line(used: int = 1000) -> str:
+def _usage_update_line(used: int = 1000, cost: float | None = None) -> str:
+ # cost is null until the turn finalizes; an explicit null-cost tail with no end_turn is
+ # the dropped-finalization fingerprint poll_for_turn salvages on.
return json.dumps(
{
"notification": {
@@ -64,6 +66,7 @@ def _usage_update_line(used: int = 1000) -> str:
"update": {
"sessionUpdate": "usage_update",
"used": used,
+ "cost": cost,
}
},
}
@@ -71,6 +74,18 @@ def _usage_update_line(used: int = 1000) -> str:
)
+def _cost_less_usage_update_line(used: int = 1000) -> str:
+ # Older sandbox builds omit cost entirely — must NOT read as the null-cost fingerprint.
+ return json.dumps(
+ {
+ "notification": {
+ "method": "session/update",
+ "params": {"update": {"sessionUpdate": "usage_update", "used": used}},
+ }
+ }
+ )
+
+
@dataclass
class FakeTaskRun:
id: str = "run-1"
diff --git a/products/tasks/backend/tests/test_multi_turn_session.py b/products/tasks/backend/tests/test_multi_turn_session.py
index 85a0e386648e..6aa9331bd03d 100644
--- a/products/tasks/backend/tests/test_multi_turn_session.py
+++ b/products/tasks/backend/tests/test_multi_turn_session.py
@@ -25,6 +25,7 @@ from products.tasks.backend.tests.agent_log_fixtures import (
FakeTaskRun,
_agent_error_line,
_agent_message_line,
+ _cost_less_usage_update_line,
_end_turn_line,
_usage_update_line,
_user_message_line,
@@ -135,6 +136,84 @@ class TestPollForTurnEmptyEndTurn:
assert printed_lines == len(poll_3_lines)
+class TestPollForTurnStaleSalvage:
+ """When the sandbox SDK never emits the closing end_turn after the agent's final
+ message (an intermittent race — the turn's cost is left null and the log goes quiet),
+ poll_for_turn must salvage the last message once the log is conclusively stale rather
+ than polling until MAX_POLL_SECONDS and failing a run that actually completed."""
+
+ @pytest.mark.asyncio
+ async def test_salvages_last_message_when_end_turn_never_arrives(self):
+ # Agent's close-out message + a final usage_update, but no end_turn line — the
+ # exact shape of the prod failures (no result of any stopReason ever written).
+ log = "\n".join([_agent_message_line("close-out summary"), _usage_update_line(165000)])
+ fake = FakeTaskRun()
+ with (
+ patch("posthog.storage.object_storage.read", return_value=log),
+ patch("asyncio.sleep", new=AsyncMock()),
+ patch("products.tasks.backend.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 10),
+ patch("products.tasks.backend.services.custom_prompt_internals.STALE_TURN_SALVAGE_SECONDS", 30),
+ patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake),
+ ):
+ last_message, _, total_lines, _ = await poll_for_turn(fake, skip_lines=0)
+
+ assert last_message == "close-out summary"
+ assert total_lines == 2
+
+ @pytest.mark.asyncio
+ async def test_does_not_salvage_while_log_approaches_threshold(self):
+ # New lines arrive after 2 silent polls (stale climbs to 20, one poll short of the
+ # 30s threshold) and each tail carries the null-cost usage_update fingerprint. So the
+ # ONLY thing keeping this still-active turn from being salvaged is the staleness
+ # reset on each new line — it completes via its real end_turn, not the salvage path.
+ c1 = [_agent_message_line("working"), _usage_update_line()]
+ c2 = [*c1, _agent_message_line("still working"), _usage_update_line()]
+ final = [*c2, _agent_message_line("final answer"), _end_turn_line()]
+ logs = ["\n".join(c1)] * 3 + ["\n".join(c2)] * 3 + ["\n".join(final)]
+ poll_iter = iter(logs)
+
+ def next_log(*_args, **_kwargs):
+ return next(poll_iter, "\n".join(final))
+
+ fake = FakeTaskRun()
+ with (
+ patch("posthog.storage.object_storage.read", side_effect=next_log),
+ patch("asyncio.sleep", new=AsyncMock()),
+ patch("products.tasks.backend.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 10),
+ patch("products.tasks.backend.services.custom_prompt_internals.STALE_TURN_SALVAGE_SECONDS", 30),
+ patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake),
+ ):
+ last_message, _, total_lines, _ = await poll_for_turn(fake, skip_lines=0)
+
+ assert last_message == "final answer"
+ assert total_lines == len(final)
+
+ @parameterized.expand(
+ [
+ ("no_usage_update_tail", []),
+ ("populated_cost_tail", [_usage_update_line(1000, cost=0.42)]),
+ ("cost_key_absent", [_cost_less_usage_update_line()]),
+ ("error_after_usage_update", [_usage_update_line(), _agent_error_line("provider 500", "provider_error")]),
+ ]
+ )
+ async def test_does_not_salvage_without_finalization_fingerprint(self, _name, tail_lines):
+ # Agent message present and the log is long-stale, but the tail is not an explicit
+ # null-cost usage_update — a mid-turn gap, an old cost-less usage line, or a terminal
+ # error after accounting. None are the dropped-finalization case, so keep polling
+ # (here to the cap) rather than salvage an unfinished or failed turn.
+ log = "\n".join([_agent_message_line("intermediate"), *tail_lines])
+ fake = FakeTaskRun()
+ with (
+ patch("posthog.storage.object_storage.read", return_value=log),
+ patch("asyncio.sleep", new=AsyncMock()),
+ patch("products.tasks.backend.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 600),
+ patch("products.tasks.backend.services.custom_prompt_internals.STALE_TURN_SALVAGE_SECONDS", 30),
+ patch("products.tasks.backend.models.TaskRun.objects.get", return_value=fake),
+ ):
+ with pytest.raises(RuntimeError, match="timed out"):
+ await poll_for_turn(fake, skip_lines=0)
+
+
class TestPollForTurnTerminalDrain:
"""Terminal-status drain must recover an agent_message from *this* turn only.