: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): skip summarization exception capture when temporal will retry (#109759)
Bernat Torresb6b879e82a33
diff --git a/posthog/temporal/ai_observability/trace_summarization/README.md b/posthog/temporal/ai_observability/trace_summarization/README.mdindex 42336773c905..41db47555ca2 100644--- a/posthog/temporal/ai_observability/trace_summarization/README.md+++ b/posthog/temporal/ai_observability/trace_summarization/README.md@@ -207,6 +207,7 @@ Text representations (up to 2 MB) are stored in Redis between the two activities- `TextReprExpiredError` is non-retryable (Redis key missing means fetch must re-run, but this is handled by workflow-level retry)- Embedding failures tracked separately, don't fail summary generation- Activity retries use exponential backoff via centralized retry policies+- A failed LLM call is captured as an exception only on the last attempt of `summarize_and_save_activity`. An earlier attempt logs `OpenAI API call failed, retry pending` at warning level, because the retry can still save the summary.## Testingdiff --git a/posthog/temporal/ai_observability/trace_summarization/summarize_and_save.py b/posthog/temporal/ai_observability/trace_summarization/summarize_and_save.pyindex bb1c1e08c7a5..1d76f2b187fa 100644--- a/posthog/temporal/ai_observability/trace_summarization/summarize_and_save.py+++ b/posthog/temporal/ai_observability/trace_summarization/summarize_and_save.py@@ -218,6 +218,8 @@ async def summarize_and_save_activity(input: SummarizeAndSaveInput) -> Summariza# The batch pipeline can wait for its summaries, so it takes the cheaper flex tier.# The provider falls back to the standard tier when flex is refused or stalls.flex=True,+ final_attempt=temporalio.activity.info().attempt+ >= constants.SUMMARIZE_AND_SAVE_RETRY_POLICY.maximum_attempts,)llm_duration_s = time.monotonic() - t0log.info(diff --git a/posthog/temporal/ai_observability/trace_summarization/tests/test_summarize_and_save.py b/posthog/temporal/ai_observability/trace_summarization/tests/test_summarize_and_save.pyindex 1419088776f9..131e979fc216 100644--- a/posthog/temporal/ai_observability/trace_summarization/tests/test_summarize_and_save.py+++ b/posthog/temporal/ai_observability/trace_summarization/tests/test_summarize_and_save.py@@ -1,12 +1,15 @@"""Tests for unified summarize_and_save activity."""import uuid+import dataclassesfrom contextlib import asynccontextmanagerfrom datetime import UTC, datetimeimport pytestfrom unittest.mock import patch+from temporalio.testing import ActivityEnvironment+from posthog.temporal.ai_observability.trace_summarization.models import SummarizeAndSaveInput, TextReprExpiredErrorfrom posthog.temporal.ai_observability.trace_summarization.summarize_and_save import summarize_and_save_activity@@ -37,6 +40,12 @@ def _make_mock_summary():)+async def _run_activity(input_data, attempt=1):+ env = ActivityEnvironment()+ env.info = dataclasses.replace(env.info, attempt=attempt)+ return await env.run(summarize_and_save_activity, input_data)++def _make_input(mock_team, generation_id=None):return SummarizeAndSaveInput(redis_key="llma:summarization:trace:1:abc:text_repr",@@ -71,11 +80,12 @@ class TestSummarizeAndSaveActivity:mock_load.return_value = Nonewith pytest.raises(TextReprExpiredError):- await summarize_and_save_activity(_make_input(mock_team))+ await _run_activity(_make_input(mock_team))@pytest.mark.django_db(transaction=True)@pytest.mark.asyncio- async def test_trace_summary_success(self, mock_team):+ @pytest.mark.parametrize("attempt,final_attempt", [(1, False), (2, True)])+ async def test_trace_summary_success(self, mock_team, attempt, final_attempt):mock_summary = _make_mock_summary()input_data = _make_input(mock_team)@@ -100,7 +110,7 @@ class TestSummarizeAndSaveActivity:mock_load.return_value = "text_repr content"mock_summarize.return_value = mock_summary- result = await summarize_and_save_activity(input_data)+ result = await _run_activity(input_data, attempt=attempt)assert result.success is Trueassert result.trace_id == input_data.trace_id@@ -108,6 +118,8 @@ class TestSummarizeAndSaveActivity:assert result.embedding_requested is True# Dropping flex here silently doubles the pipeline's LLM bill, so pin it.assert mock_summarize.call_args.kwargs["flex"] is True+ # A wrong final_attempt either alerts on failures the retry recovers or hides lost summaries.+ assert mock_summarize.call_args.kwargs["final_attempt"] is final_attemptmock_create_event.assert_called_once()call_kwargs = mock_create_event.call_args.kwargsassert call_kwargs["event"] == "$ai_trace_summary"@@ -152,7 +164,7 @@ class TestSummarizeAndSaveActivity:mock_load.return_value = "generation text repr"mock_summarize.return_value = mock_summary- result = await summarize_and_save_activity(input_data)+ result = await _run_activity(input_data)assert result.success is Trueassert result.generation_id == generation_id@@ -197,7 +209,7 @@ class TestSummarizeAndSaveActivity:mock_summarize.return_value = mock_summarymock_embedder_class.return_value.embed_document.side_effect = Exception("Kafka down")- result = await summarize_and_save_activity(input_data)+ result = await _run_activity(input_data)assert result.success is Trueassert result.embedding_requested is Falsediff --git a/products/ai_observability/backend/summarization/llm/call.py b/products/ai_observability/backend/summarization/llm/call.pyindex 380bde977b33..64fc631f337b 100644--- a/products/ai_observability/backend/summarization/llm/call.py+++ b/products/ai_observability/backend/summarization/llm/call.py@@ -19,6 +19,7 @@ def summarize(model: OpenAIModel | None = None,user_id: str | None = None,flex: bool = False,+ final_attempt: bool = True,) -> SummarizationResponse:"""Generate AI-powered summary from text representation via LLM gateway.@@ -30,9 +31,12 @@ def summarize(model: OpenAI model to use (defaults to gpt-4.1-mini)user_id: Optional user distinct_id for analytics attributionflex: Request the flex service tier, cheaper but slower (gpt-5 family only)+ final_attempt: False when the caller retries a failure, so the failure is not capturedReturns:Structured summarization response with flow diagram, bullets, and notes"""openai_model = cast(OpenAIModel, model) if model else DEFAULT_MODEL_OPENAI- return summarize_with_openai(text_repr, team_id, mode, openai_model, user_id, flex=flex)+ return summarize_with_openai(+ text_repr, team_id, mode, openai_model, user_id, flex=flex, final_attempt=final_attempt+ )diff --git a/products/ai_observability/backend/summarization/llm/openai.py b/products/ai_observability/backend/summarization/llm/openai.pyindex 95a1d8f4c973..92a81f05c185 100644--- a/products/ai_observability/backend/summarization/llm/openai.py+++ b/products/ai_observability/backend/summarization/llm/openai.py@@ -62,6 +62,7 @@ def summarize_with_openai(model: OpenAIModel,user_id: str | None = None,flex: bool = False,+ final_attempt: bool = True,) -> SummarizationResponse:"""Generate summary using OpenAI API via LLM gateway with structured outputs."""resolved_distinct_id = user_id or team_distinct_id(team_id)@@ -142,11 +143,29 @@ def summarize_with_openai(except Exception as e:status_code = _provider_status(e)reason = _failure_reason(e, status_code)+ # The OpenAI SDK reads this from the X-Request-ID response header, which the ai-gateway+ # sets to the id it stamps as $ai_gateway_request_id on the generation event.+ gateway_request_id = getattr(e, "request_id", None)+ if not final_attempt:+ # Temporal retries the activity, so the summary is not lost yet. Capture only failures+ # that cost a user their summary.+ logger.warning(+ "OpenAI API call failed, retry pending",+ error=str(e),+ error_type=type(e).__name__,+ provider_status=status_code,+ gateway_request_id=gateway_request_id,+ team_id=team_id,+ model=model,+ flex=flex,+ )+ raise SummarizationFailedError(f"Failed to generate summary{reason}")logger.exception("OpenAI API call failed",error=str(e),error_type=type(e).__name__,provider_status=status_code,+ gateway_request_id=gateway_request_id,team_id=team_id,model=model,flex=flex,@@ -163,6 +182,7 @@ def summarize_with_openai("team_id": team_id,"model": str(model),"provider_status": status_code,+ "gateway_request_id": gateway_request_id,"flex": flex,},)diff --git a/products/ai_observability/backend/summarization/tests/test_call.py b/products/ai_observability/backend/summarization/tests/test_call.pyindex abe71a791799..550cd44044bd 100644--- a/products/ai_observability/backend/summarization/tests/test_call.py+++ b/products/ai_observability/backend/summarization/tests/test_call.py@@ -36,6 +36,7 @@ class TestSummarize:DEFAULT_MODEL_OPENAI,None,flex=False,+ final_attempt=True,)assert result == mock_responsediff --git a/products/ai_observability/backend/summarization/tests/test_providers.py b/products/ai_observability/backend/summarization/tests/test_providers.pyindex ec23cf753bdb..4349b62b7acb 100644--- a/products/ai_observability/backend/summarization/tests/test_providers.py+++ b/products/ai_observability/backend/summarization/tests/test_providers.py@@ -127,7 +127,13 @@ class TestSummarizeWithOpenAI:assert str(raised.value.detail) == expected_detail- def test_api_error_is_captured_with_a_status_specific_fingerprint(self):+ @pytest.mark.parametrize("final_attempt", [True, False])+ def test_api_error_is_captured_only_when_no_retry_remains(self, final_attempt):+ error = BadRequestError(+ "bad request",+ response=httpx.Response(400, request=_REQUEST, headers={"x-request-id": "req-123"}),+ body=None,+ )with (patch("products.ai_observability.backend.summarization.llm.openai.build_openai_client") as mock_get_client,patch("products.ai_observability.backend.summarization.llm.openai.capture_exception") as mock_capture,@@ -135,7 +141,7 @@ class TestSummarizeWithOpenAI:mock_client = MagicMock()mock_get_client.return_value = mock_clientmock_client.with_options.return_value = mock_client- mock_client.chat.completions.create.side_effect = _bad_request_error()+ mock_client.chat.completions.create.side_effect = errorwith pytest.raises(exceptions.APIException) as raised:summarize_with_openai(@@ -143,13 +149,18 @@ class TestSummarizeWithOpenAI:team_id=1,mode=SummarizationMode.MINIMAL,model=OpenAIModel.GPT_4_1_MINI,+ final_attempt=final_attempt,)- mock_capture.assert_called_once()assert is_expected_activity_failure(raised.value)+ if not final_attempt:+ mock_capture.assert_not_called()+ return+ mock_capture.assert_called_once()properties = mock_capture.call_args[1]["additional_properties"]assert properties["$exception_fingerprint"] == "aio_summarization.BadRequestError.400"assert properties["provider_status"] == 400+ assert properties["gateway_request_id"] == "req-123"def test_uses_correct_model(self, valid_response_json):mock_response = MagicMock()