: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): keep skipped tagger runs out of error tracking (#105061)
Carlos Marchalf5ecd6341ffa
diff --git a/posthog/temporal/ai_observability/run_tagger.py b/posthog/temporal/ai_observability/run_tagger.pyindex 198a5c3da485..9eec0c2a92fe 100644--- a/posthog/temporal/ai_observability/run_tagger.py+++ b/posthog/temporal/ai_observability/run_tagger.py@@ -15,7 +15,7 @@ from posthog.sync import database_sync_to_asyncfrom posthog.temporal.ai_observability.evaluation_event_io import extract_event_iofrom posthog.temporal.ai_observability.evaluation_workflow_activities import update_key_state_activityfrom posthog.temporal.ai_observability.message_utils import extract_text_from_messages-from posthog.temporal.ai_observability.model_resolution import model_spec+from posthog.temporal.ai_observability.model_resolution import ResolvedModel, model_specfrom posthog.temporal.ai_observability.team_capture import capture_ai_internal_for_teamfrom posthog.temporal.common.base import PostHogWorkflowfrom posthog.temporal.common.scoped import scoped_temporal@@ -46,6 +46,19 @@ LLM_TAGGER_RETRY_POLICY = RetryPolicy(backoff_coefficient=2.0,)+TAGGER_DISABLED_ERROR_TYPE = "tagger_disabled"+TAGGER_PARSE_ERROR_TYPE = "tagger_parse_error"+# model_resolution is shared with evaluations, so the tagger types its skip reasons on the way out.+MODEL_RESOLUTION_SKIP_ERROR_TYPES = {+ "provider_key_required": "tagger_provider_key_required",+ "key_invalid": "tagger_key_invalid",+ "no_default_model": "tagger_no_default_model",+}+# RunTaggerWorkflow turns these into a skipped result, so they must stay out of error tracking.+SKIPPED_RESULT_ERROR_TYPES = frozenset(+ {TAGGER_DISABLED_ERROR_TYPE, TAGGER_PARSE_ERROR_TYPE, *MODEL_RESOLUTION_SKIP_ERROR_TYPES.values()}+)+class TagResult(BaseModel):"""Structured output for tagger results."""@@ -156,6 +169,7 @@ async def fetch_tagger_activity(inputs: RunTaggerInputs) -> dict[str, Any]:raise ApplicationError(f"Tagger {inputs.tagger_id} is disabled.",{"error_type": "tagger_disabled"},+ type=TAGGER_DISABLED_ERROR_TYPE,non_retryable=True,)@@ -193,8 +207,20 @@ class ExecuteTaggerInputs:}+async def _resolve_model(model_configuration: dict[str, Any] | None, team_id: int) -> ResolvedModel:+ try:+ return await database_sync_to_async(lambda: model_spec(model_configuration).resolve(team_id))()+ except ApplicationError as e:+ skip_type = MODEL_RESOLUTION_SKIP_ERROR_TYPES.get(e.details[0].get("error_type")) if e.details else None+ if skip_type is None:+ raise+ raise ApplicationError(e.message, *e.details, type=skip_type, non_retryable=True) from e++@temporalio.activity.defn-@scoped_temporal()+# The worker interceptor captures failures after filtering out SKIPPED_RESULT_ERROR_TYPES, and a+# capture in here would run before that filter.+@scoped_temporal(capture_exceptions=False)async def execute_tagger_activity(inputs: ExecuteTaggerInputs) -> dict[str, Any]:"""Execute LLM tagger to classify the target event."""tagger = inputs.tagger@@ -216,7 +242,7 @@ async def execute_tagger_activity(inputs: ExecuteTaggerInputs) -> dict[str, Any]# active key (provider-aware), matching execute_llm_judge_activity.team_id = tagger["team_id"]model_configuration = tagger.get("model_configuration")- resolved = await database_sync_to_async(lambda: model_spec(model_configuration).resolve(team_id))()+ resolved = await _resolve_model(model_configuration, team_id)provider = resolved.providermodel = resolved.modelprovider_key = resolved.provider_key@@ -299,9 +325,11 @@ Output: {output_data}"""except (OutputTokenLimitError, StructuredOutputParseError) as e:# A reply cut off at the output limit reaches the tagger as unusable output, same as a# malformed one, so both take the parse path.+ logger.warning("LLM tagger returned unusable output", tagger_id=tagger["id"], model=model, error=str(e))raise ApplicationError(str(e),{"error_type": "parse_error"},+ type=TAGGER_PARSE_ERROR_TYPE,non_retryable=True,) from ediff --git a/posthog/temporal/ai_observability/test_run_tagger.py b/posthog/temporal/ai_observability/test_run_tagger.pyindex 665ee3c67c9d..7d221d67d05a 100644--- a/posthog/temporal/ai_observability/test_run_tagger.py+++ b/posthog/temporal/ai_observability/test_run_tagger.py@@ -1,7 +1,7 @@import jsonimport uuidfrom datetime import datetime-from typing import Any+from typing import Any, TypedDictimport pytestfrom unittest.mock import MagicMock, patch@@ -10,11 +10,15 @@ from temporalio.exceptions import ApplicationErrorfrom posthog.api.capture import CaptureInternalErrorfrom posthog.models import Organization, Team+from posthog.sync import database_sync_to_async+from posthog.temporal.common.posthog_client import EXPECTED_CONTROL_FLOW_ERROR_TYPES, is_expected_activity_failure+from products.ai_observability.backend.llm.errors import OutputTokenLimitError, StructuredOutputParseErrorfrom products.ai_observability.backend.models.provider_keys import LLMProviderKeyfrom products.ai_observability.backend.models.taggers import Taggerfrom .run_tagger import (+ SKIPPED_RESULT_ERROR_TYPES,EmitTaggerEventInputs,ExecuteTaggerInputs,RunTaggerInputs,@@ -62,8 +66,14 @@ def make_tagger_config():}+class SetupData(TypedDict):+ organization: Organization+ team: Team+ tagger: Tagger++@pytest.fixture-def setup_data():+def setup_data() -> SetupData:organization = Organization.objects.create(name="Test Org")team = Team.objects.create(organization=organization, name="Test Team")tagger = Tagger.objects.create(@@ -307,6 +317,8 @@ class TestRunTaggerWorkflow:await execute_tagger_activity(ExecuteTaggerInputs(tagger=tagger, event_data=event_data))assert exc_info.value.details[0]["error_type"] == "provider_key_required"+ assert exc_info.value.type == "tagger_provider_key_required"+ assert is_expected_activity_failure(exc_info.value)@pytest.mark.asyncio@pytest.mark.django_db(transaction=True)@@ -774,8 +786,6 @@ class TestFetchTaggerActivityDisabled:@pytest.mark.asyncio@pytest.mark.django_db(transaction=True)async def test_short_circuits_when_tagger_disabled(self, setup_data):- from posthog.sync import database_sync_to_async-tagger = setup_data["tagger"]team = setup_data["team"]@@ -784,5 +794,49 @@ class TestFetchTaggerActivityDisabled:inputs = RunTaggerInputs(tagger_id=str(tagger.id), event_data=create_mock_event_data(team.id))- with pytest.raises(ApplicationError, match="disabled"):+ with pytest.raises(ApplicationError, match="disabled") as exc_info:await fetch_tagger_activity(inputs)++ assert exc_info.value.type == "tagger_disabled"+ assert is_expected_activity_failure(exc_info.value)+++class TestSkippedResultsStayOutOfErrorTracking:+ def test_skipped_result_types_are_expected_control_flow(self) -> None:+ assert SKIPPED_RESULT_ERROR_TYPES <= EXPECTED_CONTROL_FLOW_ERROR_TYPES++ @pytest.mark.parametrize(+ "llm_error",+ [+ OutputTokenLimitError("The model reached its output token limit."),+ StructuredOutputParseError("The reply did not match the schema."),+ ],+ )+ @pytest.mark.asyncio+ @pytest.mark.django_db(transaction=True)+ async def test_unusable_reply_is_skipped_not_captured(self, setup_data: SetupData, llm_error: Exception) -> None:+ team = setup_data["team"]+ tagger = {+ "id": str(setup_data["tagger"].id),+ "name": "Feature Tagger",+ "tagger_config": make_tagger_config(),+ "team_id": team.id,+ }++ with (+ patch("posthog.temporal.ai_observability.run_tagger.Client") as mock_client_class,+ patch("posthog.temporal.ai_observability.model_resolution.EvaluationConfig") as mock_eval_config,+ patch("posthoganalytics.capture_exception") as mock_capture_exception,+ ):+ mock_client_class.return_value.complete.side_effect = llm_error+ mock_eval_config.objects.get_or_create.return_value = (_mock_config_with_active_key(), False)++ with pytest.raises(ApplicationError) as exc_info:+ await execute_tagger_activity(+ ExecuteTaggerInputs(tagger=tagger, event_data=create_mock_event_data(team.id))+ )++ assert exc_info.value.details[0]["error_type"] == "parse_error"+ assert exc_info.value.type == "tagger_parse_error"+ assert is_expected_activity_failure(exc_info.value)+ mock_capture_exception.assert_not_called()diff --git a/posthog/temporal/common/posthog_client.py b/posthog/temporal/common/posthog_client.pyindex b76b11ee980f..034e845f964f 100644--- a/posthog/temporal/common/posthog_client.py+++ b/posthog/temporal/common/posthog_client.py@@ -36,6 +36,7 @@ logger = get_write_only_logger()# "trace_not_settled" and "session_not_settled" are the aggregate-evaluation settle probes, whose# retry schedule is the poll loop. Each settle target keeps its own type, so a new target must# list its type here too; `_NOT_SETTLED_ERROR_TYPES` is tested against this set.+# The "tagger_" types are runs RunTaggerWorkflow skips; `SKIPPED_RESULT_ERROR_TYPES` is tested against this set.EXPECTED_CONTROL_FLOW_ERROR_TYPES = frozenset({"trace_not_settled",@@ -45,6 +46,11 @@ EXPECTED_CONTROL_FLOW_ERROR_TYPES = frozenset("AIFeaturesCloudOnly","SandboxRateLimitedError","SandboxControlPlaneUnavailableError",+ "tagger_disabled",+ "tagger_parse_error",+ "tagger_provider_key_required",+ "tagger_key_invalid",+ "tagger_no_default_model",})