: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(llm-gateway): fail over to Bedrock on Anthropic billing blocks (#66298)
Joshua Snyderb99ea1ec176c
diff --git a/services/llm-gateway/src/llm_gateway/api/anthropic.py b/services/llm-gateway/src/llm_gateway/api/anthropic.pyindex fedc47a2c804..cf2d8045443f 100644--- a/services/llm-gateway/src/llm_gateway/api/anthropic.py+++ b/services/llm-gateway/src/llm_gateway/api/anthropic.py@@ -15,6 +15,7 @@ from llm_gateway.api.handler import (ANTHROPIC_CONFIG,BEDROCK_CONFIG,CLOUDFLARE_ANTHROPIC_CONFIG,+ ProviderError,_sanitize_request_data,handle_llm_request,normalize_litellm_model_name,@@ -287,6 +288,56 @@ async def _maybe_bypass_anthropic(return decision.bypass+# Substrings that identify Anthropic's billing / spend-limit refusals within a 400 error message.+# Anthropic returns these as HTTP 400 invalid_request_error — the same status+type as a genuinely+# malformed request — so the status code can't tell them apart and the message is the only signal.+# Matched case-insensitively. Keep this a tight allowlist: broadening it to all 400s would fail+# real bad requests (prompt-too-long, bad image, role ordering) over to Bedrock, which rejects them+# identically and just adds a wasted round-trip.+_ANTHROPIC_BILLING_SIGNATURES: tuple[str, ...] = (+ "credit balance", # "Your credit balance is too low to access the Anthropic API"+ "usage limit", # "You have reached your specified workspace API usage limits"+ "regain access", # "...You will regain access on <date>"+ "plans & billing", # "...go to Plans & Billing to upgrade or purchase credits"+)+++def _is_anthropic_billing_block(exc: HTTPException) -> bool:+ """True when Anthropic refused the request for billing / spend-limit reasons.++ These surface as HTTP 400 invalid_request_error (e.g. a workspace usage-limit block or an+ exhausted prepaid balance), not 5xx/429 — so they are genuinely provider-down but look like a+ caller error. We match the upstream message carried in `detail["error"]["message"]`.++ Gated on `ProviderError` so it only ever fires on a genuine upstream-provider failure: a+ gateway-local 400 (e.g. unsupported model) echoes the caller's model name into the message, and+ without this guard a crafted name like "gemini/credit balance is too low" would be misread as a+ billing block and poison the shared circuit breaker.+ """+ if not isinstance(exc, ProviderError):+ return False+ if exc.status_code != 400:+ return False+ detail = exc.detail+ if not isinstance(detail, dict):+ return False+ error = detail.get("error")+ if not isinstance(error, dict):+ return False+ message = str(error.get("message", "")).lower()+ return any(signature in message for signature in _ANTHROPIC_BILLING_SIGNATURES)+++def _anthropic_error_type(exc: HTTPException) -> str:+ """The provider error type from an Anthropic-style HTTPException detail, or "unknown"."""+ detail = exc.detail+ if isinstance(detail, dict):+ error = detail.get("error")+ if isinstance(error, dict):+ return str(error.get("type", "unknown"))+ return "unknown"++def _is_breaker_success(status_code: int) -> bool:"""4xx are caller-side errors and don't reflect Anthropic health, except 429 — that'sAnthropic-side throttling and is exactly the kind of degradation the breaker exists for.@@ -374,12 +425,16 @@ async def _handle_anthropic_messages(product=product,)except HTTPException as exc:- await _record_anthropic_outcome(breaker, success=_is_breaker_success(exc.status_code))- # Fall back to Bedrock for any provider-attributable failure (5xx + 429 throttling).- if not use_bedrock_fallback or _is_breaker_success(exc.status_code):+ # Provider-attributable failures we fail over for: 5xx, 429 throttling, and billing/spend-limit+ # blocks (which arrive as 400 invalid_request_error). All three are recorded as breaker+ # failures so the breaker can open; ordinary caller-side 4xx stay a breaker success.+ billing_block = _is_anthropic_billing_block(exc)+ fallback_eligible = billing_block or not _is_breaker_success(exc.status_code)+ await _record_anthropic_outcome(breaker, success=not fallback_eligible)+ if not use_bedrock_fallback or not fallback_eligible:raise- error_type = exc.detail.get("error", {}).get("type", "unknown") if isinstance(exc.detail, dict) else "unknown"+ error_type = "billing_block" if billing_block else _anthropic_error_type(exc)logger.warning("Anthropic request failed, attempting Bedrock fallback",model=body.model,@@ -452,7 +507,7 @@ async def _handle_count_tokens(if not use_bedrock_fallback or _is_breaker_success(exc.status_code):raise- error_type = exc.detail.get("error", {}).get("type", "unknown") if isinstance(exc.detail, dict) else "unknown"+ error_type = _anthropic_error_type(exc)logger.warning("Anthropic count_tokens failed, attempting Bedrock fallback",model=body.model,diff --git a/services/llm-gateway/src/llm_gateway/api/handler.py b/services/llm-gateway/src/llm_gateway/api/handler.pyindex 4af18dda8342..87cc2bf227c3 100644--- a/services/llm-gateway/src/llm_gateway/api/handler.py+++ b/services/llm-gateway/src/llm_gateway/api/handler.py@@ -78,6 +78,15 @@ _UNSUPPORTED_MODEL_PREFIXES = ()+class ProviderError(HTTPException):+ """An HTTPException raised from the upstream provider call itself, as opposed to gateway-local+ validation (unsupported model, bad headers, timeouts). Lets downstream handlers tell a genuine+ provider failure apart from a gateway 400 that merely echoes caller-controlled input — e.g. the+ Anthropic billing-block detector must not key off an unsupported-model message containing the+ caller's model name. Subclasses HTTPException so it serializes to the client identically.+ """++def _raise_unsupported_model(model: str) -> None:raise HTTPException(status_code=400,@@ -204,7 +213,7 @@ async def handle_llm_request(provider_error_type=getattr(e, "type", None),provider_error_code=getattr(e, "code", None),)- raise HTTPException(+ raise ProviderError(status_code=status_code,detail={"error": {@@ -286,7 +295,7 @@ async def _handle_streaming_request(streaming="true",product=product,).observe(time.monotonic() - start_time)- raise HTTPException(+ raise ProviderError(status_code=status_code,detail={"error": {diff --git a/services/llm-gateway/tests/test_anthropic.py b/services/llm-gateway/tests/test_anthropic.pyindex f7e7ac5fe141..a571f495e438 100644--- a/services/llm-gateway/tests/test_anthropic.py+++ b/services/llm-gateway/tests/test_anthropic.py@@ -6,9 +6,12 @@ from unittest.mock import AsyncMock, MagicMock, patchimport httpximport pytest+from fastapi import HTTPExceptionfrom fastapi.testclient import TestClientfrom starlette.datastructures import Headers+from llm_gateway.api.anthropic import _is_anthropic_billing_block+from llm_gateway.api.handler import ProviderErrorfrom llm_gateway.request_context import (extract_posthog_flags_from_headers,extract_posthog_properties_from_headers,@@ -1485,6 +1488,127 @@ class TestAnthropicCircuitBreakerIntegration:assert "context_management" in anthropic_kwargsassert "context_management" not in bedrock_kwargs+ @patch("llm_gateway.api.anthropic.litellm.anthropic_messages")+ def test_anthropic_billing_block_with_fallback_routes_to_bedrock(+ self,+ mock_anthropic: MagicMock,+ authenticated_client: TestClient,+ install_breaker,+ mock_response_dict: dict,+ ) -> None:+ """A workspace usage-limit / out-of-funds block arrives as HTTP 400 invalid_request_error,+ not 5xx/429 — it must still fail over to Bedrock instead of being passed back to the caller."""+ request_body = {"model": "claude-opus-4-8", "messages": [{"role": "user", "content": "Hi"}]}+ breaker = install_breaker(bypass=False)+ error = Exception("billing")+ error.status_code = 400 # type: ignore[attr-defined]+ error.message = '{"type":"error","error":{"type":"invalid_request_error","message":"You have reached your specified workspace API usage limits. You will regain access on 2026-07-01 at 00:00 UTC."}}' # type: ignore[attr-defined]+ error.type = "invalid_request_error" # type: ignore[attr-defined]++ bedrock_response = MagicMock()+ bedrock_response.model_dump = MagicMock(return_value=mock_response_dict)+ mock_anthropic.side_effect = [error, bedrock_response]++ with patch(+ "llm_gateway.api.anthropic.get_settings",+ return_value=MagicMock(bedrock_region_name="us-east-1", request_timeout=300.0),+ ):+ response = authenticated_client.post(+ "/v1/messages",+ json=request_body,+ headers={+ "Authorization": "Bearer phx_test_key",+ "X-PostHog-Use-Bedrock-Fallback": "true",+ },+ )++ assert response.status_code == 200+ breaker.record_outcome.assert_awaited_with(success=False)+ assert mock_anthropic.call_count == 2+ assert mock_anthropic.call_args_list[1].kwargs["model"] == "bedrock/us.anthropic.claude-opus-4-8"++ @patch("llm_gateway.api.anthropic.litellm.anthropic_messages")+ def test_anthropic_billing_block_recorded_as_failure(+ self,+ mock_anthropic: MagicMock,+ authenticated_client: TestClient,+ install_breaker,+ request_body: dict,+ ) -> None:+ """Even without the fallback header, a billing block is provider-attributable, so the breaker+ must record it as a failure (so it can open) rather than as a caller-side success."""+ breaker = install_breaker(bypass=False)+ error = Exception("billing")+ error.status_code = 400 # type: ignore[attr-defined]+ error.message = "Your credit balance is too low to access the Anthropic API. Please go to Plans & Billing to upgrade or purchase credits." # type: ignore[attr-defined]+ error.type = "invalid_request_error" # type: ignore[attr-defined]+ mock_anthropic.side_effect = error++ response = authenticated_client.post(+ "/v1/messages",+ json=request_body,+ headers={"Authorization": "Bearer phx_test_key"},+ )++ assert response.status_code == 400+ breaker.record_outcome.assert_awaited_with(success=False)++ @patch("llm_gateway.api.anthropic.litellm.anthropic_messages")+ def test_gateway_validation_400_does_not_poison_breaker(+ self,+ mock_anthropic: MagicMock,+ authenticated_client: TestClient,+ install_breaker,+ ) -> None:+ """A gateway-generated unsupported-model 400 echoes the caller's model name. A crafted name+ containing a billing phrase must NOT be recorded as an Anthropic provider failure — otherwise+ an authenticated caller could open the shared circuit breaker (breaker poisoning)."""+ breaker = install_breaker(bypass=False)+ request_body = {"model": "gemini/credit balance is too low", "messages": [{"role": "user", "content": "Hi"}]}++ response = authenticated_client.post(+ "/v1/messages",+ json=request_body,+ headers={+ "Authorization": "Bearer phx_test_key",+ "X-PostHog-Use-Bedrock-Fallback": "true",+ },+ )++ assert response.status_code == 400+ assert mock_anthropic.call_count == 0 # rejected before any provider call+ breaker.record_outcome.assert_awaited_with(success=True)++ @patch("llm_gateway.api.anthropic.litellm.anthropic_messages")+ def test_generic_400_not_routed_to_bedrock(+ self,+ mock_anthropic: MagicMock,+ authenticated_client: TestClient,+ install_breaker,+ ) -> None:+ """A genuinely malformed request (also HTTP 400 invalid_request_error) must NOT fail over —+ Bedrock would reject it identically, so it stays a caller error and a breaker success."""+ request_body = {"model": "claude-opus-4-8", "messages": [{"role": "user", "content": "Hi"}]}+ breaker = install_breaker(bypass=False)+ error = Exception("bad request")+ error.status_code = 400 # type: ignore[attr-defined]+ error.message = "prompt is too long: 1010381 tokens > 1000000 maximum" # type: ignore[attr-defined]+ error.type = "invalid_request_error" # type: ignore[attr-defined]+ mock_anthropic.side_effect = error++ response = authenticated_client.post(+ "/v1/messages",+ json=request_body,+ headers={+ "Authorization": "Bearer phx_test_key",+ "X-PostHog-Use-Bedrock-Fallback": "true",+ },+ )++ assert response.status_code == 400+ assert mock_anthropic.call_count == 1+ breaker.record_outcome.assert_awaited_with(success=True)+def test_streaming_success_records_after_stream_completes(self,authenticated_client: TestClient,@@ -1537,3 +1661,67 @@ class TestAnthropicCircuitBreakerIntegration:asyncio.run(consume())breaker.record_outcome.assert_awaited_with(success=False)+++class TestAnthropicBillingBlockDetection:+ """`_is_anthropic_billing_block` must separate Anthropic's financial blocks (fail over to Bedrock)+ from genuinely malformed requests (don't) — both arrive as HTTP 400 invalid_request_error, so the+ only signal is the upstream message. Fixtures are real messages captured in production. Detection+ is gated on ProviderError so a gateway-local 400 that echoes caller input can't be misread."""++ @pytest.mark.parametrize(+ "case,status_code,message,expected",+ [+ (+ "workspace_usage_limit",+ 400,+ '{"type":"error","error":{"type":"invalid_request_error","message":"You have reached your specified workspace API usage limits. You will regain access on 2026-07-01 at 00:00 UTC."}}',+ True,+ ),+ (+ "credit_balance_too_low",+ 400,+ "Your credit balance is too low to access the Anthropic API. Please go to Plans & Billing to upgrade or purchase credits.",+ True,+ ),+ ("prompt_too_long", 400, "prompt is too long: 1010381 tokens > 1000000 maximum", False),+ (+ "image_dimensions",+ 400,+ "messages.77.content.7.image.source.base64.data: At least one of the image dimensions exceed max allowed size for many-image requests: 2000 pixels",+ False,+ ),+ (+ "bad_role_order",+ 400,+ "messages.2: role 'system' must follow a 'user' message or an 'assistant' message ending in a server tool result",+ False,+ ),+ ("could_not_process_image", 400, "Could not process image", False),+ ("billing_text_but_5xx", 500, "Your credit balance is too low to access the Anthropic API.", False),+ ],+ )+ def test_billing_block_detection(self, case: str, status_code: int, message: str, expected: bool) -> None:+ exc = ProviderError(+ status_code=status_code, detail={"error": {"message": message, "type": "invalid_request_error"}}+ )+ assert _is_anthropic_billing_block(exc) is expected++ def test_non_dict_detail_is_not_billing(self) -> None:+ assert _is_anthropic_billing_block(ProviderError(status_code=400, detail="opaque string")) is False++ def test_gateway_origin_billing_text_is_not_billing(self) -> None:+ """A gateway-local 400 (plain HTTPException, not ProviderError) that echoes a caller model+ name containing a billing phrase must not be treated as a provider billing block — otherwise+ a crafted model name could poison the shared circuit breaker."""+ exc = HTTPException(+ status_code=400,+ detail={+ "error": {+ "message": "Model 'gemini/credit balance is too low' is not supported by this gateway",+ "type": "invalid_request_error",+ "code": "model_not_supported",+ }+ },+ )+ assert _is_anthropic_billing_block(exc) is False