Skip to content

: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.

fix(aio): keep byok judge rate limits out of error tracking (#123445)

Carlos Marchal6af035062ff5
diff --git a/posthog/temporal/ai_observability/evaluation_errors.py b/posthog/temporal/ai_observability/evaluation_errors.py
index 2b9d75fdf62f..67f2b40b716c 100644
--- a/posthog/temporal/ai_observability/evaluation_errors.py
+++ b/posthog/temporal/ai_observability/evaluation_errors.py
@@ -135,6 +135,12 @@ USER_ERROR_SPECS: dict[str, EvaluationErrorSpec] = {
owner="user",
safe_message="The score was outside the configured bounds, so this run was skipped. Check the score limits.",
),
+ # Unlike `rate_limit`, this limit can clear on the next run, so the evaluation stays enabled.
+ "rate_limit_retries_exhausted": EvaluationErrorSpec(
+ error_type="rate_limit_retries_exhausted",
+ owner="user",
+ safe_message="The provider kept rate limiting your API key, so this run was skipped. Raise the key's limits or lower the sampling percentage.",
+ ),
}
diff --git a/posthog/temporal/ai_observability/evaluation_llm_judge.py b/posthog/temporal/ai_observability/evaluation_llm_judge.py
index e891e5823bb1..742f4e4b2193 100644
--- a/posthog/temporal/ai_observability/evaluation_llm_judge.py
+++ b/posthog/temporal/ai_observability/evaluation_llm_judge.py
@@ -492,6 +492,23 @@ def _build_rejected_request_skip_result(
return result
+def _build_rate_limit_skip_result(
+ error: RetryableRateLimitError, *, allows_na: bool, output_type: str
+) -> EvaluationActivityResult:
+ reasoning = require_user_error_spec("rate_limit_retries_exhausted").safe_message
+ # Only the SDK error the adapter wrapped carries the provider's sentence. Our own message on
+ # `error` is generic, and the provider's text names the limit that the customer has to change.
+ detail = truncate_error_detail(provider_error_detail(error.__cause__))
+ if detail:
+ reasoning = f"{reasoning} Provider message: {detail}"
+ return build_skipped_evaluation_result(
+ output_type=output_type,
+ allows_na=allows_na,
+ reasoning=reasoning,
+ skip_reason="rate_limit_retries_exhausted",
+ )
+
+
@temporalio.activity.defn
@close_db_connections
# capture_exceptions=False: the worker interceptor reports judge failures, and its capture carries
@@ -847,11 +864,17 @@ def call_llm_judge(
skip_reason="request_rejected",
)
except RetryableRateLimitError as e:
- increment_errors("rate_limit", provider=provider)
retry_delay = timedelta(seconds=e.retry_after) if e.retry_after is not None else None
- # A retry usually gets through, so only an outage that outlasts every attempt reaches error tracking.
last = is_last_attempt(retry_delay) if backfill else _is_last_judge_attempt()
- error_class = ApplicationError if last else NonReportableApplicationError
+ # Decision endpoints raise this error for outages too (408, 503, 529). Only a 429 on the
+ # customer's own key is a limit that the customer sets and PostHog cannot act on.
+ customer_limited = is_byok and e.status == 429
+ if customer_limited and last and not backfill:
+ increment_user_errors("rate_limit_retries_exhausted", provider=provider)
+ return _build_rate_limit_skip_result(e, allows_na=allows_na, output_type=output_type)
+ increment_errors("rate_limit", provider=provider)
+ # A retry usually gets through, so only an outage that outlasts every attempt reaches error tracking.
+ error_class = ApplicationError if last and not customer_limited else NonReportableApplicationError
raise error_class(
str(e),
{"error_type": "provider_unavailable", "provider": provider},
diff --git a/posthog/temporal/ai_observability/test_run_evaluation.py b/posthog/temporal/ai_observability/test_run_evaluation.py
index 26ac0f2ddad6..34a839b10e1b 100644
--- a/posthog/temporal/ai_observability/test_run_evaluation.py
+++ b/posthog/temporal/ai_observability/test_run_evaluation.py
@@ -4,7 +4,7 @@ import dataclasses
from contextlib import nullcontext
from datetime import UTC, datetime, timedelta
from ipaddress import IPv4Address, IPv6Address, ip_address
-from typing import Any, cast
+from typing import Any, Literal, cast
import pytest
from unittest.mock import AsyncMock, MagicMock, patch
@@ -1107,6 +1107,9 @@ def test_endpoint_host_that_never_resolves_skips_the_run_with_the_reason() -> No
assert "provider_key_state" not in result
+RateLimitOutcome = Literal["reported", "unreported", "skipped"]
+
+
@pytest.mark.parametrize(
"provider, success_payload, status, retry_after",
[
@@ -1154,14 +1157,15 @@ def test_endpoint_host_that_never_resolves_skips_the_run_with_the_reason() -> No
],
)
@pytest.mark.parametrize(
- "attempt,backfill,reportable",
+ "attempt,backfill,outcome,customer_limit_outcome",
[
- pytest.param(1, False, False, id="first attempt"),
- pytest.param(3, False, True, id="last attempt"),
- pytest.param(3, True, False, id="backfill third attempt"),
- pytest.param(5, True, True, id="backfill last attempt"),
+ pytest.param(1, False, "unreported", "unreported", id="first attempt"),
+ pytest.param(3, False, "reported", "skipped", id="last attempt"),
+ pytest.param(3, True, "unreported", "unreported", id="backfill third attempt"),
+ pytest.param(5, True, "reported", "unreported", id="backfill last attempt"),
],
)
[email protected]("is_byok", [False, True], ids=["posthog key", "byok"])
def test_custom_provider_rate_limit_retries_without_disabling_the_evaluation(
provider: str,
success_payload: dict[str, Any],
@@ -1169,8 +1173,11 @@ def test_custom_provider_rate_limit_retries_without_disabling_the_evaluation(
retry_after: int,
attempt: int,
backfill: bool,
- reportable: bool,
+ outcome: RateLimitOutcome,
+ customer_limit_outcome: RateLimitOutcome,
+ is_byok: bool,
) -> None:
+ expected = customer_limit_outcome if is_byok and status == 429 else outcome
env = ActivityEnvironment()
env.info = dataclasses.replace(
env.info, attempt=attempt, retry_policy=BACKFILL_ACTIVITY_RETRY_POLICY, schedule_to_close_timeout=None
@@ -1190,7 +1197,11 @@ def test_custom_provider_rate_limit_retries_without_disabling_the_evaluation(
patch(
"httpx.AsyncHTTPTransport.handle_async_request",
side_effect=[
- httpx.Response(status, headers={"Retry-After": str(retry_after)}, stream=httpx.ByteStream(b"")),
+ httpx.Response(
+ status,
+ headers={"Retry-After": str(retry_after), "Content-Type": "application/json"},
+ stream=httpx.ByteStream(b'{"error": {"message": "Too many concurrent requests for this key."}}'),
+ ),
httpx.Response(
200,
headers={"Content-Type": "application/json"},
@@ -1198,28 +1209,44 @@ def test_custom_provider_rate_limit_retries_without_disabling_the_evaluation(
),
],
) as transport,
+ patch("posthog.temporal.ai_observability.evaluation_llm_judge.increment_user_errors") as user_errors,
):
spec.return_value.resolve.return_value = MagicMock(
provider=provider,
model="gpt-6-luna" if provider == "openai" else "example-judge-v1",
provider_key=key,
- is_byok=True,
+ is_byok=is_byok,
)
- with pytest.raises(ApplicationError) as error:
- env.run(
- lambda: call_llm_judge(
- evaluation=evaluation,
- system_prompt="",
- user_prompt="Hello!",
- allows_na=False,
- backfill=backfill,
- )
+
+ def run_judge() -> EvaluationActivityResult:
+ return call_llm_judge(
+ evaluation=evaluation,
+ system_prompt="",
+ user_prompt="Hello!",
+ allows_na=False,
+ backfill=backfill,
)
- assert not error.value.non_retryable
- assert isinstance(error.value, NonReportableError) is not reportable
- assert error.value.next_retry_delay == timedelta(seconds=retry_after)
- assert terminal_user_error_result_from_application_error(error.value, allows_na=False) is None
+
+ if expected == "skipped":
+ skipped = env.run(run_judge)
+ assert skipped["skip_reason"] == "rate_limit_retries_exhausted"
+ assert "terminal_user_error" not in skipped
+ assert "provider_key_state" not in skipped
+ # Only the OpenAI-compatible adapter wraps an SDK error that carries the provider's text.
+ assert ("Too many concurrent requests for this key." in skipped["reasoning"]) is (
+ provider == "openai_compatible"
+ )
+ else:
+ with pytest.raises(ApplicationError) as error:
+ env.run(run_judge)
+ assert not error.value.non_retryable
+ assert isinstance(error.value, NonReportableError) is (expected == "unreported")
+ assert error.value.next_retry_delay == timedelta(seconds=retry_after)
+ assert terminal_user_error_result_from_application_error(error.value, allows_na=False) is None
assert transport.call_count == 1
+ assert [call.args[0] for call in user_errors.call_args_list] == (
+ ["rate_limit_retries_exhausted"] if expected == "skipped" else []
+ )
result = call_llm_judge(
evaluation=evaluation,
diff --git a/products/ai_observability/backend/backfill_candidates.py b/products/ai_observability/backend/backfill_candidates.py
index 9c2c862b423b..dcc384414049 100644
--- a/products/ai_observability/backend/backfill_candidates.py
+++ b/products/ai_observability/backend/backfill_candidates.py
@@ -111,9 +111,9 @@ WHERE event = '$ai_generation'
GROUP BY unit_id
"""
-# Unparsable or truncated judge responses can succeed on a later run, so they do not count
-# as evaluated. A trace that errored, a prompt over the context window, or a
-# content-filter refusal skips again.
+# Unparsable or truncated judge responses, and runs that a provider kept rate limiting, can
+# succeed on a later run, so they do not count as evaluated. A trace that errored, a prompt over
+# the context window, or a content-filter refusal skips again.
# Reads the shared events table rather than ai_events: the verdict rows must stay visible past the
# ai_events retention window, so a re-run of an old backfill still sees what it already covered.
_ALREADY_EVALUATED_SQL = """
@@ -125,7 +125,9 @@ WHERE event = '$ai_evaluation'
AND timestamp >= {window_start}
AND timestamp < {verdict_end}
AND (isNull(properties.$ai_evaluation_skip_reason)
- OR properties.$ai_evaluation_skip_reason NOT IN ('unparsable_response', 'output_limit_exceeded'))
+ OR properties.$ai_evaluation_skip_reason NOT IN (
+ 'unparsable_response', 'output_limit_exceeded', 'rate_limit_retries_exhausted'
+ ))
"""
diff --git a/products/ai_observability/backend/llm/decisions.py b/products/ai_observability/backend/llm/decisions.py
index 53bad19d8f6a..ea63d3f3ea2f 100644
--- a/products/ai_observability/backend/llm/decisions.py
+++ b/products/ai_observability/backend/llm/decisions.py
@@ -88,8 +88,10 @@ class DecisionEndpointBlockedError(LLMError):
class DecisionRateLimitError(RetryableRateLimitError):
- def __init__(self, retry_after: str | None) -> None:
- super().__init__("The decision endpoint is temporarily unavailable. Try again later.", retry_after)
+ def __init__(self, retry_after: str | None, *, status: int) -> None:
+ super().__init__(
+ "The decision endpoint is temporarily unavailable. Try again later.", retry_after, status=status
+ )
class DecisionClient:
@@ -173,7 +175,7 @@ class DecisionClient:
if status == 404:
raise ModelNotFoundError(model)
if status in (408, 429, 503, 529):
- raise DecisionRateLimitError(response.headers.get("Retry-After"))
+ raise DecisionRateLimitError(response.headers.get("Retry-After"), status=status)
if status >= 500:
raise ProviderConnectionError("The decision endpoint is temporarily unavailable. Try again.")
if 300 <= status < 400:
diff --git a/products/ai_observability/backend/llm/errors.py b/products/ai_observability/backend/llm/errors.py
index 49713723e7ee..e0e8584abe0f 100644
--- a/products/ai_observability/backend/llm/errors.py
+++ b/products/ai_observability/backend/llm/errors.py
@@ -47,8 +47,9 @@ class RateLimitError(LLMError):
class RetryableRateLimitError(RateLimitError):
- def __init__(self, message: str, retry_after: str | None = None) -> None:
+ def __init__(self, message: str, retry_after: str | None = None, *, status: int = 429) -> None:
super().__init__(message)
+ self.status = status
self.retry_after: float | None = None
if retry_after:
try:
@@ -181,7 +182,7 @@ class ModelPermissionError(LLMError):
super().__init__(msg)
-def provider_error_detail(error: Exception | None) -> str | None:
+def provider_error_detail(error: BaseException | None) -> str | None:
"""The provider's own sentence, without the SDK's `Error code: NNN - {...}` wrapper.
`str(e)` on an OpenAI or Anthropic error embeds the whole response dict, so read the parsed
diff --git a/products/ai_observability/backend/llm/providers/openai_decisions.py b/products/ai_observability/backend/llm/providers/openai_decisions.py
index 6484bfc62078..1d2dcc09c8be 100644
--- a/products/ai_observability/backend/llm/providers/openai_decisions.py
+++ b/products/ai_observability/backend/llm/providers/openai_decisions.py
@@ -159,7 +159,9 @@ class OpenAIDecisionAdapter(OpenAIAdapter):
and error.status_code in (429, 503, 529)
and not isinstance(mapped, QuotaExceededError)
):
- raise DecisionRateLimitError(error.response.headers.get("Retry-After")) from error
+ raise DecisionRateLimitError(
+ error.response.headers.get("Retry-After"), status=error.status_code
+ ) from error
if mapped is not None:
raise mapped from error
if isinstance(error, openai.APIStatusError):
diff --git a/products/ai_observability/backend/test/test_backfill_candidates.py b/products/ai_observability/backend/test/test_backfill_candidates.py
index b2a35ec3e1b3..e7d11adfa6a6 100644
--- a/products/ai_observability/backend/test/test_backfill_candidates.py
+++ b/products/ai_observability/backend/test/test_backfill_candidates.py
@@ -245,9 +245,10 @@ class TestBackfillCandidates(ClickhouseTestMixin, APIBaseTest):
@parameterized.expand(
[
- # A judge response nobody could read may parse on a later run, so the unit is still owed a verdict.
+ # A later run can succeed for these, so the unit is still owed a verdict.
("unparsable_response", 4),
("output_limit_exceeded", 4),
+ ("rate_limit_retries_exhausted", 4),
# These skip the same way every run, so re-offering them would never produce a verdict.
("context_window_exceeded", 3),
("trace_errored", 3),