: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
feat(tasks): carry scout agent error categories into run telemetry (#99538)
posthog[bot]a0337299e330
diff --git a/products/signals/backend/scout_harness/runner.py b/products/signals/backend/scout_harness/runner.pyindex 1714e775423b..3c89557fb570 100644--- a/products/signals/backend/scout_harness/runner.py+++ b/products/signals/backend/scout_harness/runner.py@@ -60,7 +60,12 @@ from products.signals.backend.temporal.agentic import (resolve_acting_user_id_for_team,)from products.tasks.backend.facade import api as tasks_facade-from products.tasks.backend.facade.agents import CustomPromptSandboxContext, MultiTurnSession, TurnPollTimeout+from products.tasks.backend.facade.agents import (+ AgentTurnFailed,+ CustomPromptSandboxContext,+ MultiTurnSession,+ TurnPollTimeout,+)if TYPE_CHECKING:from products.tasks.backend.models import TaskRun@@ -488,7 +493,7 @@ async def arun_signals_scout(service_tier=service_tier,error_type=type(exc).__name__,error_message=str(exc)[:300],- extra_properties=_poll_timeout_properties(exc),+ extra_properties=_failure_properties(exc),)if streak is not None and streak.tripped:_capture_config_auto_paused(@@ -1210,16 +1215,25 @@ def _record_failure_streak(config_id: Any) -> _FailureStreak | None:return None-def _poll_timeout_properties(exc: BaseException) -> dict[str, Any] | None:- """Turn-log diagnostics for a run that died at the per-turn poll wall, or None for any other- failure. Every wall failure raises the same error string, which is why the fleet's timeout- rate reads as one cause; these properties split it into the populations that need different- fixes — an agent that never emitted a single turn-relevant line (never started), one that- worked and then went silent, and one still streaming when the budget ran out (the budget,- not the agent, is the constraint)."""- if not isinstance(exc, TurnPollTimeout):- return None- return exc.diagnostics()+def _failure_properties(exc: BaseException) -> dict[str, Any] | None:+ """Cause-specific analytics properties for a failed run, or None when the exception's type and+ message already say everything.++ A run that died at the per-turn poll wall gets the turn-log diagnostics. Every wall failure+ raises the same error string, which is why the fleet's timeout rate reads as one cause; these+ properties split it into the populations that need different fixes — an agent that never+ emitted a single turn-relevant line (never started), one that worked and then went silent, and+ one still streaming when the budget ran out (the budget, not the agent, is the constraint).++ A run the agent itself failed gets the agent's own classification, because `error_type` is+ `AgentTurnFailed` for all of them. A provider outage, a spend limit and a broken scout body+ raise the same exception, so only `error_category` separates the upstream failures worth+ retrying from the defects that must keep feeding the failure breaker."""+ if isinstance(exc, TurnPollTimeout):+ return exc.diagnostics()+ if isinstance(exc, AgentTurnFailed) and exc.category is not None:+ return {"error_category": exc.category}+ return Nonedef _run_row_exists(run_id: Any, team_id: int) -> bool:@@ -1465,9 +1479,9 @@ def _capture_run_finished(are attached so the failure rate is breakable down by cause without digging into workerlogs — the bulk of scout failures fail in this layer before the `process-task` workflow'sown `task_run_failed` event ever fires, so this is the only event that carries their reason.- `extra_properties` carries cause-specific detail the error string can't (today: the turn-log+ `extra_properties` carries cause-specific detail the error string can't: the turn-logdiagnostics behind a per-turn poll timeout, which is a single string covering several- distinct failures).+ distinct failures, and the agent's own `error_category` for a failure it classified."""properties: dict[str, Any] = {"skill_name": skill.name,diff --git a/products/signals/backend/test/test_scout_harness.py b/products/signals/backend/test/test_scout_harness.pyindex 477938b9a246..039d407a395f 100644--- a/products/signals/backend/test/test_scout_harness.py+++ b/products/signals/backend/test/test_scout_harness.py@@ -86,6 +86,7 @@ from products.signals.backend.temporal.agentic.scout_scheduler import ()from products.skills.backend.models.skills import LLMSkill, LLMSkillFile, LLMSkillOwnerfrom products.tasks.backend.facade import api as tasks_facade+from products.tasks.backend.facade.agents import AgentTurnFailedfrom products.tasks.backend.facade.billing import TaskTokenUsageUnavailableif TYPE_CHECKING:@@ -2098,15 +2099,50 @@ async def test_successful_run_captures_run_started_event(ateam, aerrors_skill):assert props["scout_config_id"] == str(config.id)+ "failure,expected_error_type,expected_error_message,expected_error_category",+ [+ (+ RuntimeError("sandbox refused to start"),+ "RuntimeError",+ "sandbox refused to start",+ None,+ ),+ # Without `error_category` a provider outage and a broken scout body read as one population.+ (+ AgentTurnFailed(+ "TaskRun reached terminal status=failed (cause: upstream_provider_failure: API Error: 429)",+ category="upstream_provider_failure",+ agent_message="API Error: 429",+ ),+ "AgentTurnFailed",+ "TaskRun reached terminal status=failed (cause: upstream_provider_failure: API Error: 429)",+ "upstream_provider_failure",+ ),+ # Older agent build: no classification to carry, so the event stays as it is today.+ (+ AgentTurnFailed(+ "TaskRun reached terminal status=failed (cause: API Error: 429)",+ category=None,+ agent_message="API Error: 429",+ ),+ "AgentTurnFailed",+ "TaskRun reached terminal status=failed (cause: API Error: 429)",+ None,+ ),+ ],+)@pytest.mark.asyncio@pytest.mark.django_db-async def test_failed_run_captures_run_finished_event(ateam, aerrors_skill):+async def test_failed_run_captures_run_finished_event(+ ateam, aerrors_skill, failure, expected_error_type, expected_error_message, expected_error_category+):TaskRun = apps.get_model("tasks", "TaskRun")with (patch("products.signals.backend.scout_harness.runner.MultiTurnSession.start",new_callable=AsyncMock,- side_effect=RuntimeError("sandbox refused to start"),+ side_effect=failure,),# A routed model must survive onto the failed event too — timeouts and crashes are# exactly the outcomes a model trial slices by.@@ -2142,8 +2178,9 @@ async def test_failed_run_captures_run_finished_event(ateam, aerrors_skill):# Failure reason rides on the event so the failure rate is breakable down by cause# without digging into worker logs — the bulk of scout failures fail here, before the# process-task workflow's own task_run_failed event fires.- assert props["error_type"] == "RuntimeError"- assert props["error_message"] == "sandbox refused to start"+ assert props["error_type"] == expected_error_type+ assert props["error_message"] == expected_error_message+ assert props.get("error_category") == expected_error_category@contextmanagerdiff --git a/products/tasks/backend/facade/agents.py b/products/tasks/backend/facade/agents.pyindex 699527db201f..faa662650ca0 100644--- a/products/tasks/backend/facade/agents.py+++ b/products/tasks/backend/facade/agents.py@@ -10,6 +10,7 @@ objects, not data, per the wiring pattern. Heavy by import, so it lives here ratfrom products.tasks.backend.constants import EVAL_INTERACTION_ORIGIN, MCP_EXEC_SKILLS_FEATURE_FLAGfrom products.tasks.backend.logic.services.custom_prompt_internals import (+ AgentTurnFailed,CustomPromptSandboxContext,EmptyAgentTurnError,OutputFn,@@ -47,6 +48,7 @@ __all__ = ["EVAL_INTERACTION_ORIGIN","MCP_EXEC_SKILLS_FEATURE_FLAG","ENV_LOCAL_SKILLS_HOST_PATH",+ "AgentTurnFailed","CustomPromptSandboxContext","EmptyAgentTurnError","LocalSkillsCache",diff --git a/products/tasks/backend/logic/services/custom_prompt_internals.py b/products/tasks/backend/logic/services/custom_prompt_internals.pyindex 25b15edb325e..6c0c37f4782a 100644--- a/products/tasks/backend/logic/services/custom_prompt_internals.py+++ b/products/tasks/backend/logic/services/custom_prompt_internals.py@@ -208,6 +208,41 @@ class EmptyAgentTurnError(RuntimeError):self.printed_lines = printed_lines+# Mirrored from RETRYABLE_UPSTREAM_ERROR_CLASSIFICATIONS in+# products/desktop/packages/agent/src/adapters/error-classification.ts, which is the source of+# truth. A category added there must be added here too, or a retryable failure reads as permanent.+UPSTREAM_RETRYABLE_ERROR_CATEGORIES = frozenset(+ {+ "upstream_stream_terminated",+ "upstream_connection_error",+ "upstream_timeout",+ "upstream_provider_failure",+ }+)+++class AgentTurnFailed(RuntimeError):+ """The sandbox agent reported a terminal error for the turn.++ Carries the agent's own classification of the failure, because the message alone collapses+ causes that need opposite responses: a provider outage is worth retrying, a spend-limit stop+ and a broken agent body are not. Callers branch on `category` (and `retryable_upstream`)+ instead of matching the message text, and record it as an analytics dimension so a fleet's+ failure rate splits by cause.++ `category` is None when the agent build emitted no `errorCategory`.+ """++ def __init__(self, message: str, *, category: str | None, agent_message: str) -> None:+ super().__init__(message)+ self.category = category+ self.agent_message = agent_message++ @property+ def retryable_upstream(self) -> bool:+ return self.category in UPSTREAM_RETRYABLE_ERROR_CATEGORIES++async def create_task_and_trigger(description: str,context: CustomPromptSandboxContext,@@ -676,9 +711,11 @@ async def _drain_final_log(cause_text = agent_error.describe()# Persist the real cause so the TaskRun stops showing "Activity task failed".await _persist_task_run_error_message(str(task_run.id), cause_text)- raise RuntimeError(+ raise AgentTurnFailed(f"custom_prompt - drain_final_log: TaskRun reached terminal status={refreshed_status} "- f"(cause: {cause_text})"+ f"(cause: {cause_text})",+ category=agent_error.category,+ agent_message=agent_error.message,)reason = "end_turn with empty response" if final_state.empty_end_turn else "no agent message"cause = f" (cause: {error_message})" if error_message else ""diff --git a/products/tasks/backend/tests/test_multi_turn_session.py b/products/tasks/backend/tests/test_multi_turn_session.pyindex b17eb8b4a227..953ba5ae3cfa 100644--- a/products/tasks/backend/tests/test_multi_turn_session.py+++ b/products/tasks/backend/tests/test_multi_turn_session.py@@ -17,6 +17,7 @@ from posthog.storage.object_storage import ObjectStorageErrorfrom products.tasks.backend.logic.services.custom_prompt_internals import (AgentError,+ AgentTurnFailed,CustomPromptSandboxContext,EmptyAgentTurnError,TurnPollResult,@@ -971,19 +972,23 @@ class TestExtractAgentError:class TestPollForTurnSurfacesAgentError:"""On a FAILED terminal status, the drain must surface the agent's classified error- (category + raw message) on both TaskRun.error_message and the raised RuntimeError- that Temporal records — never the opaque 'Activity task failed' wrapper."""+ (category + raw message) on TaskRun.error_message, on the raised exception's message that+ Temporal records — never the opaque 'Activity task failed' wrapper — and as typed fields on+ the exception, so a caller separates a retryable provider outage from a scout defect without+ matching the message text."""@parameterized.expand([- ("upstream_provider_failure", "API Error: 429 rate_limit_error"),- ("upstream_connection_error", "API Error: Connection error"),- ("upstream_stream_terminated", "API Error: terminated"),- ("agent_error", "Unhandled exception in agent loop"),+ ("upstream_provider_failure", "API Error: 429 rate_limit_error", True),+ ("upstream_connection_error", "API Error: Connection error", True),+ ("upstream_stream_terminated", "API Error: terminated", True),+ ("upstream_timeout", "API Error: Request timed out", True),+ ("task_spend_limit", "This agent run reached its spend limit", False),+ ("agent_error", "Unhandled exception in agent loop", False),])@pytest.mark.asyncio- async def test_surfaces_classified_error(self, category, message):+ async def test_surfaces_classified_error(self, category, message, retryable_upstream):turn_1 = [_agent_message_line("turn-1-response"), _end_turn_line()]# Turn 2 died with a classified error and no agent_message / end_turn.turn_2 = [_user_message_line("followup"), _usage_update_line(0), _agent_error_line(message, category=category)]@@ -1003,7 +1008,7 @@ class TestPollForTurnSurfacesAgentError:new=persist,),):- with pytest.raises(RuntimeError) as exc_info:+ with pytest.raises(AgentTurnFailed) as exc_info:await poll_for_turn(fake_task_run, skip_lines=skip)expected = f"{category}: {message}"@@ -1012,6 +1017,9 @@ class TestPollForTurnSurfacesAgentError:assert "Activity task failed" not in str(exc_info.value)# The same classified error is persisted onto TaskRun.error_message.persist.assert_awaited_once_with(str(fake_task_run.id), expected)+ assert exc_info.value.category == category+ assert exc_info.value.agent_message == message+ assert exc_info.value.retryable_upstream is retryable_upstream@pytest.mark.asyncioasync def test_acceptance_provider_failure_429(self):@@ -1058,12 +1066,14 @@ class TestPollForTurnSurfacesAgentError:new=persist,),):- with pytest.raises(RuntimeError) as exc_info:+ with pytest.raises(AgentTurnFailed) as exc_info:await poll_for_turn(fake_task_run, skip_lines=0)# No category prefix — the raw message is persisted and surfaced.persist.assert_awaited_once_with(str(fake_task_run.id), "API Error: 429 rate_limit_error")assert "API Error: 429 rate_limit_error" in str(exc_info.value)+ assert exc_info.value.category is None+ assert exc_info.value.retryable_upstream is False@pytest.mark.asyncioasync def test_missing_structured_error_keeps_generic_behavior(self):@@ -1087,6 +1097,8 @@ class TestPollForTurnSurfacesAgentError:await poll_for_turn(fake_task_run, skip_lines=0)assert "Activity task failed" in str(exc_info.value)+ # No agent classification to carry, so the generic failure stays untyped.+ assert not isinstance(exc_info.value, AgentTurnFailed)persist.assert_not_awaited()assert fake_task_run.error_message == "Activity task failed"