AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
fix(backend): skip LLM analysis for credit exhaustion (#12614)
AutoGPTf6a91983925c
diff --git a/autogpt_platform/analytics/queries/graph_execution.sql b/autogpt_platform/analytics/queries/graph_execution.sqlindex 2fb9d75e91..e5e1b8f2f5 100644--- a/autogpt_platform/analytics/queries/graph_execution.sql+++ b/autogpt_platform/analytics/queries/graph_execution.sql@@ -61,10 +61,21 @@ SELECTge."agentGraphId" AS agentGraphId,ge."agentGraphVersion" AS agentGraphVersion,CASE- WHEN jsonb_exists(ge."stats"::jsonb, 'error')+ -- Keep these legacy message predicates synchronized with+ -- backend/backend/util/exceptions.py and _LEGACY_BALANCE_CORPUS in its+ -- test module. New rows use failure_reason.+ WHEN CAST(ge."executionStatus" AS TEXT) = 'FAILED'AND (- (ge."stats"::jsonb->>'error') ILIKE '%insufficient balance%'- OR (ge."stats"::jsonb->>'error') ILIKE '%you have no credits left%'+ ge."stats"::jsonb->>'failure_reason' = 'insufficient_balance'+ OR (+ ge."stats"::jsonb->>'failure_reason' IS NULL+ AND (+ ge."stats"::jsonb->>'error' = 'You have no credits left to run an agent.'+ OR ge."stats"::jsonb->>'error' ~ '^Insufficient balance of \$-?[0-9]+(\.[0-9]+)?, where this will cost \$-?[0-9]+(\.[0-9]+)?$'+ OR ge."stats"::jsonb->>'error' ~ '^Insufficient balance to run [A-Za-z_][A-Za-z0-9_]*: dynamic-cost blocks require a positive balance\.$'+ OR ge."stats"::jsonb->>'error' ~ '^Organization has -?[0-9]+ credits but needs [0-9]+$'+ )+ ))THEN 'NO_CREDITS'ELSE CAST(ge."executionStatus" AS TEXT)diff --git a/autogpt_platform/backend/backend/api/features/admin/execution_analytics_routes.py b/autogpt_platform/backend/backend/api/features/admin/execution_analytics_routes.pyindex c101e1e53d..e4e37ac15c 100644--- a/autogpt_platform/backend/backend/api/features/admin/execution_analytics_routes.py+++ b/autogpt_platform/backend/backend/api/features/admin/execution_analytics_routes.py@@ -25,10 +25,8 @@ from backend.executor.activity_status_generator import (generate_activity_status_for_execution,)from backend.executor.manager import get_db_async_client-from backend.util.settings import Settingslogger = logging.getLogger(__name__)-settings = Settings()class ExecutionAnalyticsRequest(BaseModel):@@ -217,9 +215,9 @@ async def generate_execution_analytics(Generate activity summaries and correctness scores for graph executions.This endpoint:- 1. Fetches all completed executions matching the criteria- 2. Identifies executions missing activity_status or correctness_score- 3. Generates missing data using AI in batches+ 1. Fetches all terminal executions matching the criteria+ 2. Identifies executions missing a complete activity analysis+ 3. Generates missing data in batches, using deterministic results where available4. Updates the database with new stats5. Returns a detailed report of the analytics operation"""@@ -251,7 +249,6 @@ async def generate_execution_analytics(# Filter executions that need analytics generationexecutions_to_process = []for execution in executions:- # Skip if we should skip existing analytics and both activity_status and correctness_score existif (request.skip_existingand execution.stats@@ -271,6 +268,7 @@ async def generate_execution_analytics(results = []successful_count = 0failed_count = 0+ skipped_count = 0# Process executions that need analytics generationif executions_to_process:@@ -294,6 +292,8 @@ async def generate_execution_analytics(successful_count += 1elif result.status == "failed":failed_count += 1+ elif result.status == "skipped":+ skipped_count += 1# Small delay between batches to avoid overwhelming the LLM APIif batch_idx < total_batches - 1: # Don't delay after the last batch@@ -323,13 +323,14 @@ async def generate_execution_analytics(ended_at=execution.ended_at,))+ skipped_count += 1response = ExecutionAnalyticsResponse(total_executions=len(executions),processed_executions=len(executions_to_process),successful_analytics=successful_count,failed_analytics=failed_count,- skipped_executions=len(executions) - len(executions_to_process),+ skipped_executions=skipped_count,results=results,)@@ -350,9 +351,6 @@ async def _process_batch() -> list[ExecutionAnalyticsResult]:"""Process a batch of executions concurrently."""- if not settings.secrets.openai_internal_api_key:- raise HTTPException(status_code=500, detail="OpenAI API key not configured")-async def process_single_execution(execution) -> ExecutionAnalyticsResult:try:# Generate activity status and score using the specified modeldiff --git a/autogpt_platform/backend/backend/api/features/admin/execution_analytics_routes_test.py b/autogpt_platform/backend/backend/api/features/admin/execution_analytics_routes_test.pynew file mode 100644index 0000000000..c4e4b976f7--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/admin/execution_analytics_routes_test.py@@ -0,0 +1,213 @@+from types import SimpleNamespace+from unittest.mock import AsyncMock, patch++import pytest++from backend.api.features.admin.execution_analytics_routes import (+ ExecutionAnalyticsRequest,+ ExecutionAnalyticsResult,+ _process_batch,+ generate_execution_analytics,+)+from backend.data.execution import ExecutionStatus, GraphExecutionMeta+from backend.executor.activity_status_generator import INSUFFICIENT_BALANCE_SUMMARY+from backend.util.exceptions import ExecutionFailureReason+++async def test_process_batch_allows_credit_failure_without_openai_key():+ execution = SimpleNamespace(+ id="exec-1",+ graph_id="graph-1",+ graph_version=1,+ user_id="user-1",+ status=ExecutionStatus.FAILED,+ stats=GraphExecutionMeta.Stats(+ error="Organization has 0 credits but needs 25",+ failure_reason=ExecutionFailureReason.INSUFFICIENT_BALANCE,+ ),+ started_at=None,+ ended_at=None,+ )+ request = ExecutionAnalyticsRequest(graph_id="graph-1")+ with (+ patch(+ "backend.api.features.admin.execution_analytics_routes.update_graph_execution_stats",+ new=AsyncMock(),+ ) as mock_update,+ patch(+ "backend.executor.activity_status_generator.get_openai_client"+ ) as mock_get_openai_client,+ ):+ results = await _process_batch([execution], request, AsyncMock())++ assert results[0].status == "success"+ assert results[0].score == 0.0+ mock_update.assert_awaited_once()+ update_call = mock_update.await_args.kwargs+ assert update_call["graph_exec_id"] == "exec-1"+ updated_stats = update_call["stats"]+ assert updated_stats.failure_reason == ExecutionFailureReason.INSUFFICIENT_BALANCE+ assert updated_stats.correctness_score == 0.0+ assert updated_stats.activity_status == INSUFFICIENT_BALANCE_SUMMARY+ mock_get_openai_client.assert_not_called()+++async def test_process_batch_skips_non_credit_failure_without_llm_client():+ execution = SimpleNamespace(+ id="exec-1",+ graph_id="graph-1",+ graph_version=1,+ user_id="user-1",+ status=ExecutionStatus.FAILED,+ stats=GraphExecutionMeta.Stats(error="Connection timeout"),+ started_at=None,+ ended_at=None,+ )+ db_client = AsyncMock()+ request = ExecutionAnalyticsRequest(graph_id="graph-1")++ with (+ patch(+ "backend.api.features.admin.execution_analytics_routes.update_graph_execution_stats",+ new=AsyncMock(),+ ) as mock_update,+ patch(+ "backend.executor.activity_status_generator.get_openai_client",+ return_value=None,+ ) as mock_get_openai_client,+ ):+ results = await _process_batch([execution], request, db_client)++ assert len(results) == 1+ assert results[0].status == "skipped"+ assert results[0].summary_text is None+ assert results[0].score is None+ assert results[0].error_message == "Activity generation returned None"+ mock_update.assert_not_awaited()+ mock_get_openai_client.assert_called_once_with(prefer_openrouter=True)+ db_client.get_node_executions.assert_not_awaited()+ db_client.get_graph_metadata.assert_not_awaited()+ db_client.get_graph.assert_not_awaited()+++async def test_generate_analytics_only_skips_complete_existing_analysis():+ complete_execution = SimpleNamespace(+ id="exec-complete",+ graph_id="graph-1",+ graph_version=1,+ user_id="user-1",+ status=ExecutionStatus.FAILED,+ stats=GraphExecutionMeta.Stats(+ activity_status="Existing deterministic summary",+ correctness_score=0.0,+ ),+ started_at=None,+ ended_at=None,+ )+ legacy_execution = SimpleNamespace(+ id="exec-legacy",+ graph_id="graph-1",+ graph_version=1,+ user_id="user-1",+ status=ExecutionStatus.COMPLETED,+ stats=GraphExecutionMeta.Stats(+ activity_status="Legacy summary without a score",+ correctness_score=None,+ ),+ started_at=None,+ ended_at=None,+ )+ request = ExecutionAnalyticsRequest(graph_id="graph-1")+ processed_result = ExecutionAnalyticsResult(+ agent_id="graph-1",+ version_id=1,+ user_id="user-1",+ exec_id="exec-legacy",+ summary_text="Regenerated summary",+ score=0.8,+ status="success",+ )+ db_client = AsyncMock()++ with (+ patch(+ "backend.api.features.admin.execution_analytics_routes.get_db_async_client",+ return_value=db_client,+ ),+ patch(+ "backend.api.features.admin.execution_analytics_routes.get_graph_executions",+ new=AsyncMock(return_value=[complete_execution, legacy_execution]),+ ),+ patch(+ "backend.api.features.admin.execution_analytics_routes._process_batch",+ new=AsyncMock(return_value=[processed_result]),+ ) as mock_process_batch,+ ):+ response = await generate_execution_analytics(+ request,+ admin_user_id="admin-1",+ )++ assert response.processed_executions == 1+ assert response.skipped_executions == 1+ assert {result.exec_id: result.status for result in response.results} == {+ "exec-complete": "skipped",+ "exec-legacy": "success",+ }+ mock_process_batch.assert_awaited_once_with(+ [legacy_execution],+ request,+ db_client,+ )+++async def test_generate_analytics_counts_processed_rows_skipped():+ execution = SimpleNamespace(+ id="exec-no-client",+ graph_id="graph-1",+ graph_version=1,+ user_id="user-1",+ status=ExecutionStatus.COMPLETED,+ stats=GraphExecutionMeta.Stats(),+ started_at=None,+ ended_at=None,+ )+ skipped_result = ExecutionAnalyticsResult(+ agent_id="graph-1",+ version_id=1,+ user_id="user-1",+ exec_id="exec-no-client",+ summary_text=None,+ score=None,+ status="skipped",+ error_message="Activity generation returned None",+ )++ with (+ patch(+ "backend.api.features.admin.execution_analytics_routes.get_db_async_client",+ return_value=AsyncMock(),+ ),+ patch(+ "backend.api.features.admin.execution_analytics_routes.get_graph_executions",+ new=AsyncMock(return_value=[execution]),+ ),+ patch(+ "backend.api.features.admin.execution_analytics_routes._process_batch",+ new=AsyncMock(return_value=[skipped_result]),+ ),+ ):+ response = await generate_execution_analytics(+ ExecutionAnalyticsRequest(graph_id="graph-1"),+ admin_user_id="admin-1",+ )++ assert response.processed_executions == 1+ assert response.successful_analytics == 0+ assert response.failed_analytics == 0+ assert response.skipped_executions == 1+ assert response.results == [skipped_result]diff --git a/autogpt_platform/backend/backend/blocks/_base.py b/autogpt_platform/backend/backend/blocks/_base.pyindex fb8111dc92..78ee113730 100644--- a/autogpt_platform/backend/backend/blocks/_base.py+++ b/autogpt_platform/backend/backend/blocks/_base.py@@ -38,6 +38,7 @@ from backend.util.exceptions import (BlockInputError,BlockOutputError,BlockUnknownError,+ InsufficientBalanceError,)from backend.util.settings import Config@@ -737,8 +738,8 @@ class Block(ABC, Generic[BlockSchemaInputType, BlockSchemaOutputType]):):yield output_name, output_dataexcept Exception as ex:- if isinstance(ex, BlockError):- raise ex+ if isinstance(ex, (BlockError, InsufficientBalanceError)):+ raiseelse:raise (BlockExecutionErrordiff --git a/autogpt_platform/backend/backend/blocks/test/test_block.py b/autogpt_platform/backend/backend/blocks/test/test_block.pyindex 719dd600d5..1c589a577a 100644--- a/autogpt_platform/backend/backend/blocks/test/test_block.py+++ b/autogpt_platform/backend/backend/blocks/test/test_block.py@@ -5,8 +5,10 @@ import pytestfrom backend.blocks import get_blocksfrom backend.blocks._base import Block, BlockSchemaInputfrom backend.blocks.io import AgentDropdownInputBlock, AgentInputBlock+from backend.data.execution import ExecutionContextfrom backend.data.graph import BaseGraphfrom backend.data.model import SchemaField+from backend.util.exceptions import InsufficientBalanceErrorfrom backend.util.test import execute_block_testSKIP_BLOCK_TESTS = {@@ -14,6 +16,28 @@ SKIP_BLOCK_TESTS = {}+async def test_execute_preserves_insufficient_balance_error_type():+ error = InsufficientBalanceError(+ message="Producer wording is irrelevant to classification",+ user_id="user-1",+ balance=0,+ amount=1,+ )++ class BalanceFailingBlock(Block):+ async def run(self, input_data, **kwargs):+ raise error+ yield++ block = BalanceFailingBlock(id="credit-failure-block")++ with pytest.raises(InsufficientBalanceError) as exc_info:+ async for _ in block.execute({}, execution_context=ExecutionContext()):+ pass++ assert exc_info.value is error++@pytest.mark.parametrize("block", get_blocks().values(), ids=lambda b: b().name)async def test_available_blocks(block: Type[Block]):block_instance = block()diff --git a/autogpt_platform/backend/backend/data/execution.py b/autogpt_platform/backend/backend/data/execution.pyindex 60efeace7d..c7ac3236ba 100644--- a/autogpt_platform/backend/backend/data/execution.py+++ b/autogpt_platform/backend/backend/data/execution.py@@ -49,7 +49,12 @@ from backend.blocks import get_block, get_io_block_ids, get_webhook_block_idsfrom backend.blocks._base import BlockTypefrom backend.data.tenancy import get_user_team_ids, visibility_filterfrom backend.util import type as type_utils-from backend.util.exceptions import DatabaseError, NotFoundError+from backend.util.exceptions import (+ DatabaseError,+ ExecutionFailureReason,+ NotFoundError,+ get_execution_failure_reason,+)from backend.util.json import SafeJsonfrom backend.util.models import Paginationfrom backend.util.retry import func_retry@@ -246,6 +251,10 @@ class GraphExecutionMeta(BaseDbModel):default=None,description="Error message if any",)+ failure_reason: ExecutionFailureReason | None = Field(+ default=None,+ description="Structured reason for a terminal execution failure",+ )activity_status: str | None = Field(default=None,description="AI-generated summary of what the agent did",@@ -265,6 +274,7 @@ class GraphExecutionMeta(BaseDbModel):node_count=self.node_exec_count,node_error_count=self.node_error_count,error=self.error,+ failure_reason=self.failure_reason,activity_status=self.activity_status,correctness_score=self.correctness_score,)@@ -281,6 +291,7 @@ class GraphExecutionMeta(BaseDbModel):def from_db(_graph_exec: AgentGraphExecution):start_time = _graph_exec.startedAtend_time = _graph_exec.endedAt+ execution_status = ExecutionStatus(_graph_exec.executionStatus)try:stats = GraphExecutionStats.model_validate(_graph_exec.stats)@@ -292,6 +303,19 @@ class GraphExecutionMeta(BaseDbModel):)stats = None+ failure_reason = stats.failure_reason if stats else None+ if (+ stats+ and failure_reason is None+ and execution_status == ExecutionStatus.FAILED+ ):+ # Historical error text may include provider-controlled content, so+ # this compatibility path accepts only the anchored full-message forms.+ failure_reason = get_execution_failure_reason(+ stats.error,+ allow_legacy_text=True,+ )+return GraphExecutionMeta(id=_graph_exec.id,user_id=_graph_exec.userId,@@ -310,7 +334,7 @@ class GraphExecutionMeta(BaseDbModel):dict[str, BlockInput] | None, _graph_exec.nodesInputMasks),preset_id=_graph_exec.agentPresetId,- status=ExecutionStatus(_graph_exec.executionStatus),+ status=execution_status,started_at=start_time,ended_at=end_time,stats=(@@ -327,6 +351,7 @@ class GraphExecutionMeta(BaseDbModel):if isinstance(stats.error, Exception)else stats.error),+ failure_reason=failure_reason,activity_status=stats.activity_status,correctness_score=stats.correctness_score,)diff --git a/autogpt_platform/backend/backend/data/execution_stats_test.py b/autogpt_platform/backend/backend/data/execution_stats_test.pynew file mode 100644index 0000000000..5c8666f247--- /dev/null+++ b/autogpt_platform/backend/backend/data/execution_stats_test.py@@ -0,0 +1,101 @@+from types import SimpleNamespace++import pytest++from backend.data.execution import ExecutionStatus, GraphExecutionMeta+from backend.util.exceptions import ExecutionFailureReason+++def _db_execution(*, status: ExecutionStatus, stats: dict):+ return SimpleNamespace(+ id="exec-1",+ userId="user-1",+ agentGraphId="graph-1",+ agentGraphVersion=1,+ inputs=None,+ credentialInputs=None,+ nodesInputMasks=None,+ agentPresetId=None,+ executionStatus=status,+ startedAt=None,+ endedAt=None,+ stats=stats,+ isShared=False,+ shareToken=None,+ organizationId=None,+ teamId=None,+ expertId=None,+ )+++def test_failure_reason_round_trips_through_api_stats():+ stats = GraphExecutionMeta.Stats(+ error="Organization has 0 credits but needs 10",+ failure_reason=ExecutionFailureReason.INSUFFICIENT_BALANCE,+ activity_status="The available credit balance was insufficient.",+ correctness_score=0.0,+ )++ persisted = stats.to_db()++ assert persisted.failure_reason == ExecutionFailureReason.INSUFFICIENT_BALANCE+ assert persisted.model_dump()["failure_reason"] == (+ ExecutionFailureReason.INSUFFICIENT_BALANCE+ )+ assert persisted.model_dump(mode="json")["failure_reason"] == (+ "insufficient_balance"+ )+ assert persisted.correctness_score == 0.0+++ ("status", "expected_reason"),+ [+ (ExecutionStatus.FAILED, ExecutionFailureReason.INSUFFICIENT_BALANCE),+ (ExecutionStatus.COMPLETED, None),+ ],+)+def test_legacy_failure_reason_is_derived_only_for_failed_executions(+ status,+ expected_reason,+):+ execution = GraphExecutionMeta.from_db(+ _db_execution(+ status=status,+ stats={+ "error": "Organization has 0 credits but needs 10",+ "activity_status": None,+ "correctness_score": None,+ },+ )+ )++ assert execution.stats is not None+ assert execution.stats.failure_reason == expected_reason+++def test_failed_execution_without_error_has_no_derived_failure_reason():+ execution = GraphExecutionMeta.from_db(+ _db_execution(+ status=ExecutionStatus.FAILED,+ stats={"error": None},+ )+ )++ assert execution.stats is not None+ assert execution.stats.failure_reason is None+++def test_persisted_failure_reason_is_preserved():+ execution = GraphExecutionMeta.from_db(+ _db_execution(+ status=ExecutionStatus.FAILED,+ stats={+ "error": "Producer wording can change",+ "failure_reason": "insufficient_balance",+ },+ )+ )++ assert execution.stats is not None+ assert execution.stats.failure_reason == ExecutionFailureReason.INSUFFICIENT_BALANCEdiff --git a/autogpt_platform/backend/backend/data/model.py b/autogpt_platform/backend/backend/data/model.pyindex c4d0c872e4..5c0cd5873c 100644--- a/autogpt_platform/backend/backend/data/model.py+++ b/autogpt_platform/backend/backend/data/model.py@@ -43,6 +43,7 @@ from typing_extensions import TypedDictfrom backend.data.onboarding_steps import OnboardingStepfrom backend.integrations.providers import ProviderName+from backend.util.exceptions import ExecutionFailureReasonfrom backend.util.json import loads as json_loadsfrom backend.util.request import parse_urlfrom backend.util.settings import Secrets@@ -970,6 +971,10 @@ class GraphExecutionStats(BaseModel):)error: Optional[Exception | str] = None+ failure_reason: Optional[ExecutionFailureReason] = Field(+ default=None,+ description="Structured reason for a terminal execution failure",+ )walltime: float = Field(default=0, description="Time between start and end of run (seconds)")diff --git a/autogpt_platform/backend/backend/executor/activity_status_generator.py b/autogpt_platform/backend/backend/executor/activity_status_generator.pyindex 2285e55bdd..c45e65c75f 100644--- a/autogpt_platform/backend/backend/executor/activity_status_generator.py+++ b/autogpt_platform/backend/backend/executor/activity_status_generator.py@@ -21,6 +21,7 @@ from backend.data.model import GraphExecutionStatsfrom backend.data.platform_cost import PlatformCostEntry, usd_to_microdollarsfrom backend.executor.cost_tracking import schedule_platform_cost_logfrom backend.util.clients import get_openai_client, openrouter_helper_cost_provider+from backend.util.exceptions import ExecutionFailureReasonfrom backend.util.feature_flag import Flag, is_feature_enabledfrom backend.util.truncate import truncate@@ -44,6 +45,11 @@ _MAX_OUTPUT_TOKENS = 150# supply an explicit value — same pattern ``ChatConfig._apply_local_aux_models``# uses for ``title_model`` / ``simulation_model``._DEFAULT_MODEL_NAME = "gpt-4o-mini"+INSUFFICIENT_BALANCE_GUIDANCE = "Please make more credits available and try again."+INSUFFICIENT_BALANCE_SUMMARY = (+ "This run couldn't complete because there weren't enough credits available. "+ f"{INSUFFICIENT_BALANCE_GUIDANCE}"+)# Default system prompt template for activity status generation@@ -197,6 +203,28 @@ def _truncate_uuid(uuid_str: str) -> str:return uuid_str.split("-")[0] if "-" in uuid_str else uuid_str[:8]+def _get_deterministic_failure_response(+ execution_stats: GraphExecutionStats,+ execution_status: ExecutionStatus | None,+) -> ActivityStatusResponse | None:+ """+ Check if the execution failed for an obvious, deterministic reason+ that doesn't require LLM analysis.++ Returns a static ActivityStatusResponse if matched, None otherwise.+ """+ if execution_status != ExecutionStatus.FAILED:+ return None++ if execution_stats.failure_reason == ExecutionFailureReason.INSUFFICIENT_BALANCE:+ return {+ "activity_status": INSUFFICIENT_BALANCE_SUMMARY,+ "correctness_score": 0.0,+ }++ return None++async def generate_activity_status_for_execution(graph_exec_id: str,graph_id: str,@@ -212,10 +240,10 @@ async def generate_activity_status_for_execution(skip_existing: bool = True,) -> ActivityStatusResponse | None:"""- Generate an AI-based activity status summary and correctness assessment for a graph execution.+ Generate an activity status summary and correctness assessment for a graph execution.- This function handles all the data collection and AI generation logic,- keeping the manager integration simple.+ Deterministic terminal failures return a static result. Other executions use+ the configured LLM after the required execution data is collected.Args:graph_exec_id: The graph execution ID@@ -232,8 +260,8 @@ async def generate_activity_status_for_execution(skip_existing: Whether to skip if activity_status and correctness_score already existReturns:- AI-generated activity status response with activity_status and correctness_status,- or None if feature is disabled or skipped+ Activity status response with activity_status and correctness_score, or+ None if generation is disabled or skipped"""# Check LaunchDarkly feature flag for AI activity status generation with full context supportif not skip_feature_flag and not await is_feature_enabled(@@ -242,7 +270,7 @@ async def generate_activity_status_for_execution(logger.debug("AI activity status generation is disabled via LaunchDarkly")return None- # Check if we should skip existing data (for admin regeneration option)+ # Check if we should skip existing data (for admin regeneration option).if (skip_existingand execution_stats.activity_status@@ -256,6 +284,16 @@ async def generate_activity_status_for_execution("correctness_score": execution_stats.correctness_score,}+ # Check for deterministic failures that don't need LLM analysis.+ deterministic_result = _get_deterministic_failure_response(+ execution_stats, execution_status+ )+ if deterministic_result is not None:+ logger.info(+ f"Skipping LLM analysis for {graph_exec_id}: deterministic failure detected"+ )+ return deterministic_result+# Acquire an OpenRouter-backed (or local-transport) OpenAI client.# Activity-status generation under OpenRouter is only meaningful when we# can record real USD cost in PlatformCostLog; without OpenRouter thediff --git a/autogpt_platform/backend/backend/executor/activity_status_generator_test.py b/autogpt_platform/backend/backend/executor/activity_status_generator_test.pyindex 1612ee0cef..b3d722f227 100644--- a/autogpt_platform/backend/backend/executor/activity_status_generator_test.py+++ b/autogpt_platform/backend/backend/executor/activity_status_generator_test.py@@ -17,8 +17,10 @@ from backend.data.execution import ExecutionStatus, NodeExecutionResultfrom backend.data.model import GraphExecutionStatsfrom backend.executor.activity_status_generator import (_build_execution_summary,+ _get_deterministic_failure_response,generate_activity_status_for_execution,)+from backend.util.exceptions import ExecutionFailureReasondef _make_usage(@@ -1093,3 +1095,142 @@ class TestIntegration:mock_db_client.get_node_executions.assert_not_called()mock_db_client.get_graph_metadata.assert_not_called()mock_db_client.get_graph.assert_not_called()+++class TestDeterministicFailureResponse:+ """Tests for structured failures that skip LLM analysis."""++ def test_structured_credit_failure_returns_zero_score(self):+ stats = GraphExecutionStats(+ failure_reason=ExecutionFailureReason.INSUFFICIENT_BALANCE+ )++ result = _get_deterministic_failure_response(stats, ExecutionStatus.FAILED)++ assert result is not None+ assert result["correctness_score"] == 0.0+ assert "enough credits" in result["activity_status"].lower()+ assert "billing owner" not in result["activity_status"].lower()++ @pytest.mark.parametrize(+ "status",+ [ExecutionStatus.COMPLETED, ExecutionStatus.TERMINATED, None],+ )+ def test_non_failed_status_does_not_use_deterministic_response(self, status):+ stats = GraphExecutionStats(+ failure_reason=ExecutionFailureReason.INSUFFICIENT_BALANCE+ )++ assert _get_deterministic_failure_response(stats, status) is None++ def test_credit_like_error_text_is_not_trusted(self):+ stats = GraphExecutionStats(+ error="Third-party API says insufficient balance to run this request"+ )++ result = _get_deterministic_failure_response(stats, ExecutionStatus.FAILED)++ assert result is None++ def test_terminated_credit_text_does_not_use_deterministic_response(self):+ stats = GraphExecutionStats(error="You have no credits left to run an agent.")++ result = _get_deterministic_failure_response(stats, ExecutionStatus.TERMINATED)++ assert result is None++ @pytest.mark.asyncio+ async def test_non_credit_failed_execution_reaches_llm_path(self):+ stats = GraphExecutionStats(error="Connection timeout")+ mock_db_client = AsyncMock()++ with patch(+ "backend.executor.activity_status_generator.get_openai_client",+ return_value=None,+ ) as mock_get_openai_client:+ result = await generate_activity_status_for_execution(+ graph_exec_id="test_exec",+ graph_id="test_graph",+ graph_version=1,+ execution_stats=stats,+ db_client=mock_db_client,+ user_id="test_user",+ execution_status=ExecutionStatus.FAILED,+ skip_feature_flag=True,+ )++ assert result is None+ mock_get_openai_client.assert_called_once_with(prefer_openrouter=True)++ @pytest.mark.asyncio+ async def test_generate_skips_llm_for_structured_credit_failure(self):+ stats = GraphExecutionStats(+ failure_reason=ExecutionFailureReason.INSUFFICIENT_BALANCE,+ node_count=0,+ node_error_count=0,+ )+ mock_db_client = AsyncMock()++ with patch(+ "backend.executor.activity_status_generator.get_openai_client"+ ) as mock_get_openai_client:+ result = await generate_activity_status_for_execution(+ graph_exec_id="test_exec",+ graph_id="test_graph",+ graph_version=1,+ execution_stats=stats,+ db_client=mock_db_client,+ user_id="test_user",+ execution_status=ExecutionStatus.FAILED,+ skip_feature_flag=True,+ )++ assert result is not None+ assert result["correctness_score"] == 0.0+ assert "credits" in result["activity_status"].lower()+ mock_db_client.get_node_executions.assert_not_called()+ mock_db_client.get_graph_metadata.assert_not_called()+ mock_db_client.get_graph.assert_not_called()+ mock_get_openai_client.assert_not_called()++ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ ("correctness_score", "skip_existing", "expect_existing"),+ [(0.0, True, True), (None, True, False), (0.8, False, False)],+ )+ async def test_skip_existing_requires_complete_analysis(+ self,+ correctness_score,+ skip_existing,+ expect_existing,+ ):+ stats = GraphExecutionStats(+ activity_status="Existing summary",+ correctness_score=correctness_score,+ )+ mock_db_client = AsyncMock()++ with patch(+ "backend.executor.activity_status_generator.get_openai_client",+ return_value=None,+ ) as mock_get_openai_client:+ result = await generate_activity_status_for_execution(+ graph_exec_id="test_exec",+ graph_id="test_graph",+ graph_version=1,+ execution_stats=stats,+ db_client=mock_db_client,+ user_id="test_user",+ skip_feature_flag=True,+ skip_existing=skip_existing,+ )++ if expect_existing:+ assert result == {+ "activity_status": "Existing summary",+ "correctness_score": correctness_score,+ }+ mock_get_openai_client.assert_not_called()+ else:+ assert result is None+ mock_get_openai_client.assert_called_once()diff --git a/autogpt_platform/backend/backend/executor/manager.py b/autogpt_platform/backend/backend/executor/manager.pyindex 23329a46a4..a21dee4eb2 100644--- a/autogpt_platform/backend/backend/executor/manager.py+++ b/autogpt_platform/backend/backend/executor/manager.py@@ -65,10 +65,12 @@ from backend.util.decorator import (time_measured,)from backend.util.exceptions import (+ ExecutionFailureReason,GraphNotFoundError,InsufficientBalanceError,ModerationError,NotFoundError,+ get_execution_failure_reason,)from backend.util.file import clean_exec_filesfrom backend.util.logging import TruncatedLogger, configure_logging@@ -81,7 +83,10 @@ from backend.util.retry import (from backend.util.settings import Settingsfrom . import billing, expert_posts-from .activity_status_generator import generate_activity_status_for_execution+from .activity_status_generator import (+ INSUFFICIENT_BALANCE_GUIDANCE,+ generate_activity_status_for_execution,+)from .auto_credentials import acquire_auto_credentialsfrom .automod.manager import automod_managerfrom .cluster_lock import ClusterLock@@ -111,6 +116,55 @@ _logger = logging.getLogger(__name__)logger = TruncatedLogger(_logger, prefix="[GraphExecutor]")settings = Settings()++def _get_execution_credit_balance(+ db_client: "DatabaseManagerClient",+ graph_exec: GraphExecutionEntry,+) -> int:+ """Return the balance for the wallet billed by this execution."""+ organization_id = graph_exec.execution_context.organization_id+ if organization_id:+ return db_client.get_org_credits(org_id=organization_id)+ return db_client.get_credits(graph_exec.user_id)+++def _record_execution_failure(+ execution_stats: GraphExecutionStats,+ error: BaseException,+) -> None:+ """Record an error without erasing a trusted reason promoted by a node.++ Precedence is deliberately asymmetric between the two fields:++ ``error`` always reflects the *latest* failure, so the message a user sees+ describes what actually terminated the run.++ ``failure_reason`` is *sticky*: once a typed failure (currently only+ :class:`InsufficientBalanceError`) has been promoted from a node via+ :func:`_propagate_node_failure`, a later untyped error cannot clear it.+ An exhausted wallet is the root cause of whatever fails next, and losing+ that reason would send the run back to LLM analysis — the exact cost this+ module exists to avoid. Only another typed classification may replace it.++ The trade-off: when a run hits a credit failure *and* a later unrelated+ typed-less terminal error, the deterministic summary attributes the run to+ the credit failure while ``error`` names the later one. That is intended;+ the credit condition is the actionable one for the user.+ """+ if failure_reason := get_execution_failure_reason(error):+ execution_stats.failure_reason = failure_reason+ execution_stats.error = str(error) or type(error).__name__+++def _propagate_node_failure(+ graph_stats: GraphExecutionStats,+ node_error: BaseException,+) -> None:+ """Promote only trusted, typed node failures to graph-level stats."""+ if get_execution_failure_reason(node_error):+ _record_execution_failure(graph_stats, node_error)++active_runs_gauge = Gauge("execution_manager_active_runs", "Number of active graph runs")@@ -720,6 +774,7 @@ class ExecutionProcessor:)if isinstance(execution_stats.error, Exception):graph_stats.node_error_count += 1+ _propagate_node_failure(graph_stats, execution_stats.error)node_error = execution_stats.errornode_stats = execution_stats.model_dump()@@ -924,16 +979,6 @@ class ExecutionProcessor:graph_exec_id=graph_exec.graph_exec_id,status=ExecutionStatus.RUNNING,)- elif exec_meta.status == ExecutionStatus.FAILED:- exec_meta.status = ExecutionStatus.RUNNING- log_metadata.info(- f"⚙️ Graph execution #{graph_exec.graph_exec_id} was disturbed, continuing where it left off."- )- update_graph_execution_state(- db_client=db_client,- graph_exec_id=graph_exec.graph_exec_id,- status=ExecutionStatus.RUNNING,- )else:log_metadata.warning(f"Skipped graph execution {graph_exec.graph_exec_id}, the graph execution status is `{exec_meta.status}`."@@ -948,6 +993,12 @@ class ExecutionProcessor:exec_stats = exec_meta.stats.to_db()exec_stats.is_dry_run = graph_exec.execution_context.dry_run+ # Analysis is terminal-only, so discard prior interpretation before continuing.+ exec_stats.error = None+ exec_stats.failure_reason = None+ exec_stats.activity_status = None+ exec_stats.correctness_score = None+timing_info, status = self._on_graph_execution(graph_exec=graph_exec,cancel=cancel,@@ -1046,14 +1097,20 @@ class ExecutionProcessor:try:if (not graph_exec.execution_context.dry_run- and db_client.get_credits(graph_exec.user_id) <= 0+ and settings.config.enable_credit):- raise InsufficientBalanceError(- user_id=graph_exec.user_id,- message="You have no credits left to run an agent.",- balance=0,- amount=1,- )+ credit_balance = _get_execution_credit_balance(db_client, graph_exec)+ required_balance = 1+ if credit_balance < required_balance:+ raise InsufficientBalanceError(+ user_id=graph_exec.user_id,+ message=(+ f"At least {required_balance} credit must be available to run "+ f"this agent. {INSUFFICIENT_BALANCE_GUIDANCE}"+ ),+ balance=credit_balance,+ amount=required_balance,+ )# Input moderationtry:@@ -1269,7 +1326,11 @@ class ExecutionProcessor:# Determine final execution status based on whether there was an error or terminationif cancel.is_set():execution_status = ExecutionStatus.TERMINATED- elif error is not None:+ elif (+ error is not None+ or execution_stats.failure_reason+ == ExecutionFailureReason.INSUFFICIENT_BALANCE+ ):execution_status = ExecutionStatus.FAILEDelse:if db_client.has_pending_reviews_for_graph_exec(@@ -1280,7 +1341,7 @@ class ExecutionProcessor:execution_status = ExecutionStatus.COMPLETEDif error:- execution_stats.error = str(error) or type(error).__name__+ _record_execution_failure(execution_stats, error)return execution_status@@ -1290,8 +1351,7 @@ class ExecutionProcessor:if isinstance(e, Exception)else Exception(f"{e.__class__.__name__}: {e}"))- if not execution_stats.error:- execution_stats.error = str(error)+ _record_execution_failure(execution_stats, error)known_errors = (InsufficientBalanceError, ModerationError)if isinstance(error, known_errors):diff --git a/autogpt_platform/backend/backend/executor/manager_activity_status_test.py b/autogpt_platform/backend/backend/executor/manager_activity_status_test.pynew file mode 100644index 0000000000..c4b49d4080--- /dev/null+++ b/autogpt_platform/backend/backend/executor/manager_activity_status_test.py@@ -0,0 +1,332 @@+import threading+from types import SimpleNamespace+from unittest.mock import MagicMock, patch++import pytest++from backend.data.execution import (+ ExecutionContext,+ ExecutionStatus,+ GraphExecutionEntry,+ GraphExecutionMeta,+)+from backend.data.model import GraphExecutionStats+from backend.executor.manager import (+ ExecutionProcessor,+ _get_execution_credit_balance,+ _propagate_node_failure,+ _record_execution_failure,+)+from backend.util.decorator import TimingInfo+from backend.util.exceptions import ExecutionFailureReason, InsufficientBalanceError+++def test_continued_execution_clears_prior_terminal_analysis():+ execution = GraphExecutionEntry(+ user_id="user-1",+ graph_exec_id="exec-1",+ graph_id="graph-1",+ graph_version=1,+ )+ execution_meta = SimpleNamespace(+ status=ExecutionStatus.RUNNING,+ stats=GraphExecutionMeta.Stats(+ error="You have no credits left to run an agent.",+ failure_reason=ExecutionFailureReason.INSUFFICIENT_BALANCE,+ activity_status="The prior attempt ran out of credits.",+ correctness_score=0.0,+ cost=27,+ node_exec_count=3,+ ),+ )+ db_client = MagicMock()+ db_client.get_graph_execution_meta.return_value = execution_meta+ processor = ExecutionProcessor()+ processor._on_graph_execution = MagicMock(+ return_value=(+ TimingInfo(cpu_time=0.0, wall_time=0.0),+ ExecutionStatus.TERMINATED,+ )+ )++ with (+ patch("backend.executor.manager.get_db_client", return_value=db_client),+ patch("backend.executor.manager.send_execution_update"),+ patch("backend.executor.manager.update_graph_execution_state"),+ patch("backend.executor.manager.billing.handle_agent_run_notif"),+ patch("backend.executor.manager.expert_posts.handle_expert_run_post"),+ ):+ processor.on_graph_execution(+ execution,+ threading.Event(),+ MagicMock(),+ )++ resumed_stats = processor._on_graph_execution.call_args.kwargs["execution_stats"]+ assert resumed_stats.error is None+ assert resumed_stats.failure_reason is None+ assert resumed_stats.activity_status is None+ assert resumed_stats.correctness_score is None+ assert resumed_stats.cost == 27+ assert resumed_stats.node_count == 3+++def test_failed_execution_is_not_continued():+ execution = GraphExecutionEntry(+ user_id="user-1",+ graph_exec_id="exec-1",+ graph_id="graph-1",+ graph_version=1,+ )+ db_client = MagicMock()+ db_client.get_graph_execution_meta.return_value = SimpleNamespace(+ status=ExecutionStatus.FAILED,+ stats=GraphExecutionMeta.Stats(+ error="You have no credits left to run an agent.",+ failure_reason=ExecutionFailureReason.INSUFFICIENT_BALANCE,+ activity_status="The prior attempt ran out of credits.",+ correctness_score=0.0,+ ),+ )+ processor = ExecutionProcessor()+ processor._on_graph_execution = MagicMock()++ with patch("backend.executor.manager.get_db_client", return_value=db_client):+ processor.on_graph_execution(+ execution,+ threading.Event(),+ MagicMock(),+ )++ processor._on_graph_execution.assert_not_called()+ db_client.update_graph_execution_start_time.assert_not_called()+++def test_execution_credit_balance_uses_organization_aware_lookup():+ execution = GraphExecutionEntry(+ user_id="user-1",+ graph_exec_id="exec-1",+ graph_id="graph-1",+ graph_version=1,+ execution_context=ExecutionContext(organization_id="org-1"),+ )+ db_client = MagicMock()+ db_client.get_org_credits.return_value = 500+ db_client.get_credits.return_value = 0++ assert _get_execution_credit_balance(db_client, execution) == 500+ db_client.get_org_credits.assert_called_once_with(org_id="org-1")+ db_client.get_credits.assert_not_called()+++def test_execution_credit_balance_uses_user_wallet_without_organization():+ execution = GraphExecutionEntry(+ user_id="user-1",+ graph_exec_id="exec-1",+ graph_id="graph-1",+ graph_version=1,+ )+ db_client = MagicMock()+ db_client.get_credits.return_value = 250++ assert _get_execution_credit_balance(db_client, execution) == 250+ db_client.get_credits.assert_called_once_with("user-1")+ db_client.get_org_credits.assert_not_called()+++def test_nested_credit_failure_is_propagated_to_graph_stats():+ graph_stats = GraphExecutionStats()+ error = InsufficientBalanceError(+ message="Organization has 0 credits but needs 25",+ user_id="user-1",+ balance=0,+ amount=25,+ )++ _propagate_node_failure(graph_stats, error)++ assert graph_stats.error == str(error)+ assert graph_stats.failure_reason == ExecutionFailureReason.INSUFFICIENT_BALANCE+++def test_graph_error_does_not_erase_promoted_credit_failure_reason():+ graph_stats = GraphExecutionStats(+ error="Organization has 0 credits but needs 25",+ failure_reason=ExecutionFailureReason.INSUFFICIENT_BALANCE,+ )++ _record_execution_failure(graph_stats, RuntimeError("Output moderation failed"))++ assert graph_stats.error == "Output moderation failed"+ assert graph_stats.failure_reason == ExecutionFailureReason.INSUFFICIENT_BALANCE+++def test_credit_node_failure_replaces_prior_graph_error():+ graph_stats = GraphExecutionStats(error="Earlier non-credit node error")+ error = InsufficientBalanceError(+ message="Organization has 0 credits but needs 25",+ user_id="user-1",+ balance=0,+ amount=25,+ )++ _propagate_node_failure(graph_stats, error)++ assert graph_stats.error == str(error)+ assert graph_stats.failure_reason == ExecutionFailureReason.INSUFFICIENT_BALANCE+++def test_untyped_node_failure_is_not_promoted_to_graph_failure():+ graph_stats = GraphExecutionStats()++ _propagate_node_failure(+ graph_stats,+ RuntimeError("Third-party API reported insufficient balance"),+ )++ assert graph_stats.error is None+ assert graph_stats.failure_reason is None++[email protected]("credit_balance", [0, -25])+def test_graph_start_credit_failure_records_structured_reason(credit_balance):+ execution = GraphExecutionEntry(+ user_id="user-1",+ graph_exec_id="exec-1",+ graph_id="graph-1",+ graph_version=1,+ execution_context=ExecutionContext(organization_id="org-1"),+ )+ db_client = MagicMock()+ db_client.get_org_credits.return_value = credit_balance+ processor = ExecutionProcessor()+ processor._cleanup_graph_execution = MagicMock()+ stats = GraphExecutionStats()++ with (+ patch("backend.executor.manager.get_db_client", return_value=db_client),+ patch("backend.executor.manager.settings.config.enable_credit", True),+ ):+ _, status = processor._on_graph_execution(+ graph_exec=execution,+ cancel=threading.Event(),+ log_metadata=MagicMock(),+ execution_stats=stats,+ cluster_lock=MagicMock(),+ )++ assert status == ExecutionStatus.FAILED+ assert stats.failure_reason == ExecutionFailureReason.INSUFFICIENT_BALANCE+ assert stats.error == (+ "At least 1 credit must be available to run this agent. "+ "Please make more credits available and try again."+ )+ db_client.get_org_credits.assert_called_once_with(org_id="org-1")+ db_client.get_credits.assert_not_called()+++def test_graph_start_skips_balance_check_when_credits_are_disabled():+ execution = GraphExecutionEntry(+ user_id="user-1",+ graph_exec_id="exec-1",+ graph_id="graph-1",+ graph_version=1,+ execution_context=ExecutionContext(organization_id="org-1"),+ )+ db_client = MagicMock()+ db_client.get_node_executions.return_value = []+ db_client.has_pending_reviews_for_graph_exec.return_value = False+ processor = ExecutionProcessor()+ processor._cleanup_graph_execution = MagicMock()+ processor.node_evaluation_loop = MagicMock()+ stats = GraphExecutionStats()+ completed_future = MagicMock()+ completed_future.result.return_value = None++ def complete_coroutine(coroutine, _loop):+ coroutine.close()+ return completed_future++ with (+ patch("backend.executor.manager.get_db_client", return_value=db_client),+ patch("backend.executor.manager.settings.config.enable_credit", False),+ patch(+ "backend.executor.manager.asyncio.run_coroutine_threadsafe",+ side_effect=complete_coroutine,+ ),+ ):+ _, status = processor._on_graph_execution(+ graph_exec=execution,+ cancel=threading.Event(),+ log_metadata=MagicMock(),+ execution_stats=stats,+ cluster_lock=MagicMock(),+ )++ assert status == ExecutionStatus.COMPLETED+ db_client.get_org_credits.assert_not_called()+ db_client.get_credits.assert_not_called()+++ ("cancelled", "expected_status"),+ [+ (False, ExecutionStatus.FAILED),+ (True, ExecutionStatus.TERMINATED),+ ],+)+def test_nested_credit_failure_marker_respects_cancellation_precedence(+ cancelled, expected_status+):+ execution = GraphExecutionEntry(+ user_id="user-1",+ graph_exec_id="exec-1",+ graph_id="graph-1",+ graph_version=1,+ )+ db_client = MagicMock()+ db_client.get_credits.return_value = 100+ db_client.get_node_executions.return_value = []+ db_client.has_pending_reviews_for_graph_exec.return_value = False+ processor = ExecutionProcessor()+ processor._cleanup_graph_execution = MagicMock()+ processor.node_evaluation_loop = MagicMock()+ stats = GraphExecutionStats()+ _propagate_node_failure(+ stats,+ InsufficientBalanceError(+ message="Organization has 0 credits but needs 25",+ user_id="user-1",+ balance=0,+ amount=25,+ ),+ )+ completed_future = MagicMock()+ completed_future.result.return_value = None++ def complete_coroutine(coroutine, _loop):+ coroutine.close()+ return completed_future++ cancel = threading.Event()+ if cancelled:+ cancel.set()++ with (+ patch("backend.executor.manager.get_db_client", return_value=db_client),+ patch(+ "backend.executor.manager.asyncio.run_coroutine_threadsafe",+ side_effect=complete_coroutine,+ ),+ ):+ _, status = processor._on_graph_execution(+ graph_exec=execution,+ cancel=cancel,+ log_metadata=MagicMock(),+ execution_stats=stats,+ cluster_lock=MagicMock(),+ )++ assert status == expected_status+ assert stats.failure_reason == ExecutionFailureReason.INSUFFICIENT_BALANCE+ assert stats.error == "Organization has 0 credits but needs 25"diff --git a/autogpt_platform/backend/backend/util/exceptions.py b/autogpt_platform/backend/backend/util/exceptions.pyindex 7d7f81e316..77396d1275 100644--- a/autogpt_platform/backend/backend/util/exceptions.py+++ b/autogpt_platform/backend/backend/util/exceptions.py@@ -1,3 +1,5 @@+import re+from enum import Enumfrom typing import Mapping@@ -110,6 +112,49 @@ class InsufficientBalanceError(ValueError):return self.message+class ExecutionFailureReason(str, Enum):+ """Structured reasons for terminal graph execution failures."""++ INSUFFICIENT_BALANCE = "insufficient_balance"+++# Keep this legacy-only fallback synchronized with the equivalent predicates in+# autogpt_platform/analytics/queries/graph_execution.sql and the shared corpus in+# exceptions_test.py. Live failures are classified by type, never by these messages.+_LEGACY_INSUFFICIENT_BALANCE_PATTERNS = (+ re.compile(r"You have no credits left to run an agent\."),+ re.compile(+ r"Insufficient balance of \$-?\d+(?:\.\d+)?, "+ r"where this will cost \$-?\d+(?:\.\d+)?"+ ),+ re.compile(+ r"Insufficient balance to run [A-Za-z_][A-Za-z0-9_]*: "+ r"dynamic-cost blocks require a positive balance\."+ ),+ re.compile(r"Organization has -?\d+ credits but needs \d+"),+)+++def get_execution_failure_reason(+ error: BaseException | str | None,+ *,+ allow_legacy_text: bool = False,+) -> ExecutionFailureReason | None:+ """Classify trusted exceptions, with an opt-in fallback for persisted text."""+ if isinstance(error, InsufficientBalanceError):+ return ExecutionFailureReason.INSUFFICIENT_BALANCE+ if (+ allow_legacy_text+ and isinstance(error, str)+ and any(+ pattern.fullmatch(error)+ for pattern in _LEGACY_INSUFFICIENT_BALANCE_PATTERNS+ )+ ):+ return ExecutionFailureReason.INSUFFICIENT_BALANCE+ return None++class ModerationError(ValueError):"""Content moderation failure during execution"""diff --git a/autogpt_platform/backend/backend/util/exceptions_test.py b/autogpt_platform/backend/backend/util/exceptions_test.pyindex 4108aba4f9..208abda730 100644--- a/autogpt_platform/backend/backend/util/exceptions_test.py+++ b/autogpt_platform/backend/backend/util/exceptions_test.py@@ -1,12 +1,138 @@+import re+from pathlib import Path++import pytest+from backend.util.exceptions import (BlockError,BlockExecutionError,BlockInputError,BlockOutputError,BlockUnknownError,+ ExecutionFailureReason,+ InsufficientBalanceError,+ get_execution_failure_reason,+)++_ANALYTICS_QUERIES_DIR = Path(__file__).resolve().parents[3] / "analytics" / "queries"+_GRAPH_EXECUTION_SQL = _ANALYTICS_QUERIES_DIR / "graph_execution.sql"+_SQL_LEGACY_ERROR_PREDICATE = re.compile(+ r"""ge\."stats"::jsonb->>'error'\s*(?P<operator>=|~)\s*'(?P<pattern>(?:''|[^'])*)'"""+)+_SQL_NO_CREDITS_BRANCH = re.compile(+ r"""WHEN\s+CAST\(ge\."executionStatus"\s+AS\s+TEXT\)\s*=\s*'FAILED'\s+AND\s*\(\s*ge\."stats"::jsonb->>'failure_reason'\s*=\s*'insufficient_balance'.*?\)\s*THEN\s+'NO_CREDITS'""",+ re.DOTALL,+)+_LEGACY_BALANCE_CORPUS = (+ ("You have no credits left to run an agent.", True),+ ("Insufficient balance of $0.0, where this will cost $1.25", True),+ ("Insufficient balance of $-1.5, where this will cost $0", True),+ (+ "Insufficient balance to run ReplicateModelBlock: "+ "dynamic-cost blocks require a positive balance.",+ True,+ ),+ ("Organization has 12 credits but needs 25", True),+ ("Organization has -5 credits but needs 25", True),+ ("Third-party API reported insufficient balance", False),+ ("Insufficient balance", False),+ ("prefix: You have no credits left to run an agent.", False),+ ("You have no credits left to run an agent. Please retry.", False),+ ("Organization has some credits but needs more", False),+ ("Organization has 12 credits but needs 25.", False),+ (+ "Insufficient balance to run : "+ "dynamic-cost blocks require a positive balance.",+ False,+ ),+ (+ "Insufficient balance to run Third-party API: "+ "dynamic-cost blocks require a positive balance.",+ False,+ ),)+def _read_graph_execution_sql() -> str:+ """Load the analytics SQL, failing closed on drift inside a source checkout.++ Skipping is only legitimate when the whole ``analytics/queries`` tree is+ absent, i.e. the backend is running from a packaged install (the runtime+ container ships no analytics SQL). When that directory *is* present the+ parity guarantee is in force, so a missing or renamed file is drift and+ must fail rather than silently dropping the Python<->SQL check.+ """+ if _GRAPH_EXECUTION_SQL.exists():+ return _GRAPH_EXECUTION_SQL.read_text(encoding="utf-8")+ if _ANALYTICS_QUERIES_DIR.is_dir():+ pytest.fail(+ f"{_GRAPH_EXECUTION_SQL} is missing while {_ANALYTICS_QUERIES_DIR} "+ "exists: the Python<->SQL legacy-classifier parity check cannot be "+ "verified. Update the path if the query moved."+ )+ pytest.skip("analytics SQL is not included in this backend package")+++def _matches_analytics_sql_legacy_predicate(message: str) -> bool:+ sql = _read_graph_execution_sql()+ predicates = [+ (match["operator"], match["pattern"].replace("''", "'"))+ for match in _SQL_LEGACY_ERROR_PREDICATE.finditer(sql)+ ]+ assert len(predicates) == 4, "Expected all four legacy SQL error predicates"++ for operator, pattern in predicates:+ if operator == "=" and message == pattern:+ return True+ if operator == "~":+ assert pattern.startswith("^") and pattern.endswith("$")+ if re.fullmatch(pattern, message):+ return True+ return False+++def test_typed_insufficient_balance_error_is_classified_by_type():+ error = InsufficientBalanceError(+ message="New producer wording without legacy keywords",+ user_id="user-1",+ balance=0,+ amount=1,+ )++ assert (+ get_execution_failure_reason(error)+ == ExecutionFailureReason.INSUFFICIENT_BALANCE+ )+++def test_analytics_sql_gates_structured_credit_failures_on_failed_status():+ sql = _read_graph_execution_sql()++ assert _SQL_NO_CREDITS_BRANCH.search(sql)+++def test_untyped_balance_error_is_not_classified():+ assert (+ get_execution_failure_reason(+ RuntimeError("New producer wording without legacy keywords")+ )+ is None+ )++[email protected](("message", "expected"), _LEGACY_BALANCE_CORPUS)+def test_legacy_credit_classifier_matches_analytics_sql(message, expected):+ assert get_execution_failure_reason(message) is None+ python_matches = (+ get_execution_failure_reason(message, allow_legacy_text=True)+ == ExecutionFailureReason.INSUFFICIENT_BALANCE+ )+ sql_matches = _matches_analytics_sql_legacy_predicate(message)++ assert python_matches is expected+ assert sql_matches is expected++class TestBlockError:"""Tests for BlockError and its subclasses."""diff --git a/autogpt_platform/backend/backend/util/metrics.py b/autogpt_platform/backend/backend/util/metrics.pyindex fb0235c018..953f5a62ad 100644--- a/autogpt_platform/backend/backend/util/metrics.py+++ b/autogpt_platform/backend/backend/util/metrics.py@@ -23,6 +23,7 @@ except ImportError:LaunchDarklyIntegration = None # type: ignore[assignment,misc]from backend.util import feature_flag+from backend.util.exceptions import get_execution_failure_reasonfrom backend.util.security import SENSITIVE_FIELD_NAMESfrom backend.util.settings import BehaveAs, Settings@@ -196,7 +197,7 @@ def _before_send(event, hint):return None# Expected business logic — insufficient balance- if "insufficient balance" in exc_msg or "no credits left" in exc_msg:+ if get_execution_failure_reason(exc_value) is not None:return None# Expected security check — blocked IP accessdiff --git a/autogpt_platform/backend/backend/util/metrics_test.py b/autogpt_platform/backend/backend/util/metrics_test.pyindex c5ca7508a5..1cbbf3b7c0 100644--- a/autogpt_platform/backend/backend/util/metrics_test.py+++ b/autogpt_platform/backend/backend/util/metrics_test.py@@ -15,6 +15,7 @@ import sysfrom sentry_sdk.consts import DEFAULT_OPTIONSfrom sentry_sdk.utils import event_from_exception+from backend.util.exceptions import InsufficientBalanceErrorfrom backend.util.metrics import (_FALKORDB_DRIVER_LOGGER,_FALKORDB_TEARDOWN_SIGNATURES,@@ -200,6 +201,46 @@ def test_before_send_scrubs_secrets_from_actual_exception_event() -> None:assert "safe-context-value" in serialized+def test_before_send_keeps_untyped_balance_message() -> None:+ try:+ raise RuntimeError("Third-party API reported insufficient balance")+ except RuntimeError:+ exc_info = sys.exc_info()++ assert _before_send({"level": "error"}, hint={"exc_info": exc_info}) is not None+++def test_before_send_drops_typed_insufficient_balance_error() -> None:+ try:+ raise InsufficientBalanceError(+ message="New producer wording without legacy keywords",+ user_id="user-1",+ balance=0,+ amount=1,+ )+ except InsufficientBalanceError:+ exc_info = sys.exc_info()++ assert _before_send({"level": "error"}, hint={"exc_info": exc_info}) is None+++def test_before_send_keeps_wrapper_around_insufficient_balance_error() -> None:+ try:+ try:+ raise InsufficientBalanceError(+ message="New producer wording without legacy keywords",+ user_id="user-1",+ balance=0,+ amount=1,+ )+ except InsufficientBalanceError as error:+ raise RuntimeError("Unexpected execution wrapper") from error+ except RuntimeError:+ exc_info = sys.exc_info()++ assert _before_send({"level": "error"}, hint={"exc_info": exc_info}) is not None++# ---------- FalkorDB connection-teardown noise → dropped ----------diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex 45677580d1..b29ad0eb1a 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -5683,7 +5683,7 @@"post": {"tags": ["v2", "admin", "admin", "execution_analytics"],"summary": "Generate Execution Analytics",- "description": "Generate activity summaries and correctness scores for graph executions.\n\nThis endpoint:\n1. Fetches all completed executions matching the criteria\n2. Identifies executions missing activity_status or correctness_score\n3. Generates missing data using AI in batches\n4. Updates the database with new stats\n5. Returns a detailed report of the analytics operation",+ "description": "Generate activity summaries and correctness scores for graph executions.\n\nThis endpoint:\n1. Fetches all terminal executions matching the criteria\n2. Identifies executions missing a complete activity analysis\n3. Generates missing data in batches, using deterministic results where available\n4. Updates the database with new stats\n5. Returns a detailed report of the analytics operation","operationId": "postV2Generate execution analytics","requestBody": {"content": {@@ -18070,6 +18070,12 @@"title": "ExecutionDiagnosticsResponse","description": "Response model for execution diagnostics"},+ "ExecutionFailureReason": {+ "type": "string",+ "enum": ["insufficient_balance"],+ "title": "ExecutionFailureReason",+ "description": "Structured reasons for terminal graph execution failures."+ },"ExecutionOptions": {"properties": {"manual": { "type": "boolean", "title": "Manual", "default": true },@@ -24428,6 +24434,13 @@"title": "Error","description": "Error message if any"},+ "failure_reason": {+ "anyOf": [+ { "$ref": "#/components/schemas/ExecutionFailureReason" },+ { "type": "null" }+ ],+ "description": "Structured reason for a terminal execution failure"+ },"activity_status": {"anyOf": [{ "type": "string" }, { "type": "null" }],"title": "Activity Status",