: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): stop retrying timed-out translations and report them as 504 (#83071)
Carlos Marchal8d6956a23be0
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex dd2245c63fe4..270ab2506fbb 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6101,7 +6101,7 @@ snapshots:scenes-app-experiments--experiment-stopped-with-conclusion--light:hash: v1.k794b7964.793a4b6109b2c0ab65b07d9eaefd1c8862f12bfc7f33b2f452ad20044396b2a7.6B0Meq7yO75vBEoBmuP2dNl2oKTugzzr_IKTcJHhEi0scenes-app-experiments--experiment-with-funnel-metric--dark:- hash: v1.k794b7964.fd0d0ad7569f50079a322a8901513f854823ce694796a2a24a1e6714ac9c5902.fBtAQkm1LZ7xYp6DTXoQSDqDFjsUkxMCP-aNAZJ1Fmc+ hash: v1.k794b7964.bd425da753ec6f788f968fb15c6a7783af3c8479103849bf3ab4fad4f4276287.KPZegtTwokdMxA6_KV2bsmFYxTZO1AYRlPZp4tZ6y7Escenes-app-experiments--experiment-with-funnel-metric--light:hash: v1.k794b7964.a608f24a82fc56569fb7029e98bab3121baa3fd6c5c63492fe9952aa6a43afc5.ZgTLiUZPjDNcaChht0ijSp2F7HoqRkdn__-6JKI7p4Ascenes-app-experiments--experiment-with-legacy-funnels-query--dark:diff --git a/products/ai_observability/backend/api/test/test_translate.py b/products/ai_observability/backend/api/test/test_translate.pyindex 7570dbe8f887..60cc37dbc84d 100644--- a/products/ai_observability/backend/api/test/test_translate.py+++ b/products/ai_observability/backend/api/test/test_translate.py@@ -3,6 +3,8 @@from posthog.test.base import APIBaseTestfrom unittest.mock import MagicMock, patch+import httpx+from openai import APITimeoutErrorfrom rest_framework import statusfrom products.ai_observability.backend.translation.constants import (@@ -14,6 +16,20 @@ from products.ai_observability.backend.translation.constants import (MOCK_PATH = "products.ai_observability.backend.translation.llm.get_llm_client"+def mock_llm_client(mock_get_client: MagicMock) -> MagicMock:+ # Self-referential so `with_options(...)` returns the same client the assertions inspect.+ client = MagicMock()+ client.with_options.return_value = client+ mock_get_client.return_value = client+ return client+++def mock_completion(client: MagicMock, content: str | None) -> None:+ response = MagicMock()+ response.choices = [MagicMock(message=MagicMock(content=content))]+ client.chat.completions.create.return_value = response++class TestTranslateAPI(APIBaseTest):def test_unauthenticated_user_cannot_access_translation(self):self.client.logout()@@ -24,9 +40,7 @@ class TestTranslateAPI(APIBaseTest):def test_successful_translation(self, mock_get_client):self.organization.is_ai_data_processing_approved = Trueself.organization.save()- mock_response = MagicMock()- mock_response.choices = [MagicMock(message=MagicMock(content="Hola mundo"))]- mock_get_client.return_value.chat.completions.create.return_value = mock_response+ mock_completion(mock_llm_client(mock_get_client), "Hola mundo")response = self.client.post(f"/api/environments/{self.team.id}/llm_analytics/translate",@@ -42,11 +56,8 @@ class TestTranslateAPI(APIBaseTest):def test_translation_uses_correct_model(self, mock_get_client):self.organization.is_ai_data_processing_approved = Trueself.organization.save()- mock_response = MagicMock()- mock_response.choices = [MagicMock(message=MagicMock(content="Translated"))]- mock_client = MagicMock()- mock_client.chat.completions.create.return_value = mock_response- mock_get_client.return_value = mock_client+ mock_client = mock_llm_client(mock_get_client)+ mock_completion(mock_client, "Translated")self.client.post(f"/api/environments/{self.team.id}/llm_analytics/translate",@@ -61,11 +72,8 @@ class TestTranslateAPI(APIBaseTest):def test_translation_uses_default_language_when_not_specified(self, mock_get_client):self.organization.is_ai_data_processing_approved = Trueself.organization.save()- mock_response = MagicMock()- mock_response.choices = [MagicMock(message=MagicMock(content="Translated"))]- mock_client = MagicMock()- mock_client.chat.completions.create.return_value = mock_response- mock_get_client.return_value = mock_client+ mock_client = mock_llm_client(mock_get_client)+ mock_completion(mock_client, "Translated")self.client.post(f"/api/environments/{self.team.id}/llm_analytics/translate",@@ -121,7 +129,7 @@ class TestTranslateAPI(APIBaseTest):def test_translation_handles_llm_error(self, mock_get_client):self.organization.is_ai_data_processing_approved = Trueself.organization.save()- mock_get_client.return_value.chat.completions.create.side_effect = Exception("API error")+ mock_llm_client(mock_get_client).chat.completions.create.side_effect = Exception("API error")response = self.client.post(f"/api/environments/{self.team.id}/llm_analytics/translate",@@ -130,17 +138,34 @@ class TestTranslateAPI(APIBaseTest):)assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR- assert response.data["detail"] == "Translation failed due to an internal error."+ assert response.data["detail"] == "Translation failed. Please try again."++ @patch(MOCK_PATH)+ def test_translation_timeout_is_reported_as_gateway_timeout(self, mock_get_client):+ self.organization.is_ai_data_processing_approved = True+ self.organization.save()+ mock_llm_client(mock_get_client).chat.completions.create.side_effect = APITimeoutError(+ request=httpx.Request("POST", "http://gateway.invalid/chat/completions")+ )++ response = self.client.post(+ f"/api/environments/{self.team.id}/llm_analytics/translate",+ {"text": "Hello world", "target_language": "es"},+ format="json",+ )++ # A slow model is not an internal error, and the copy has to tell the user what to do next.+ assert response.status_code == status.HTTP_504_GATEWAY_TIMEOUT+ assert response.data["detail"] == (+ "Translation took too long. Try again, and if it keeps failing this message may be too long to translate."+ )@patch(MOCK_PATH)def test_translation_preserves_formatting(self, mock_get_client):self.organization.is_ai_data_processing_approved = Trueself.organization.save()- mock_response = MagicMock()- mock_response.choices = [MagicMock(message=MagicMock(content="Translated"))]- mock_client = MagicMock()- mock_client.chat.completions.create.return_value = mock_response- mock_get_client.return_value = mock_client+ mock_client = mock_llm_client(mock_get_client)+ mock_completion(mock_client, "Translated")self.client.post(f"/api/environments/{self.team.id}/llm_analytics/translate",@@ -156,9 +181,7 @@ class TestTranslateAPI(APIBaseTest):def test_translation_handles_empty_response(self, mock_get_client):self.organization.is_ai_data_processing_approved = Trueself.organization.save()- mock_response = MagicMock()- mock_response.choices = [MagicMock(message=MagicMock(content=None))]- mock_get_client.return_value.chat.completions.create.return_value = mock_response+ mock_completion(mock_llm_client(mock_get_client), None)response = self.client.post(f"/api/environments/{self.team.id}/llm_analytics/translate",@@ -186,9 +209,7 @@ class TestTranslateAPI(APIBaseTest):def test_translation_allowed_when_ai_consent_approved(self, mock_get_client):self.organization.is_ai_data_processing_approved = Trueself.organization.save()- mock_response = MagicMock()- mock_response.choices = [MagicMock(message=MagicMock(content="Hola mundo"))]- mock_get_client.return_value.chat.completions.create.return_value = mock_response+ mock_completion(mock_llm_client(mock_get_client), "Hola mundo")response = self.client.post(f"/api/environments/{self.team.id}/llm_analytics/translate",@@ -202,11 +223,8 @@ class TestTranslateAPI(APIBaseTest):def test_translation_passes_user_distinct_id(self, mock_get_client):self.organization.is_ai_data_processing_approved = Trueself.organization.save()- mock_response = MagicMock()- mock_response.choices = [MagicMock(message=MagicMock(content="Translated"))]- mock_client = MagicMock()- mock_client.chat.completions.create.return_value = mock_response- mock_get_client.return_value = mock_client+ mock_client = mock_llm_client(mock_get_client)+ mock_completion(mock_client, "Translated")self.client.post(f"/api/environments/{self.team.id}/llm_analytics/translate",diff --git a/products/ai_observability/backend/api/translate.py b/products/ai_observability/backend/api/translate.pyindex 2aa3c0b7afd7..df030a71d28c 100644--- a/products/ai_observability/backend/api/translate.py+++ b/products/ai_observability/backend/api/translate.py@@ -28,11 +28,19 @@ from posthog.rate_limit import (from products.ai_observability.backend.api.metrics import llma_track_latencyfrom products.ai_observability.backend.translation.constants import DEFAULT_TARGET_LANGUAGE-from products.ai_observability.backend.translation.llm import translate_text+from products.ai_observability.backend.translation.llm import TranslationTimeoutError, translate_textlogger = structlog.get_logger(__name__)+class TranslationTimeout(exceptions.APIException):+ status_code = status.HTTP_504_GATEWAY_TIMEOUT+ default_detail = (+ "Translation took too long. Try again, and if it keeps failing this message may be too long to translate."+ )+ default_code = "translation_timeout"++class TranslateRequestSerializer(serializers.Serializer):text = serializers.CharField(max_length=10000, help_text="The text to translate")target_language = serializers.CharField(@@ -124,9 +132,18 @@ class AIObservabilityTranslateViewSet(TeamAndOrgViewSetMixin, viewsets.GenericVi},status=status.HTTP_200_OK,)+ except TranslationTimeoutError:+ # Not logger.exception: the traceback is all HTTP client plumbing, and the input length+ # is what actually explains a timeout.+ logger.warning(+ "translation_timed_out",+ target_language=target_language,+ text_length=len(text),+ )+ raise TranslationTimeout()except Exception as e:logger.exception("translation_failed", error=str(e), target_language=target_language)raise exceptions.APIException(- detail="Translation failed due to an internal error.",+ detail="Translation failed. Please try again.",code="translation_error",)diff --git a/products/ai_observability/backend/translation/constants.py b/products/ai_observability/backend/translation/constants.pyindex 37c82320d54b..50e36e88b304 100644--- a/products/ai_observability/backend/translation/constants.py+++ b/products/ai_observability/backend/translation/constants.py@@ -12,3 +12,8 @@ SUPPORTED_LANGUAGES = {lang["code"]: lang["label"] for lang in _languages_list}DEFAULT_TARGET_LANGUAGE = "en"TRANSLATION_MODEL = "gpt-4.1-mini"++# `translate_text` makes a single attempt, so this is the whole wall clock a user waits behind the+# spinner rather than a per-attempt budget. It has to cover a text as long as the 10,000 character+# cap the request serializer enforces, while still returning inside the proxy's request timeout.+TRANSLATION_TIMEOUT_SECONDS = 45.0diff --git a/products/ai_observability/backend/translation/llm.py b/products/ai_observability/backend/translation/llm.pyindex c3247e7473ac..b71402a73e62 100644--- a/products/ai_observability/backend/translation/llm.py+++ b/products/ai_observability/backend/translation/llm.py@@ -1,14 +1,19 @@"""LLM-based translation using the LLM gateway."""import structlog+from openai import APITimeoutErrorfrom posthog.llm.gateway_client import get_llm_client-from .constants import SUPPORTED_LANGUAGES, TRANSLATION_MODEL+from .constants import SUPPORTED_LANGUAGES, TRANSLATION_MODEL, TRANSLATION_TIMEOUT_SECONDSlogger = structlog.get_logger(__name__)+class TranslationTimeoutError(Exception):+ """The model did not return a translation inside TRANSLATION_TIMEOUT_SECONDS."""++def translate_text(text: str, target_language: str, user_distinct_id: str | None = None) -> str:"""Translate text to target language using the LLM gateway.@@ -20,24 +25,35 @@ def translate_text(text: str, target_language: str, user_distinct_id: str | NoneReturns:Translated text++ Raises:+ TranslationTimeoutError: The request exceeded TRANSLATION_TIMEOUT_SECONDS."""- client = get_llm_client("llma_translation")+ # A translation that runs out of time does so because the text is long and the model is slow,+ # not because the gateway blipped, so a second attempt spends the same budget to fail the same+ # way. The SDK retries twice by default, which makes the caller wait three timeouts before+ # seeing an error. One attempt with a larger budget fails sooner and leaves a text at the+ # 10,000 character cap more room to finish.+ client = get_llm_client("llma_translation").with_options(max_retries=0)target_name = SUPPORTED_LANGUAGES.get(target_language, target_language)- response = client.chat.completions.create(- model=TRANSLATION_MODEL,- messages=[- {- "role": "system",- "content": f"You are a translator. Translate the following text to {target_name}. "- "Only return the translation, nothing else. Preserve formatting and line breaks.",- },- {"role": "user", "content": text},- ],- timeout=30.0,- user=user_distinct_id or "llma-translation",- )+ try:+ response = client.chat.completions.create(+ model=TRANSLATION_MODEL,+ messages=[+ {+ "role": "system",+ "content": f"You are a translator. Translate the following text to {target_name}. "+ "Only return the translation, nothing else. Preserve formatting and line breaks.",+ },+ {"role": "user", "content": text},+ ],+ timeout=TRANSLATION_TIMEOUT_SECONDS,+ user=user_distinct_id or "llma-translation",+ )+ except APITimeoutError as e:+ raise TranslationTimeoutError from econtent = response.choices[0].message.contentreturn content.strip() if content else ""diff --git a/products/ai_observability/backend/translation/test/test_llm.py b/products/ai_observability/backend/translation/test/test_llm.pyindex 5001001bd922..fc3f57faa97c 100644--- a/products/ai_observability/backend/translation/test/test_llm.py+++ b/products/ai_observability/backend/translation/test/test_llm.py@@ -3,20 +3,34 @@import pytestfrom unittest.mock import MagicMock, patch+import httpx+from openai import APITimeoutErrorfrom parameterized import parameterizedfrom products.ai_observability.backend.translation.constants import SUPPORTED_LANGUAGES, TRANSLATION_MODEL-from products.ai_observability.backend.translation.llm import translate_text+from products.ai_observability.backend.translation.llm import TranslationTimeoutError, translate_textMOCK_PATH = "products.ai_observability.backend.translation.llm.get_llm_client"+def mock_llm_client(mock_get_client: MagicMock) -> MagicMock:+ # Self-referential so `with_options(...)` returns the same client the assertions inspect.+ client = MagicMock()+ client.with_options.return_value = client+ mock_get_client.return_value = client+ return client+++def mock_completion(client: MagicMock, content: str | None) -> None:+ response = MagicMock()+ response.choices = [MagicMock(message=MagicMock(content=content))]+ client.chat.completions.create.return_value = response++class TestTranslateText:@patch(MOCK_PATH)def test_returns_translated_text(self, mock_get_client):- mock_response = MagicMock()- mock_response.choices = [MagicMock(message=MagicMock(content=" Hola mundo "))]- mock_get_client.return_value.chat.completions.create.return_value = mock_response+ mock_completion(mock_llm_client(mock_get_client), " Hola mundo ")result = translate_text("Hello world", "es")@@ -24,11 +38,8 @@ class TestTranslateText:@patch(MOCK_PATH)def test_uses_correct_model(self, mock_get_client):- mock_response = MagicMock()- mock_response.choices = [MagicMock(message=MagicMock(content="Translated"))]- mock_client = MagicMock()- mock_client.chat.completions.create.return_value = mock_response- mock_get_client.return_value = mock_client+ mock_client = mock_llm_client(mock_get_client)+ mock_completion(mock_client, "Translated")translate_text("Test", "es")@@ -37,11 +48,8 @@ class TestTranslateText:@patch(MOCK_PATH)def test_uses_fallback_user_when_no_distinct_id(self, mock_get_client):- mock_response = MagicMock()- mock_response.choices = [MagicMock(message=MagicMock(content="Translated"))]- mock_client = MagicMock()- mock_client.chat.completions.create.return_value = mock_response- mock_get_client.return_value = mock_client+ mock_client = mock_llm_client(mock_get_client)+ mock_completion(mock_client, "Translated")translate_text("Test", "es")@@ -50,11 +58,8 @@ class TestTranslateText:@patch(MOCK_PATH)def test_passes_distinct_id_as_user(self, mock_get_client):- mock_response = MagicMock()- mock_response.choices = [MagicMock(message=MagicMock(content="Translated"))]- mock_client = MagicMock()- mock_client.chat.completions.create.return_value = mock_response- mock_get_client.return_value = mock_client+ mock_client = mock_llm_client(mock_get_client)+ mock_completion(mock_client, "Translated")translate_text("Test", "es", user_distinct_id="user-123")@@ -63,22 +68,27 @@ class TestTranslateText:@patch(MOCK_PATH)def test_creates_client_with_correct_product(self, mock_get_client):- mock_response = MagicMock()- mock_response.choices = [MagicMock(message=MagicMock(content="Translated"))]- mock_get_client.return_value.chat.completions.create.return_value = mock_response+ mock_completion(mock_llm_client(mock_get_client), "Translated")translate_text("Test", "es")mock_get_client.assert_called_once_with("llma_translation")+ @patch(MOCK_PATH)+ def test_disables_client_retries(self, mock_get_client):+ mock_client = mock_llm_client(mock_get_client)+ mock_completion(mock_client, "Translated")++ translate_text("Test", "es")++ # Restoring the SDK's default two retries makes a caller wait three timeouts for an error.+ mock_client.with_options.assert_called_once_with(max_retries=0)+@parameterized.expand(list(SUPPORTED_LANGUAGES.items()))@patch(MOCK_PATH)def test_includes_language_name_in_prompt(self, lang_code, lang_name, mock_get_client):- mock_response = MagicMock()- mock_response.choices = [MagicMock(message=MagicMock(content="Translated"))]- mock_client = MagicMock()- mock_client.chat.completions.create.return_value = mock_response- mock_get_client.return_value = mock_client+ mock_client = mock_llm_client(mock_get_client)+ mock_completion(mock_client, "Translated")translate_text("Test", lang_code)@@ -88,11 +98,8 @@ class TestTranslateText:@patch(MOCK_PATH)def test_falls_back_to_language_code_for_unknown_language(self, mock_get_client):- mock_response = MagicMock()- mock_response.choices = [MagicMock(message=MagicMock(content="Translated"))]- mock_client = MagicMock()- mock_client.chat.completions.create.return_value = mock_response- mock_get_client.return_value = mock_client+ mock_client = mock_llm_client(mock_get_client)+ mock_completion(mock_client, "Translated")translate_text("Test", "unknown_lang")@@ -102,11 +109,8 @@ class TestTranslateText:@patch(MOCK_PATH)def test_passes_text_as_user_message(self, mock_get_client):- mock_response = MagicMock()- mock_response.choices = [MagicMock(message=MagicMock(content="Translated"))]- mock_client = MagicMock()- mock_client.chat.completions.create.return_value = mock_response- mock_get_client.return_value = mock_client+ mock_client = mock_llm_client(mock_get_client)+ mock_completion(mock_client, "Translated")translate_text("Hello world", "es")@@ -117,9 +121,7 @@ class TestTranslateText:@patch(MOCK_PATH)def test_returns_empty_string_for_none_content(self, mock_get_client):- mock_response = MagicMock()- mock_response.choices = [MagicMock(message=MagicMock(content=None))]- mock_get_client.return_value.chat.completions.create.return_value = mock_response+ mock_completion(mock_llm_client(mock_get_client), None)result = translate_text("Test", "es")@@ -127,9 +129,7 @@ class TestTranslateText:@patch(MOCK_PATH)def test_strips_whitespace_from_response(self, mock_get_client):- mock_response = MagicMock()- mock_response.choices = [MagicMock(message=MagicMock(content="\n\n Translated text \n\n"))]- mock_get_client.return_value.chat.completions.create.return_value = mock_response+ mock_completion(mock_llm_client(mock_get_client), "\n\n Translated text \n\n")result = translate_text("Test", "es")@@ -137,18 +137,27 @@ class TestTranslateText:@patch(MOCK_PATH)def test_propagates_exceptions(self, mock_get_client):- mock_get_client.return_value.chat.completions.create.side_effect = Exception("API Error")+ mock_llm_client(mock_get_client).chat.completions.create.side_effect = Exception("API Error")with pytest.raises(Exception, match="API Error"):translate_text("Test", "es")+ @patch(MOCK_PATH)+ def test_raises_translation_timeout_error_on_api_timeout(self, mock_get_client):+ mock_llm_client(mock_get_client).chat.completions.create.side_effect = APITimeoutError(+ request=httpx.Request("POST", "http://gateway.invalid/chat/completions")+ )++ # The API layer maps only this type to a 504, so a raw APITimeoutError would surface as a 500.+ with pytest.raises(TranslationTimeoutError):+ translate_text("Test", "es")+@patch(MOCK_PATH)def test_sets_timeout(self, mock_get_client):- mock_response = MagicMock()- mock_response.choices = [MagicMock(message=MagicMock(content="Translated"))]- mock_get_client.return_value.chat.completions.create.return_value = mock_response+ mock_client = mock_llm_client(mock_get_client)+ mock_completion(mock_client, "Translated")translate_text("Test", "es")- call_kwargs = mock_get_client.return_value.chat.completions.create.call_args.kwargs- assert call_kwargs["timeout"] == 30.0+ call_kwargs = mock_client.chat.completions.create.call_args.kwargs+ assert call_kwargs["timeout"] == 45.0diff --git a/products/ai_observability/frontend/ConversationDisplay/TranslatePopover.tsx b/products/ai_observability/frontend/ConversationDisplay/TranslatePopover.tsxindex 7363d05a5379..d40b53cc4e24 100644--- a/products/ai_observability/frontend/ConversationDisplay/TranslatePopover.tsx+++ b/products/ai_observability/frontend/ConversationDisplay/TranslatePopover.tsx@@ -81,7 +81,7 @@ export function TranslatePopover({ content, title = 'Translate' }: TranslatePopo</div>) : translationError ? (<div className="text-center py-2">- <p className="text-danger mb-2">Translation failed. Please try again.</p>+ <p className="text-danger mb-2">{translationError}</p></div>) : translationText ? (<div className="whitespace-pre-wrap text-sm bg-bg-light rounded p-2 max-h-80 overflow-y-auto">