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(signals): salvage finished scout turns despite trailing side-channels (#73801)

posthog[bot]70eaa93df04a
diff --git a/products/tasks/backend/logic/services/custom_prompt_internals.py b/products/tasks/backend/logic/services/custom_prompt_internals.py
index b340c9d2441c..11d9fd5f2198 100644
--- a/products/tasks/backend/logic/services/custom_prompt_internals.py
+++ b/products/tasks/backend/logic/services/custom_prompt_internals.py
@@ -34,14 +34,16 @@ OutputFn = Callable[[str], object] | None
POLL_INTERVAL_SECONDS = 10
MAX_POLL_SECONDS = 30 * 60 # default per-turn budget; callers with longer turns pass max_poll_seconds
MAX_CONSECUTIVE_STORAGE_ERRORS = 3
-# Continuous log silence required before salvaging a dropped-finalization turn — one SSE read window
-# (SSE_READ_TIMEOUT_SECONDS). The null-cost finalization fingerprint (_ended_on_pending_finalization)
-# is the real safety gate; this floor only rules out salvaging a turn caught mid-stream. It must sit
-# well below the 1800s poll budget: a floor near the budget would only salvage turns that fell silent
-# in the first few minutes and reject a turn that does real work late and *then* drops end_turn — the
-# exact case this path exists to recover. The relay's true continuous-silence ceiling is
-# 6 × SSE_READ_TIMEOUT_SECONDS = 1800s, which can't be fully observed inside the 1800s budget; keying
-# salvage off a real terminal signal instead of the poll deadline stays the layer-2 follow-up.
+# Turn-relevant log silence required before salvaging a dropped-finalization turn, sized to one SSE
+# read window (SSE_READ_TIMEOUT_SECONDS): if the turn produced no real output for a whole read window,
+# a live stream would have. The poll loop measures this silence over turn-relevant lines only, because
+# the relay keeps appending transient side-channels (network audits, credential refreshes, stdout)
+# after a turn goes quiet; counting those would keep resetting the timer so the floor never clears and
+# a finished-but-noisy turn is never salvaged (the observed dominant failure mode). The null-cost
+# finalization fingerprint (_ended_on_pending_finalization) is the real safety gate; this floor only
+# rules out salvaging a turn caught mid-stream. It must stay well below the per-turn poll budget (the
+# Signals scout passes 900s): a floor near the budget would salvage only turns that fell silent early
+# and reject one that works late and then drops end_turn, the exact case this path exists to recover.
STALE_TURN_SALVAGE_SECONDS = 300
# Notification method the sandbox agent emits on a terminal failure. The agent
@@ -269,9 +271,16 @@ async def poll_for_turn(
raise
continue
consecutive_storage_errors = 0
- # Track the timings
+ # Advance the silence marker only on turn-relevant growth. Transient relay side-channels
+ # (network audits, credential refreshes, stdout) keep arriving after a turn goes quiet, so
+ # counting them here would keep resetting the marker and STALE_TURN_SALVAGE_SECONDS would
+ # never clear, starving the dropped-finalization salvage of the silence window it needs. This
+ # mirrors the side-channel discounting the tail check already does in
+ # _ended_on_pending_finalization.
if total_lines > skip_lines:
- last_new_lines_at = elapsed
+ new_lines = (full_log or "").strip().split("\n")[skip_lines:]
+ if (total_lines - skip_lines) - _transient_growth(new_lines) > 0:
+ last_new_lines_at = elapsed
stale_seconds = elapsed - last_new_lines_at
# Warn once per minute of silence (not every poll) so stalls surface without flooding logs.
if stale_seconds >= 60 and stale_seconds % 60 < POLL_INTERVAL_SECONDS:
diff --git a/products/tasks/backend/tests/test_multi_turn_session.py b/products/tasks/backend/tests/test_multi_turn_session.py
index 3dc7b56da81c..9ec669632fd4 100644
--- a/products/tasks/backend/tests/test_multi_turn_session.py
+++ b/products/tasks/backend/tests/test_multi_turn_session.py
@@ -232,6 +232,36 @@ class TestPollForTurnStaleSalvage:
assert last_message == "close-out summary"
assert total_lines == 2 + len(trailing)
+ @pytest.mark.asyncio
+ async def test_salvages_dropped_finalization_despite_side_channels_arriving_every_poll(self):
+ # The prod failure shape that the single-static-log test above can't reach: the agent finishes
+ # (close-out + null-cost usage_update) early, then the relay keeps trickling a NEW side-channel
+ # line on every poll right up to the wall. The silence marker must ignore that transient growth
+ # so STALE_TURN_SALVAGE_SECONDS clears and the finished turn is salvaged. If the marker counted
+ # any line (the old behavior), each poll would reset it and the run would time out despite being
+ # done — the systemic ~8-12% baseline / ~36% spike failure.
+ base = [_agent_message_line("close-out summary"), _usage_update_line(165000)]
+ logs = ["\n".join(base + [_console_line(f"agentsh network events {i}") for i in range(n)]) for n in range(6)]
+ poll_iter = iter(logs)
+
+ def next_log(*_args, **_kwargs):
+ return next(poll_iter, logs[-1])
+
+ fake = FakeTaskRun()
+ with (
+ patch("posthog.storage.object_storage.read", side_effect=next_log),
+ patch("asyncio.sleep", new=AsyncMock()),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.POLL_INTERVAL_SECONDS", 10),
+ patch("products.tasks.backend.logic.services.custom_prompt_internals.MAX_POLL_SECONDS", 60),
+ # Floor scaled to the tiny test budget: the agent falls silent (turn-relevant) after poll 1
+ # at elapsed 10, so 50s of real silence accrues by the 60s wall and clears this 15s floor.
+ patch("products.tasks.backend.logic.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_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