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): discount transient relay lines in salvage growth check (#63494)

Andrew Maguire06b0994ca9d0
diff --git a/products/tasks/backend/services/custom_prompt_internals.py b/products/tasks/backend/services/custom_prompt_internals.py
index 5644621b04c2..dfeae49a6d48 100644
--- a/products/tasks/backend/services/custom_prompt_internals.py
+++ b/products/tasks/backend/services/custom_prompt_internals.py
@@ -59,6 +59,12 @@ TRANSIENT_SIDE_CHANNEL_METHODS = frozenset(
}
)
+# `_posthog/progress` is normally an informational setup step (status in_progress/completed), but the
+# workflow's failure and cancel handlers emit a progress marker with this status *before* the TaskRun
+# reaches its terminal state. A salvage reread that lands in that window must not skip past it to an
+# earlier finalization fingerprint and report a bogus success, so a failed progress line stays decisive.
+FAILED_PROGRESS_STATUS = "failed"
+
@dataclass(frozen=True)
class AgentError:
@@ -370,14 +376,20 @@ async def _salvage_dropped_finalization(
if last_message is None or not _ended_on_pending_finalization(full_log):
return None
# The fingerprint also matches a mid-turn pause between chunks. The log is append-only, so the only
- # benign growth since polling is the finalization usage_update itself landing late (+1 line beyond
- # the high-water mark). Any more than that — a new message chunk, a tool call, etc. — is fresh
- # activity that has had no silence window and could still be live, so decline rather than truncate.
- if total_lines - max_total_lines_seen > 1:
+ # benign turn-relevant growth since polling is the finalization usage_update itself landing late
+ # (+1 line beyond the high-water mark). Any more than that — a new message chunk, a tool call, etc.
+ # — is fresh activity that has had no silence window and could still be live, so decline rather than
+ # truncate. Transient relay side-channels (network audits, credential refreshes, stdout) also land
+ # in this post-poll window; they carry no turn-state and must be discounted, or one arriving
+ # alongside the late usage_update would push raw growth past the threshold and wrongly decline the
+ # very dropped-finalization case this path recovers.
+ new_lines = (full_log or "").strip().split("\n")[max_total_lines_seen:]
+ relevant_growth = (total_lines - max_total_lines_seen) - _transient_growth(new_lines)
+ if relevant_growth > 1:
logger.warning(
- "custom_prompt - salvage_dropped_finalization: reread grew %d line(s) past the high-water "
- "mark (%d) — fresh activity, no silence window; declining salvage, run=%s",
- total_lines - max_total_lines_seen,
+ "custom_prompt - salvage_dropped_finalization: reread grew %d turn-relevant line(s) past "
+ "the high-water mark (%d) — fresh activity, no silence window; declining salvage, run=%s",
+ relevant_growth,
max_total_lines_seen,
task_run.id,
)
@@ -593,6 +605,36 @@ 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 _is_failed_progress(notification: dict) -> bool:
+ """True for a `_posthog/progress` notification carrying the failed/cancelled status the workflow's
+ exception and cancel handlers emit before writing the terminal TaskRun status."""
+ if notification.get("method") != "_posthog/progress":
+ return False
+ params = notification.get("params")
+ return isinstance(params, dict) and params.get("status") == FAILED_PROGRESS_STATUS
+
+
+def _transient_growth(lines: list[str]) -> int:
+ """Count how many of `lines` are transient relay side-channel notifications (network audits,
+ credential refreshes, sandbox stdout, informational progress). A failed progress line is not
+ transient — it must count as real activity so the growth check can't discount a failure away."""
+ count = 0
+ for line in lines:
+ line = line.strip()
+ if not line:
+ continue
+ try:
+ notification = json.loads(line).get("notification")
+ except json.JSONDecodeError:
+ continue
+ if not isinstance(notification, dict) or notification.get("method") not in TRANSIENT_SIDE_CHANNEL_METHODS:
+ continue
+ if _is_failed_progress(notification):
+ continue
+ count += 1
+ return count
+
+
def _ended_on_pending_finalization(full_log: str | None) -> bool:
"""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
@@ -606,7 +648,8 @@ def _ended_on_pending_finalization(full_log: str | None) -> bool:
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."""
+ timeout and being marked failed. The one exception is a failed/cancelled `_posthog/progress`
+ marker: the workflow emits it on its way to a terminal status, so it stays decisive."""
if not full_log:
return False
for line in reversed(full_log.strip().split("\n")):
@@ -620,6 +663,10 @@ def _ended_on_pending_finalization(full_log: str | None) -> bool:
if not isinstance(notification, dict):
continue
if notification.get("method") in TRANSIENT_SIDE_CHANNEL_METHODS:
+ # A failed/cancelled progress marker is decisive — the workflow emits it on its way to a
+ # terminal status, so we must not skip it to salvage an earlier finalization fingerprint.
+ if _is_failed_progress(notification):
+ return False
continue
params = notification.get("params")
update = params.get("update") if isinstance(params, dict) else None
diff --git a/products/tasks/backend/tests/agent_log_fixtures.py b/products/tasks/backend/tests/agent_log_fixtures.py
index e5bb6f46e507..0799e0d41174 100644
--- a/products/tasks/backend/tests/agent_log_fixtures.py
+++ b/products/tasks/backend/tests/agent_log_fixtures.py
@@ -112,6 +112,20 @@ def _console_line(message: str = "agentsh network events", method: str = "_posth
return json.dumps({"notification": {"method": method, "params": {"level": "debug", "message": message}}})
+def _progress_line(status: str = "failed", step: str = "agent", label: str = "Running agent") -> str:
+ # A `_posthog/progress` notification. The workflow's failure/cancel handlers emit one with
+ # status="failed" BEFORE the TaskRun reaches its terminal status — that line must stay decisive
+ # in the dropped-finalization tail check, not be skipped as informational setup progress.
+ return json.dumps(
+ {
+ "notification": {
+ "method": "_posthog/progress",
+ "params": {"step": step, "status": status, "label": label, "group": "setup"},
+ }
+ }
+ )
+
+
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 b99cb21adcac..511be37d371c 100644
--- a/products/tasks/backend/tests/test_multi_turn_session.py
+++ b/products/tasks/backend/tests/test_multi_turn_session.py
@@ -30,6 +30,7 @@ from products.tasks.backend.tests.agent_log_fixtures import (
_console_line,
_cost_less_usage_update_line,
_end_turn_line,
+ _progress_line,
_tool_call_line,
_usage_update_line,
_user_message_line,
@@ -640,6 +641,87 @@ class TestPollForTurnStaleSalvage:
with pytest.raises(RuntimeError, match="timed out"):
await poll_for_turn(fake, skip_lines=0)
+ @parameterized.expand(
+ [
+ ("one_console_line", [_console_line("agentsh network events")]),
+ (
+ "console_then_credential_refresh",
+ [_console_line("agentsh network events"), _console_line("Refreshed sandbox credentials: github")],
+ ),
+ ("sandbox_output", [_console_line("npm install ...", method="_posthog/sandbox_output")]),
+ ]
+ )
+ async def test_salvages_when_late_fingerprint_and_trailing_relay_lines_both_land_on_reread(self, _name, trailing):
+ # The growth check must discount transient relay side-channels, not just the tail classifier.
+ # Polls saw only the agent_message; the late null-cost usage_update AND trailing relay line(s)
+ # both appear on the salvage reread. Raw growth is +2 or more, but only +1 line is turn-relevant
+ # (the finalization fingerprint), so salvage must proceed — counting the relay lines as growth
+ # would re-open the exact dropped-finalization-behind-trailing-logs case this path recovers.
+ seen = _agent_message_line("close-out summary") # message only, no fingerprint yet
+ finalized = "\n".join([_agent_message_line("close-out summary"), _usage_update_line(165000), *trailing])
+ calls = {"n": 0}
+
+ def next_log(*_args, **_kwargs):
+ calls["n"] += 1
+ # polls 1-3 see only the message; the salvage reread (4th) sees the fingerprint + relay lines.
+ return finalized if calls["n"] > 3 else seen
+
+ 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.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, _, _, _ = await poll_for_turn(fake, skip_lines=0)
+
+ assert last_message == "close-out summary"
+
+ @pytest.mark.asyncio
+ async def test_failed_progress_after_fingerprint_declines_salvage(self):
+ # The workflow's failure/cancel handlers emit a `_posthog/progress` status="failed" BEFORE the
+ # TaskRun reaches a terminal status. A salvage reread landing in that window must treat the
+ # failed progress marker as decisive — not skip it as informational setup progress and report a
+ # bogus success off the preceding finalization fingerprint. Status is still non-terminal here,
+ # so without this the run would salvage instead of letting the terminal drain win.
+ log = "\n".join(
+ [_agent_message_line("close-out summary"), _usage_update_line(165000), _progress_line(status="failed")]
+ )
+ 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)
+
+ @parameterized.expand([("in_progress",), ("completed",)])
+ async def test_informational_progress_after_fingerprint_still_salvages(self, status):
+ # Only failed/cancelled progress is decisive — an informational progress line (a normal setup
+ # step) trailing the fingerprint is still skipped as transient, so the dropped finalization is
+ # salvaged as before.
+ log = "\n".join(
+ [_agent_message_line("close-out summary"), _usage_update_line(165000), _progress_line(status=status)]
+ )
+ 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, _, _, _ = await poll_for_turn(fake, skip_lines=0)
+
+ assert last_message == "close-out summary"
+
class TestPollForTurnTerminalDrain:
"""Terminal-status drain must recover an agent_message from *this* turn only.