: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(aio): don't fail eval emission when team is over billing quota (#74014)
Radu Raicea8412a8517640
diff --git a/posthog/api/capture.py b/posthog/api/capture.pyindex 9b22ccdc75bd..78e172885f67 100644--- a/posthog/api/capture.py+++ b/posthog/api/capture.py@@ -24,6 +24,7 @@ import timefrom concurrent.futures import ThreadPoolExecutor, as_completedfrom dataclasses import dataclass, fieldfrom datetime import UTC, datetime+from http import HTTPStatusfrom typing import Any, Optionalfrom uuid import uuid4@@ -130,6 +131,10 @@ class CaptureInternalError(Exception):super().__init__(message)self.status_code = status_code+ @property+ def is_billing_limit_exceeded(self) -> bool:+ return self.status_code == HTTPStatus.PAYMENT_REQUIRED+@dataclassclass CaptureInternalResult:diff --git a/posthog/temporal/ai_observability/evaluation_workflow_activities.py b/posthog/temporal/ai_observability/evaluation_workflow_activities.pyindex abeb0eb4fded..d7732ef90a28 100644--- a/posthog/temporal/ai_observability/evaluation_workflow_activities.py+++ b/posthog/temporal/ai_observability/evaluation_workflow_activities.py@@ -10,7 +10,7 @@ import structlogimport temporaliofrom structlog.contextvars import bind_contextvars-from posthog.api.capture import capture_internal+from posthog.api.capture import CaptureInternalError, capture_internalfrom posthog.models.team import Teamfrom posthog.sync import database_sync_to_asyncfrom posthog.temporal.ai_observability.evaluation_llm_judge import DEFAULT_JUDGE_MODEL@@ -325,6 +325,13 @@ async def emit_evaluation_event_activity(inputs: EmitEvaluationEventInputs) -> Ntry:await database_sync_to_async(_emit, thread_sensitive=False)()increment_emit_event_outcome("success")+ except CaptureInternalError as e:+ if e.is_billing_limit_exceeded:+ increment_emit_event_outcome("dropped_billing_limited")+ logger.info("Skipping eval event emission; team over billing quota", team_id=event_data["team_id"])+ return+ increment_emit_event_outcome("failed")+ raiseexcept Exception:increment_emit_event_outcome("failed")raisediff --git a/posthog/temporal/ai_observability/metrics.py b/posthog/temporal/ai_observability/metrics.pyindex 5d22afec9379..df42ca1f5abd 100644--- a/posthog/temporal/ai_observability/metrics.py+++ b/posthog/temporal/ai_observability/metrics.py@@ -131,17 +131,19 @@ def increment_tokens(token_type: str, count: int) -> None:def increment_emit_event_outcome(outcome: str) -> None:- """Track $ai_evaluation event emission outcomes (success/failed).+ """Track $ai_evaluation event emission outcomes (success/failed/dropped_billing_limited).Distinguishes Activity 4 failures from other workflow failures so we can- measure and alert on dropped eval events specifically.+ measure and alert on dropped eval events specifically. `dropped_billing_limited`+ is an expected billing condition, not a system failure, so it's kept out of+ the `failed` bucket the error-rate alert watches."""if not activity.in_activity() and not workflow.in_workflow():returnmeter = get_metric_meter({"outcome": outcome})counter = meter.create_counter("llma_eval_emit_event_outcome",- "Outcome of $ai_evaluation event emission (success/failed)",+ "Outcome of $ai_evaluation event emission (success/failed/dropped_billing_limited)",)counter.add(1)diff --git a/posthog/temporal/ai_observability/run_tagger.py b/posthog/temporal/ai_observability/run_tagger.pyindex 4f850710d803..b511633bb1d6 100644--- a/posthog/temporal/ai_observability/run_tagger.py+++ b/posthog/temporal/ai_observability/run_tagger.py@@ -10,7 +10,7 @@ from structlog.contextvars import bind_contextvarsfrom temporalio.common import RetryPolicyfrom temporalio.exceptions import ApplicationError-from posthog.api.capture import capture_internal+from posthog.api.capture import CaptureInternalError, capture_internalfrom posthog.models.team import Teamfrom posthog.sync import database_sync_to_asyncfrom posthog.temporal.ai_observability.evaluation_event_io import extract_event_io@@ -527,7 +527,13 @@ async def emit_tagger_event_activity(inputs: EmitTaggerEventInputs) -> None:)routed_result.raise_for_status()- await database_sync_to_async(_emit, thread_sensitive=False)()+ try:+ await database_sync_to_async(_emit, thread_sensitive=False)()+ except CaptureInternalError as e:+ if e.is_billing_limit_exceeded:+ logger.info("Skipping tag event emission; team over billing quota", team_id=event_data["team_id"])+ return+ raise@temporalio.activity.defndiff --git a/posthog/temporal/ai_observability/run_trace_evaluation.py b/posthog/temporal/ai_observability/run_trace_evaluation.pyindex e4266d558012..8a43df2c3f6e 100644--- a/posthog/temporal/ai_observability/run_trace_evaluation.py+++ b/posthog/temporal/ai_observability/run_trace_evaluation.py@@ -29,7 +29,7 @@ from posthog.schema import DateRange, LLMTrace, QueryLogTags, TraceQueryfrom posthog.hogql import astfrom posthog.hogql.parser import parse_select-from posthog.api.capture import capture_internal+from posthog.api.capture import CaptureInternalError, capture_internalfrom posthog.hogql_queries.ai.ai_table_resolver import query_ai_eventsfrom posthog.hogql_queries.ai.trace_query_runner import TraceQueryRunnerfrom posthog.models.team import Team@@ -643,6 +643,13 @@ async def emit_trace_evaluation_event_activity(inputs: EmitTraceEvaluationEventItry:await database_sync_to_async(_emit, thread_sensitive=False)()increment_emit_event_outcome("success")+ except CaptureInternalError as e:+ if e.is_billing_limit_exceeded:+ increment_emit_event_outcome("dropped_billing_limited")+ logger.info("Skipping eval event emission; team over billing quota", team_id=inputs.team_id)+ return+ increment_emit_event_outcome("failed")+ raiseexcept Exception:increment_emit_event_outcome("failed")raisediff --git a/posthog/temporal/ai_observability/test_run_evaluation.py b/posthog/temporal/ai_observability/test_run_evaluation.pyindex d538268a4199..31cca82409bf 100644--- a/posthog/temporal/ai_observability/test_run_evaluation.py+++ b/posthog/temporal/ai_observability/test_run_evaluation.py@@ -13,6 +13,7 @@ from temporalio.exceptions import ApplicationErrorfrom temporalio.testing import WorkflowEnvironmentfrom temporalio.worker import UnsandboxedWorkflowRunner, Worker+from posthog.api.capture import CaptureInternalErrorfrom posthog.models import Organization, Teamfrom posthog.temporal.ai_observability.sentiment.extraction import truncate_to_head_tailfrom posthog.temporal.ai_observability.sentiment.schema import SentimentResult@@ -375,6 +376,52 @@ class TestRunEvaluationWorkflow:assert props["$ai_output_tokens"] == 18assert props["$ai_evaluation_type"] == "online"+ @pytest.mark.asyncio+ @pytest.mark.django_db(transaction=True)+ @pytest.mark.parametrize(+ "status_code,should_raise",+ [+ pytest.param(402, False, id="billing_limit_is_swallowed"),+ pytest.param(500, True, id="server_error_still_raises"),+ ],+ )+ async def test_emit_evaluation_event_activity_billing_limit(self, setup_data, status_code: int, should_raise: bool):+ team = setup_data["team"]+ evaluation = {"id": str(setup_data["evaluation"].id), "name": "Test Evaluation"}+ event_data = create_mock_event_data(team.id, properties={})+ result: EvaluationActivityResult = {+ "result_type": "boolean",+ "verdict": True,+ "reasoning": "Test passed",+ "allows_na": False,+ "model": "gpt-5-mini",+ "provider": "openai",+ }++ capture_result = MagicMock(+ raise_for_status=MagicMock(side_effect=CaptureInternalError("boom", status_code=status_code))+ )+ inputs = EmitEvaluationEventInputs(+ evaluation=evaluation,+ event_data=event_data,+ result=result,+ start_time=datetime(2024, 1, 1, 12, 0, 0),+ )++ with patch(+ "posthog.temporal.ai_observability.evaluation_workflow_activities.Team.objects.get",+ return_value=team,+ ):+ with patch(+ "posthog.temporal.ai_observability.evaluation_workflow_activities.capture_internal",+ return_value=capture_result,+ ):+ if should_raise:+ with pytest.raises(CaptureInternalError):+ await emit_evaluation_event_activity(inputs)+ else:+ await emit_evaluation_event_activity(inputs)+@pytest.mark.asyncio@pytest.mark.django_db(transaction=True)async def test_emit_evaluation_event_activity_skipped_omits_cost_attribution(self, setup_data):diff --git a/posthog/temporal/ai_observability/test_run_tagger.py b/posthog/temporal/ai_observability/test_run_tagger.pyindex 0bb2fd6a4b60..45cac9e96d27 100644--- a/posthog/temporal/ai_observability/test_run_tagger.py+++ b/posthog/temporal/ai_observability/test_run_tagger.py@@ -8,6 +8,7 @@ from unittest.mock import MagicMock, patchfrom temporalio.exceptions import ApplicationError+from posthog.api.capture import CaptureInternalErrorfrom posthog.models import Organization, Teamfrom products.ai_observability.backend.models.provider_keys import LLMProviderKey@@ -426,6 +427,36 @@ class TestRunTaggerWorkflow:f"Hog tagger event leaked LLM-only props: {llm_keys & set(props)}")+ @pytest.mark.asyncio+ @pytest.mark.django_db(transaction=True)+ @pytest.mark.parametrize(+ "status_code,should_raise",+ [+ pytest.param(402, False, id="billing_limit_is_swallowed"),+ pytest.param(500, True, id="server_error_still_raises"),+ ],+ )+ async def test_emit_tagger_event_activity_billing_limit(self, setup_data, status_code: int, should_raise: bool):+ team = setup_data["team"]+ tagger = {"id": str(setup_data["tagger"].id), "name": "Feature Tagger"}+ event_data = create_mock_event_data(team.id, properties={})+ result = {"tags": ["billing"], "reasoning": "matched", "is_hog": True}++ capture_result = MagicMock(+ raise_for_status=MagicMock(side_effect=CaptureInternalError("boom", status_code=status_code))+ )+ inputs = EmitTaggerEventInputs(+ tagger=tagger, event_data=event_data, result=result, start_time=datetime(2024, 1, 1, 12, 0, 0)+ )++ with patch("posthog.temporal.ai_observability.run_tagger.Team.objects.get", return_value=team):+ with patch("posthog.temporal.ai_observability.run_tagger.capture_internal", return_value=capture_result):+ if should_raise:+ with pytest.raises(CaptureInternalError):+ await emit_tagger_event_activity(inputs)+ else:+ await emit_tagger_event_activity(inputs)+@pytest.mark.asyncio@pytest.mark.django_db(transaction=True)async def test_disable_tagger_activity(self, setup_data):diff --git a/posthog/temporal/ai_observability/test_run_trace_evaluation.py b/posthog/temporal/ai_observability/test_run_trace_evaluation.pyindex 8c8839cfcbf5..8e7ced6eb2e0 100644--- a/posthog/temporal/ai_observability/test_run_trace_evaluation.py+++ b/posthog/temporal/ai_observability/test_run_trace_evaluation.py@@ -11,6 +11,7 @@ from posthog.schema import LLMTrace, LLMTraceEventfrom posthog.hogql import ast+from posthog.api.capture import CaptureInternalErrorfrom posthog.cdp.validation import compile_hogfrom posthog.models import Organization, Team@@ -588,6 +589,48 @@ class TestEmitTraceEvaluationEventActivity:assert "$ai_target_event_id" not in propsassert "$ai_target_event_type" not in props+ @pytest.mark.asyncio+ @pytest.mark.django_db(transaction=True)+ @pytest.mark.parametrize(+ "status_code,should_raise",+ [+ pytest.param(402, False, id="billing_limit_is_swallowed"),+ pytest.param(500, True, id="server_error_still_raises"),+ ],+ )+ async def test_emits_event_billing_limit(self, setup_data, status_code: int, should_raise: bool):+ team = setup_data["team"]+ result: EvaluationActivityResult = {+ "result_type": "boolean",+ "verdict": True,+ "reasoning": "Looks good",+ "allows_na": False,+ "model": "gpt-5-mini",+ "provider": "openai",+ }+ capture_result = MagicMock(+ raise_for_status=MagicMock(side_effect=CaptureInternalError("boom", status_code=status_code))+ )+ inputs = EmitTraceEvaluationEventInputs(+ evaluation=evaluation_dict(setup_data),+ team_id=team.id,+ trace_id="trace-123",+ distinct_id="test-user",+ session_id="session-1",+ result=result,+ start_time=datetime(2024, 1, 1, 12, 0, 0),+ )++ with patch("posthog.temporal.ai_observability.run_trace_evaluation.Team.objects.get", return_value=team):+ with patch(+ "posthog.temporal.ai_observability.run_trace_evaluation.capture_internal", return_value=capture_result+ ):+ if should_raise:+ with pytest.raises(CaptureInternalError):+ await emit_trace_evaluation_event_activity(inputs)+ else:+ await emit_trace_evaluation_event_activity(inputs)+class TestRunTraceEvaluationWorkflowInputs:def test_parse_inputs(self):