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 dropped-finalization turns past trailing relay logs (#63481)

Andrew Maguired3595e228ad3
diff --git a/products/tasks/backend/services/custom_prompt_internals.py b/products/tasks/backend/services/custom_prompt_internals.py
index bff85020d378..5644621b04c2 100644
--- a/products/tasks/backend/services/custom_prompt_internals.py
+++ b/products/tasks/backend/services/custom_prompt_internals.py
@@ -46,6 +46,19 @@ STALE_TURN_SALVAGE_SECONDS = 300
# "Activity task failed" wrapper.
AGENT_ERROR_METHOD = "_posthog/error"
+# Observability side-channels the relay interleaves into the turn log asynchronously
+# (agentsh network-audit dumps and sandbox credential refreshes ride on `_posthog/console`,
+# sandbox stdout/stderr on `_posthog/sandbox_output`, setup steps on `_posthog/progress`).
+# They carry no turn-state and routinely land *after* the agent's closing usage_update, so the
+# dropped-finalization tail check skips them rather than treating one as the decisive tail.
+TRANSIENT_SIDE_CHANNEL_METHODS = frozenset(
+ {
+ "_posthog/console",
+ "_posthog/progress",
+ "_posthog/sandbox_output",
+ }
+)
+
@dataclass(frozen=True)
class AgentError:
@@ -581,12 +594,19 @@ def _check_logs(task_run, skip_lines: int = 0) -> tuple[bool, str | None, str |
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."""
+ """True when the agent's last turn-relevant 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 turn-relevant 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.
+
+ Observability side-channels (`TRANSIENT_SIDE_CHANNEL_METHODS`) are skipped while walking back:
+ the relay appends agentsh network-audit events and credential-refresh notices to the turn log
+ asynchronously, so one routinely lands after the closing usage_update. Treating such a line as
+ the decisive tail (the prior behavior) masked the fingerprint and made the salvage decline a
+ turn that had genuinely finished — the dominant cause of scout runs hanging out to the poll
+ timeout and being marked failed."""
if not full_log:
return False
for line in reversed(full_log.strip().split("\n")):
@@ -599,6 +619,8 @@ def _ended_on_pending_finalization(full_log: str | None) -> bool:
continue
if not isinstance(notification, dict):
continue
+ if notification.get("method") in TRANSIENT_SIDE_CHANNEL_METHODS:
+ continue
params = notification.get("params")
update = params.get("update") if isinstance(params, dict) else None
if not isinstance(update, dict):
diff --git a/products/tasks/backend/tests/agent_log_fixtures.py b/products/tasks/backend/tests/agent_log_fixtures.py
index edb66ef6f9bf..e5bb6f46e507 100644
--- a/products/tasks/backend/tests/agent_log_fixtures.py
+++ b/products/tasks/backend/tests/agent_log_fixtures.py
@@ -105,6 +105,13 @@ def _usage_update_line(used: int = 1000, cost: float | None = None) -> str:
)
+def _console_line(message: str = "agentsh network events", method: str = "_posthog/console") -> str:
+ # An observability side-channel the relay interleaves into the turn log (agentsh network audit,
+ # sandbox credential refresh, stdout). It carries no turn-state and can land AFTER the agent's
+ # closing usage_update — the dropped-finalization tail check must skip it, not stop on it.
+ return json.dumps({"notification": {"method": method, "params": {"level": "debug", "message": message}}})
+
+
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(
diff --git a/products/tasks/backend/tests/test_multi_turn_session.py b/products/tasks/backend/tests/test_multi_turn_session.py
index ef182fe924e0..b99cb21adcac 100644
--- a/products/tasks/backend/tests/test_multi_turn_session.py
+++ b/products/tasks/backend/tests/test_multi_turn_session.py
@@ -27,6 +27,7 @@ from products.tasks.backend.tests.agent_log_fixtures import (
_agent_error_line,
_agent_message_chunk_line,
_agent_message_line,
+ _console_line,
_cost_less_usage_update_line,
_end_turn_line,
_tool_call_line,
@@ -193,6 +194,55 @@ class TestPollForTurnStaleSalvage:
assert last_message == "close-out summary"
assert total_lines == len(done)
+ @parameterized.expand(
+ [
+ ("single_network_audit", [_console_line("agentsh network events")]),
+ (
+ "audit_then_credential_refresh",
+ [_console_line("agentsh network events"), _console_line("Refreshed sandbox credentials: github")],
+ ),
+ ("sandbox_output", [_console_line("npm install ...", method="_posthog/sandbox_output")]),
+ ("setup_progress", [_console_line("cloning repo", method="_posthog/progress")]),
+ ]
+ )
+ async def test_salvages_dropped_finalization_despite_trailing_console_lines(self, _name, trailing):
+ # The prod failure shape: the agent emits its close-out + null-cost usage_update, then the relay
+ # appends observability side-channels (agentsh network audit, credential refresh, stdout, setup
+ # progress) AFTER the fingerprint while the turn hangs. The tail check must skip those and still
+ # recognize the dropped finalization — otherwise the run hangs to the poll timeout and fails.
+ log = "\n".join([_agent_message_line("close-out summary"), _usage_update_line(165000), *trailing])
+ 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.MAX_POLL_SECONDS", 30),
+ patch("products.tasks.backend.services.custom_prompt_internals.STALE_TURN_SALVAGE_SECONDS", 15),
+ 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 + len(trailing)
+
+ @pytest.mark.asyncio
+ async def test_does_not_salvage_when_console_lines_follow_a_live_tail(self):
+ # Trailing console noise must NOT manufacture a salvage when the agent's own tail isn't the
+ # finalization fingerprint: here the last turn-relevant line is a bare agent_message (no
+ # usage_update), so skipping the console lines still finds no fingerprint and the run times out.
+ log = "\n".join([_agent_message_line("still working"), _console_line("agentsh network events")])
+ 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.MAX_POLL_SECONDS", 30),
+ patch("products.tasks.backend.services.custom_prompt_internals.STALE_TURN_SALVAGE_SECONDS", 15),
+ 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)
+
@pytest.mark.asyncio
async def test_max_poll_seconds_overrides_module_budget(self):
# A caller-supplied max_poll_seconds bounds the loop instead of the module MAX_POLL_SECONDS: