: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): surface a blocked or unresolved judge endpoint (#111747)
Carlos Marchal2c28f2310577
diff --git a/posthog/security/url_validation.py b/posthog/security/url_validation.pyindex cd2357958044..f9e89aeda8f5 100644--- a/posthog/security/url_validation.py+++ b/posthog/security/url_validation.py@@ -26,6 +26,8 @@ class PinnedUrlVerdict:pinned_ips: ResolvedIPs+UNRESOLVED_HOST_REASON = "Could not resolve host"+DNS_RESOLUTION_LIFETIME_SECONDS = 2.0DNS_RESOLUTION_BATCH_TIMEOUT_SECONDS = 2.5DNS_RESOLUTION_MAX_WORKERS = 20@@ -478,7 +480,7 @@ def _validate_url_with_ips(ips = resolve_host_ips(host) if resolved_ips_by_host is None else resolved_ips_by_host.get(host, empty)if not ips:- return _blocked("Could not resolve host", host=host)+ return _blocked(UNRESOLVED_HOST_REASON, host=host)for ip in ips:if _is_internal_ip(ip):return _blocked(f"Disallowed target IP: {ip}", host=host, ip=str(ip))diff --git a/posthog/temporal/ai_observability/evaluation_llm_judge.py b/posthog/temporal/ai_observability/evaluation_llm_judge.pyindex 0701d33d7ba6..5143de9cf988 100644--- a/posthog/temporal/ai_observability/evaluation_llm_judge.py+++ b/posthog/temporal/ai_observability/evaluation_llm_judge.py@@ -55,7 +55,9 @@ from products.ai_observability.backend.llm.errors import (ModelNotFoundError,ModelPermissionError,OutputTokenLimitError,+ ProviderConfigurationError,ProviderConnectionError,+ ProviderHostUnresolvedError,ProviderRequestRejectedError,QuotaExceededError,RateLimitError,@@ -97,6 +99,12 @@ LLM_JUDGE_RETRY_POLICY = RetryPolicy(_RETRYABLE_CLIENT_ERROR_STATUSES = frozenset({408, 409, 429, 499})+def _is_last_judge_attempt() -> bool:+ if not temporalio.activity.in_activity():+ return False+ return temporalio.activity.info().attempt >= (LLM_JUDGE_RETRY_POLICY.maximum_attempts or 0)++class TransientJudgeError(NonReportableError):"""A transient transport failure that reached the judge, wrapped to keep it out of error tracking.@@ -744,7 +752,7 @@ def call_llm_judge(response_format=response_format,))- except SystemOneEndpointBlockedError as e:+ except (SystemOneEndpointBlockedError, ProviderConfigurationError) as e:increment_user_errors("endpoint_blocked", provider=provider)return terminal_user_error_result(spec=require_user_error_spec("endpoint_blocked", is_byok=is_byok),@@ -916,6 +924,21 @@ def call_llm_judge(allows_na, is_byok=is_byok, key_id=key_id, provider=provider, model=model, output_type=output_type)+ except ProviderHostUnresolvedError as e:+ if not _is_last_judge_attempt():+ increment_errors("connection_error", provider=provider)+ raise TransientJudgeError(str(e)) from e+ # The host did not resolve on any attempt, so the base URL is probably wrong. A failed+ # workflow shows the user nothing, so skip the run with the reason instead. A skip leaves+ # the evaluation and its key enabled, because a DNS outage that ends needs no user action.+ increment_user_errors("host_unresolved", provider=provider)+ return build_skipped_evaluation_result(+ output_type=output_type,+ allows_na=allows_na,+ reasoning=str(e),+ skip_reason="host_unresolved",+ )+except ProviderConnectionError as e:# Transient transport failure (connection reset, read timeout). Retrying usually succeeds,# so track it as a metric and re-raise for the retry policy. `TransientJudgeError` keeps itdiff --git a/posthog/temporal/ai_observability/test_run_evaluation.py b/posthog/temporal/ai_observability/test_run_evaluation.pyindex 1f02e9958732..2596214e25ae 100644--- a/posthog/temporal/ai_observability/test_run_evaluation.py+++ b/posthog/temporal/ai_observability/test_run_evaluation.py@@ -2,7 +2,7 @@ import jsonimport uuidimport dataclassesfrom datetime import UTC, datetime, timedelta-from ipaddress import ip_address+from ipaddress import IPv4Address, IPv6Address, ip_addressfrom typing import Any, castimport pytest@@ -666,6 +666,56 @@ def test_provider_rejections_distinguish_blocked_endpoints_from_bad_inputs(assert "uncompressed responses no larger than 1 MiB" in result["reasoning"]+def _call_openai_compatible_judge(resolved_ips: set[IPv4Address | IPv6Address]) -> EvaluationActivityResult:+ key = MagicMock(+ provider="openai_compatible",+ encrypted_config={"api_key": "example-token", "base_url": "https://decisions.example.com/v1"},+ )+ with (+ patch("posthog.security.url_validation.resolve_host_ips", return_value=resolved_ips),+ patch("posthog.temporal.ai_observability.evaluation_llm_judge.model_spec") as spec,+ ):+ spec.return_value.resolve.return_value = MagicMock(+ provider="openai_compatible", model="example-judge-v1", provider_key=key, is_byok=True+ )+ return call_llm_judge(+ evaluation={"id": "test-evaluation", "team_id": 1, "evaluation_config": {"prompt": "Polite?"}},+ system_prompt="",+ user_prompt="Hello!",+ allows_na=False,+ )+++def test_endpoint_on_a_disallowed_address_is_a_terminal_user_error() -> None:+ result = _call_openai_compatible_judge({ip_address("10.0.0.1")})++ assert result["skip_reason"] == "endpoint_blocked"+ assert result["terminal_user_error"] is True+ assert result["provider_key_state"] == "error"+ assert "Base URL must be a public https:// URL" in result["reasoning"]++[email protected]("attempt", [1, 2])+def test_endpoint_host_that_does_not_resolve_is_retried(attempt: int) -> None:+ env = ActivityEnvironment()+ env.info = dataclasses.replace(env.info, attempt=attempt)++ with pytest.raises(TransientJudgeError):+ env.run(_call_openai_compatible_judge, set())+++def test_endpoint_host_that_never_resolves_skips_the_run_with_the_reason() -> None:+ env = ActivityEnvironment()+ env.info = dataclasses.replace(env.info, attempt=3)++ result = env.run(_call_openai_compatible_judge, set())++ assert result["skip_reason"] == "host_unresolved"+ assert "Could not resolve the base URL host" in result["reasoning"]+ assert "terminal_user_error" not in result+ assert "provider_key_state" not in result++@pytest.mark.parametrize("provider, success_payload",[diff --git a/products/ai_observability/backend/api/proxy.py b/products/ai_observability/backend/api/proxy.pyindex effb4d136fb0..3f2e3b355c25 100644--- a/products/ai_observability/backend/api/proxy.py+++ b/products/ai_observability/backend/api/proxy.py@@ -49,7 +49,11 @@ from products.ai_observability.backend.llm import (ModelInfo,get_playground_models,)-from products.ai_observability.backend.llm.errors import ProviderConfigurationError, UnsupportedProviderError+from products.ai_observability.backend.llm.errors import (+ ProviderConfigurationError,+ ProviderHostUnresolvedError,+ UnsupportedProviderError,+)from products.ai_observability.backend.models.provider_keys import (LLMProvider,LLMProviderKey,@@ -231,7 +235,7 @@ class LLMProxyViewSet(viewsets.ViewSet):on_error(Exception("Client disconnected"), perf_counter() - started)returnyield chunk.to_sse().encode()- except ProviderConfigurationError as e:+ except (ProviderConfigurationError, ProviderHostUnresolvedError) as e:if on_error:on_error(e, perf_counter() - started)yield f"data: {json.dumps({'error': str(e), 'status_code': 400})}\n\n".encode()@@ -375,9 +379,9 @@ class LLMProxyViewSet(viewsets.ViewSet):except UnsupportedProviderError:return Response({"error": "Unsupported provider"}, status=400)- except ProviderConfigurationError as e:- # The key's stored configuration is unusable and a retry cannot fix it, so report the- # reason instead of logging an exception on every attempt and returning a 500.+ except (ProviderConfigurationError, ProviderHostUnresolvedError) as e:+ # The key's stored endpoint is unusable or its host does not resolve. The message tells+ # the user what to check, so report it instead of logging an exception and returning a 500.return Response({"error": str(e)}, status=400)except Exception as e:diff --git a/products/ai_observability/backend/llm/errors.py b/products/ai_observability/backend/llm/errors.pyindex 88743853602f..cf561e350074 100644--- a/products/ai_observability/backend/llm/errors.py+++ b/products/ai_observability/backend/llm/errors.py@@ -67,6 +67,14 @@ class ProviderTimeoutError(ProviderConnectionError):)+class ProviderHostUnresolvedError(ProviderConnectionError):+ """A configured endpoint whose hostname did not resolve. A DNS lookup can fail for a moment+ while the endpoint is healthy, so this is retryable and must not disable the provider key."""++ def __init__(self) -> None:+ super().__init__("Could not resolve the base URL host. Check the base URL, then try again.")++RESPONSE_LIMIT_MESSAGE = ("The endpoint returned a compressed or oversized response. ""Configure it to return uncompressed responses no larger than 1 MiB."diff --git a/products/ai_observability/backend/llm/providers/openai_compatible.py b/products/ai_observability/backend/llm/providers/openai_compatible.pyindex d3b5599a9d87..314969b1fb55 100644--- a/products/ai_observability/backend/llm/providers/openai_compatible.py+++ b/products/ai_observability/backend/llm/providers/openai_compatible.py@@ -23,12 +23,13 @@ import openaifrom temporalio.exceptions import CancelledErrorfrom posthog.security.pinned_requests import SSRFBlockedError-from posthog.security.url_validation import is_url_allowed, validate_url_and_pin_ips+from posthog.security.url_validation import UNRESOLVED_HOST_REASON, is_url_allowed, validate_url_and_pin_ipsfrom products.ai_observability.backend.llm.errors import (RESPONSE_LIMIT_MESSAGE,LLMError,ProviderConfigurationError,+ ProviderHostUnresolvedError,ProviderRequestRejectedError,ProviderTimeoutError,RateLimitError,@@ -82,18 +83,29 @@ def error_field_for_validation_message(error_message: str | None) -> str | None:return error_field_for_message(_ERROR_FIELD_BY_PREFIX, error_message)-def is_allowed_custom_base_url(base_url: str) -> bool:- """Return True if the base URL is https:// and passes the shared SSRF validator."""+def _custom_base_url_block_reason(base_url: str) -> str | None:+ """Return why the base URL fails the https:// and shared SSRF checks, or None when it passes."""if not base_url:- return False+ return DISALLOWED_BASE_URL_MESSAGEtry:parsed = urlparse(base_url)except ValueError:- return False+ return DISALLOWED_BASE_URL_MESSAGEif parsed.scheme != "https" or not parsed.hostname:- return False- allowed, _reason = is_url_allowed(base_url)- return allowed+ return DISALLOWED_BASE_URL_MESSAGE+ allowed, reason = is_url_allowed(base_url)+ return None if allowed else reason or DISALLOWED_BASE_URL_MESSAGE+++def is_allowed_custom_base_url(base_url: str) -> bool:+ """Return True if the base URL is https:// and passes the shared SSRF validator."""+ return _custom_base_url_block_reason(base_url) is None+++def _blocked_base_url_error(reason: str) -> LLMError:+ if reason == UNRESOLVED_HOST_REASON:+ return ProviderHostUnresolvedError()+ return ProviderConfigurationError(DISALLOWED_BASE_URL_MESSAGE)def _pinned_http_client(base_url: str, timeout: float) -> httpx.Client:@@ -138,13 +150,17 @@ class OpenAICompatibleAdapter(OpenAIAdapter):``settings.OPENAI_BASE_URL`` in ``OpenAIAdapter.complete`` and send theuser's key to the wrong host."""- if not is_allowed_custom_base_url(self.base_url):- raise ProviderConfigurationError(DISALLOWED_BASE_URL_MESSAGE)+ reason = _custom_base_url_block_reason(self.base_url)+ if reason is not None:+ raise _blocked_base_url_error(reason)return self.base_urldef _build_http_client(self) -> httpx.Client:"""Pin the connection to the configured endpoint's validated address."""- return _pinned_http_client(self._require_allowed_base_url(), self.request_timeout)+ try:+ return _pinned_http_client(self._require_allowed_base_url(), self.request_timeout)+ except SSRFBlockedError as error:+ raise _blocked_base_url_error(str(error)) from errordef _mapped_error(self, error: Exception, model: str) -> LLMError | None:cause = error.__cause__ if isinstance(error, openai.APIConnectionError) else errordiff --git a/products/ai_observability/backend/llm/providers/test/test_openai_compatible.py b/products/ai_observability/backend/llm/providers/test/test_openai_compatible.pyindex 9f5354ffd0cb..3f0b30ff8a50 100644--- a/products/ai_observability/backend/llm/providers/test/test_openai_compatible.py+++ b/products/ai_observability/backend/llm/providers/test/test_openai_compatible.py@@ -13,12 +13,13 @@ from pydantic import BaseModelfrom temporalio.exceptions import CancelledErrorfrom posthog.security.pinned_requests import SSRFBlockedError-from posthog.security.url_validation import PinnedUrlVerdict+from posthog.security.url_validation import UNRESOLVED_HOST_REASON, PinnedUrlVerdictfrom products.ai_observability.backend.llm.errors import (AuthenticationError,LLMError,ProviderConfigurationError,+ ProviderHostUnresolvedError,ProviderRequestRejectedError,ProviderTimeoutError,QuotaExceededError,@@ -181,6 +182,30 @@ class TestOpenAICompatibleAdapter:with pytest.raises(ProviderConfigurationError, match="Base URL must be"):adapter.complete(_completion_request(), "test-key", AnalyticsContext())+ def test_complete_reports_an_unresolved_host_as_retryable(self):+ adapter = OpenAICompatibleAdapter(base_url="https://llm.example.com/v1")++ with patch("posthog.security.url_validation.resolve_host_ips", return_value=set()):+ with pytest.raises(ProviderHostUnresolvedError):+ adapter.complete(_completion_request(), "test-key", AnalyticsContext())++ @parameterized.expand(+ [+ ("unresolved_host", UNRESOLVED_HOST_REASON, ProviderHostUnresolvedError),+ ("internal_address", "Disallowed target IP: 10.0.0.1", ProviderConfigurationError),+ ]+ )+ def test_complete_classifies_a_block_while_pinning_the_connection(self, _name, reason, expected_error):+ adapter = OpenAICompatibleAdapter(base_url=ALLOWED_BASE_URL)++ with patch.object(+ openai_compatible,+ "validate_url_and_pin_ips",+ return_value=PinnedUrlVerdict(allowed=False, reason=reason, pinned_ips=set()),+ ):+ with pytest.raises(expected_error):+ adapter.complete(_completion_request(), "test-key", AnalyticsContext())+def test_stream_refuses_disallowed_base_url(self):adapter = OpenAICompatibleAdapter(base_url="")