: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(tasks): fail agent turns fast on provider refusals (#75965)
Alex Lebedev5a8a22092fc5
diff --git a/products/tasks/backend/logic/services/custom_prompt_internals.py b/products/tasks/backend/logic/services/custom_prompt_internals.pyindex e4d6a8c88209..ff0addea3a06 100644--- a/products/tasks/backend/logic/services/custom_prompt_internals.py+++ b/products/tasks/backend/logic/services/custom_prompt_internals.py@@ -322,7 +322,7 @@ async def poll_for_turn(logger.warning("custom_prompt - poll_for_turn: failed to send workflow heartbeat", exc_info=True)try:# Poll the logs.- finished, last_message, full_log, total_lines, empty_end_turn = await sync_to_async(+ finished, last_message, full_log, total_lines, empty_end_turn, refused = await sync_to_async(# thread_sensitive=False because of pure I/O (object_storage.read + JSON parsing) and doesn't touch the ORM_check_logs,thread_sensitive=False,@@ -362,6 +362,19 @@ async def poll_for_turn()# Detect how many lines were printed in this pollprinted_lines = _stream_new_lines(full_log, printed_lines, verbose=verbose, output_fn=output_fn)+ # Fail the turn immediately on a provider refusal — the EmptyAgentTurnError channel gives+ # it the in-session nudge retry, then the caller's activity retry, instead of a dead poll.+ if refused:+ logger.warning(+ "custom_prompt - poll_for_turn: agent refused the turn (stopReason=refusal), run=%s total_lines=%d",+ task_run.id,+ total_lines,+ )+ raise EmptyAgentTurnError(+ f"Agent refused the turn (stopReason=refusal) for run={task_run.id}",+ total_lines=total_lines,+ printed_lines=printed_lines,+ )if last_message:latest_assistant_text = last_message# If success@@ -477,7 +490,7 @@ async def poll_for_turn(async def _read_turn_log_with_retry(task_run, *, skip_lines: int, context: str-) -> tuple[bool, str | None, str | None, int, bool]:+) -> tuple[bool, str | None, str | None, int, bool, bool]:"""Read the turn log via _check_logs, retrying transient ObjectStorageError up toMAX_CONSECUTIVE_STORAGE_ERRORS times (one POLL_INTERVAL_SECONDS apart). Re-raises the errorif every attempt fails, so a single S3 blip doesn't fail an otherwise-recoverable turn.@@ -529,7 +542,7 @@ async def _salvage_dropped_finalization(Declining falls back to the caller's timeout failure. A storage outage on the reread propagates(like the poll loop and terminal drain) rather than masquerading as a timeout."""- finished, last_message, full_log, total_lines, _ = await _read_turn_log_with_retry(+ finished, last_message, full_log, total_lines, _, _ = await _read_turn_log_with_retry(task_run, skip_lines=original_skip_lines, context="salvage_dropped_finalization")if finished and last_message is not None:@@ -596,7 +609,7 @@ async def _drain_final_log(stale earlier-turn response in multi-turn sessions). For single-turn callers `original_skip_lines == 0`, sothe scan covers the full log as before. The walk is idempotent and only runs once at terminal status."""- _, final_message, final_log, final_lines, final_empty_end_turn = await _read_turn_log_with_retry(+ _, final_message, final_log, final_lines, final_empty_end_turn, _ = await _read_turn_log_with_retry(task_run, skip_lines=original_skip_lines, context="drain_final_log")printed_lines = _stream_new_lines(final_log, printed_lines, verbose=verbose, output_fn=output_fn)@@ -709,21 +722,24 @@ def _stream_new_lines(return max(printed_lines, len(lines))-def _check_logs(task_run, skip_lines: int = 0) -> tuple[bool, str | None, str | None, int, bool]:+def _check_logs(task_run, skip_lines: int = 0) -> tuple[bool, str | None, str | None, int, bool, bool]:"""Parse S3 logs. When skip_lines > 0, only lines after that offset are inspected for end_turnand agent messages. This avoids re-parsing the entire log on every poll cycle.+ The final tuple element flags a provider refusal (stopReason "refusal") — a terminal turn+ state: without it the poll loop would wait out its whole budget on a turn that already died."""log_content = object_storage.read(task_run.log_url, missing_ok=True) or ""if not log_content.strip():- return False, None, None, 0, False+ return False, None, None, 0, False, Falseall_lines = log_content.strip().split("\n")total_lines = len(all_lines)# Eventual consistency: if S3 returns fewer lines than expected, no new dataif total_lines <= skip_lines:- return False, None, log_content, total_lines, False+ return False, None, log_content, total_lines, False, Falselines_to_parse = all_lines[skip_lines:]agent_finished = False+ refused = False# Collect all parsed session updates so we can walk backwards at the end.parsed_updates: list[dict] = []for line in lines_to_parse:@@ -738,8 +754,14 @@ def _check_logs(task_run, skip_lines: int = 0) -> tuple[bool, str | None, str |if not isinstance(notification, dict):continueresult = notification.get("result")- if isinstance(result, dict) and result.get("stopReason") == "end_turn":+ stop_reason = result.get("stopReason") if isinstance(result, dict) else None+ if stop_reason == "end_turn":+ # A successful end_turn outranks a refusal in the same slice, in either order:+ # once the turn finished, failing it as refused would discard a good response.agent_finished = True+ refused = False+ elif stop_reason == "refusal" and not agent_finished:+ refused = Trueif notification.get("method") != "session/update":continueparams = notification.get("params")@@ -768,10 +790,14 @@ def _check_logs(task_run, skip_lines: int = 0) -> tuple[bool, str | None, str |trailing_parts.append(text)trailing_parts.reverse()latest_text = "".join(trailing_parts) if trailing_parts else None+ # A refused turn must not surface its partial text — the caller would mistake it for the+ # turn's real response.+ if refused:+ return False, None, log_content, total_lines, False, True# If we found end_turn but no agent message in the new lines, flag it as an empty turn.if agent_finished and latest_text is None:- return False, None, log_content, total_lines, True- return agent_finished, latest_text, log_content, total_lines, False+ return False, None, log_content, total_lines, True, False+ return agent_finished, latest_text, log_content, total_lines, False, Falsedef _is_failed_progress(notification: dict) -> bool:diff --git a/products/tasks/backend/tests/agent_log_fixtures.py b/products/tasks/backend/tests/agent_log_fixtures.pyindex 0799e0d41174..f58fe46ddaae 100644--- a/products/tasks/backend/tests/agent_log_fixtures.py+++ b/products/tasks/backend/tests/agent_log_fixtures.py@@ -60,6 +60,10 @@ def _end_turn_line() -> str:return json.dumps({"notification": {"result": {"stopReason": "end_turn"}}})+def _refusal_line() -> str:+ return json.dumps({"notification": {"result": {"stopReason": "refusal"}}})++def _user_message_line(text: str) -> str:return json.dumps({diff --git a/products/tasks/backend/tests/test_check_logs.py b/products/tasks/backend/tests/test_check_logs.pyindex 738f26676941..a83e22986633 100644--- a/products/tasks/backend/tests/test_check_logs.py+++ b/products/tasks/backend/tests/test_check_logs.py@@ -1,3 +1,4 @@+import pytestfrom unittest.mock import patchfrom products.tasks.backend.logic.services.custom_prompt_internals import _check_logs, _stream_new_lines@@ -5,6 +6,7 @@ from products.tasks.backend.tests.agent_log_fixtures import (FakeTaskRun,_agent_message_line,_end_turn_line,+ _refusal_line,_usage_update_line,_user_message_line,)@@ -14,7 +16,7 @@ class TestCheckLogs:def test_returns_agent_message_when_both_present(self):log = "\n".join([_agent_message_line("hello"), _end_turn_line()])with patch("posthog.storage.object_storage.read", return_value=log):- finished, text, _, _, empty_end_turn = _check_logs(FakeTaskRun())+ finished, text, _, _, empty_end_turn, _ = _check_logs(FakeTaskRun())assert finished is Trueassert text == "hello"assert empty_end_turn is False@@ -33,7 +35,7 @@ class TestCheckLogs:skip = len(turn_1) + len(turn_2_prompt)with patch("posthog.storage.object_storage.read", return_value=log):- finished, text, _, total, empty_end_turn = _check_logs(FakeTaskRun(), skip_lines=skip)+ finished, text, _, total, empty_end_turn, _ = _check_logs(FakeTaskRun(), skip_lines=skip)assert finished is Falseassert text is None@@ -48,7 +50,7 @@ class TestCheckLogs:skip = len(turn_1)with patch("posthog.storage.object_storage.read", return_value=log):- finished, text, _, _, empty_end_turn = _check_logs(FakeTaskRun(), skip_lines=skip)+ finished, text, _, _, empty_end_turn, _ = _check_logs(FakeTaskRun(), skip_lines=skip)assert finished is Trueassert text == "new"@@ -56,15 +58,15 @@ class TestCheckLogs:def test_empty_log_returns_all_defaults(self):with patch("posthog.storage.object_storage.read", return_value=""):- finished, text, full_log, total, empty_end_turn = _check_logs(FakeTaskRun())- assert (finished, text, full_log, total, empty_end_turn) == (False, None, None, 0, False)+ finished, text, full_log, total, empty_end_turn, refused = _check_logs(FakeTaskRun())+ assert (finished, text, full_log, total, empty_end_turn, refused) == (False, None, None, 0, False, False)def test_no_new_lines_since_skip_does_not_flag_empty(self):"""Eventual-consistency case: S3 hasn't caught up yet, no new data to parse."""turn_1 = [_agent_message_line("x"), _end_turn_line()]log = "\n".join(turn_1)with patch("posthog.storage.object_storage.read", return_value=log):- finished, text, _, total, empty_end_turn = _check_logs(FakeTaskRun(), skip_lines=len(turn_1))+ finished, text, _, total, empty_end_turn, _ = _check_logs(FakeTaskRun(), skip_lines=len(turn_1))assert finished is Falseassert text is Noneassert empty_end_turn is False@@ -75,7 +77,7 @@ class TestCheckLogs:Otherwise MultiTurnSession.start silently polls until timeout."""log = "\n".join([_end_turn_line()])with patch("posthog.storage.object_storage.read", return_value=log):- finished, text, _, _, empty_end_turn = _check_logs(FakeTaskRun(), skip_lines=0)+ finished, text, _, _, empty_end_turn, _ = _check_logs(FakeTaskRun(), skip_lines=0)assert finished is Falseassert text is Noneassert empty_end_turn is True@@ -93,12 +95,50 @@ class TestCheckLogs:log = "\n".join(turn_1 + turn_2_empty)with patch("posthog.storage.object_storage.read", return_value=log):- finished, text, _, _, empty_end_turn = _check_logs(FakeTaskRun(), skip_lines=len(turn_1))+ finished, text, _, _, empty_end_turn, _ = _check_logs(FakeTaskRun(), skip_lines=len(turn_1))assert finished is Falseassert text is Noneassert empty_end_turn is True+ def test_refusal_flags_refused_and_suppresses_partial_text(self):+ """Regression: a provider refusal used to look like a still-running turn, so every+ refusing unit polled out the full budget (30 min). It must surface as refused, and any+ pre-refusal partial text must not be mistaken for the turn's response."""+ log = "\n".join([_agent_message_line("partial reasoning"), _refusal_line()])+ with patch("posthog.storage.object_storage.read", return_value=log):+ finished, text, _, _, empty_end_turn, refused = _check_logs(FakeTaskRun())+ assert refused is True+ assert finished is False+ assert text is None+ assert empty_end_turn is False++ @pytest.mark.parametrize(+ "lines,expected_text",+ [+ pytest.param(+ [_refusal_line(), _agent_message_line("recovered"), _end_turn_line()],+ "recovered",+ id="refusal-then-end-turn",+ ),+ pytest.param(+ [_agent_message_line("done"), _end_turn_line(), _refusal_line()],+ "done",+ id="end-turn-then-refusal",+ ),+ ],+ )+ def test_end_turn_outranks_refusal_in_either_order(self, lines: list[str], expected_text: str):+ """A successful end_turn outranks a refusal in the same slice regardless of order —+ failing a finished turn as refused would discard a good response."""+ log = "\n".join(lines)+ with patch("posthog.storage.object_storage.read", return_value=log):+ finished, text, _, _, empty_end_turn, refused = _check_logs(FakeTaskRun())+ assert refused is False+ assert finished is True+ assert text == expected_text+ assert empty_end_turn is False+class TestStreamNewLinesMonotonic:def test_no_duplicate_output_after_s3_regression_then_recovery(self):