: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): say a gated model is unavailable, not an auth failure (#93611)
posthog[bot]558fa6639fa8
diff --git a/products/desktop/packages/agent/src/adapters/base-acp-agent.test.ts b/products/desktop/packages/agent/src/adapters/base-acp-agent.test.tsindex 847edbcb1a04..c1997fea077a 100644--- a/products/desktop/packages/agent/src/adapters/base-acp-agent.test.ts+++ b/products/desktop/packages/agent/src/adapters/base-acp-agent.test.ts@@ -74,4 +74,32 @@ describe("BaseAcpAgent", () => {}),);});++ it.each(["moonshotai/kimi-k3", "deepseek-ai/deepseek-v4-flash-0731"])(+ "does not restore omitted gateway model %s as a custom option",+ async (savedModel) => {+ vi.mocked(fetchGatewayModels).mockResolvedValue([+ {+ id: "claude-opus-4-8",+ owned_by: "anthropic",+ context_window: 1_000_000,+ supports_streaming: true,+ supports_vision: true,+ allowed: true,+ },+ ]);++ const agent = new TestAcpAgent({} as AgentSideConnection);+ const result = await agent.getModelConfigOptions(+ savedModel,+ "https://gateway.us.posthog.com/posthog_code",+ "token",+ );++ expect(result.currentModelId).toBe("claude-opus-4-8");+ expect(result.options).not.toContainEqual(+ expect.objectContaining({ value: savedModel }),+ );+ },+ );});diff --git a/products/desktop/packages/agent/src/adapters/base-acp-agent.ts b/products/desktop/packages/agent/src/adapters/base-acp-agent.tsindex 0e89ef5dc86a..7eb95228d944 100644--- a/products/desktop/packages/agent/src/adapters/base-acp-agent.ts+++ b/products/desktop/packages/agent/src/adapters/base-acp-agent.ts@@ -211,7 +211,14 @@ export abstract class BaseAcpAgent implements Agent {}if (!options.some((opt) => opt.value === currentModelId)) {- if (!isClaudeAdapterModelId(currentModelId)) {+ if (isModalModelId(currentModelId) || isDeepseekModelId(currentModelId)) {+ const fallbackOption =+ options.find((option) => option.value === DEFAULT_GATEWAY_MODEL) ??+ options.find((option) => option._meta === undefined);+ if (fallbackOption) {+ currentModelId = fallbackOption.value;+ }+ } else if (!isClaudeAdapterModelId(currentModelId)) {// A model the Claude adapter can't drive reached it, which means the adapter and model// desynced upstream (e.g. a Codex model paired with the Claude adapter). Log it instead of// silently masquerading as a deliberate Opus session.diff --git a/products/desktop/packages/core/src/billing/usageLimitContent.test.ts b/products/desktop/packages/core/src/billing/usageLimitContent.test.tsindex 0ff269a6eda7..d33333da17ed 100644--- a/products/desktop/packages/core/src/billing/usageLimitContent.test.ts+++ b/products/desktop/packages/core/src/billing/usageLimitContent.test.ts@@ -25,6 +25,21 @@ describe("usageLimitContent", () => {expect(content.actionLabel).toBeNull();});+ it.each([true, false] as const)(+ "never sends a billing prompt for an unavailable model (canManageBilling=%s)",+ (canManageBilling) => {+ const content = usageLimitContent({+ cause: "model_unavailable",+ resetLabel: null,+ subscribed: false,+ canManageBilling,+ });+ expect(content.title).toBe("This model isn't available");+ expect(content.description).toContain("Pick another model");+ expect(content.actionLabel).toBeNull();+ },+ );+it.each([// Confirmed-free org: allocation used up, the fix is adding a card.[false, "Free usage used up", "Add payment method"],diff --git a/products/desktop/packages/core/src/billing/usageLimitContent.ts b/products/desktop/packages/core/src/billing/usageLimitContent.tsindex 5cd032dfa467..343ab466c20b 100644--- a/products/desktop/packages/core/src/billing/usageLimitContent.ts+++ b/products/desktop/packages/core/src/billing/usageLimitContent.ts@@ -34,6 +34,16 @@ export function usageLimitContent(args: {};}+ if (cause === "model_unavailable") {+ return {+ title: "This model isn't available",+ description:+ "It's in preview and isn't turned on for your account yet. Pick another model to keep going.",+ actionLabel: null,+ dismissLabel: "Got it",+ };+ }+if (cause === "org_limit") {if (!canManageBilling) {return {diff --git a/products/desktop/packages/core/src/pi-runtime/piSessionController.ts b/products/desktop/packages/core/src/pi-runtime/piSessionController.tsindex f3b00f1d5319..ec2e0184cc18 100644--- a/products/desktop/packages/core/src/pi-runtime/piSessionController.ts+++ b/products/desktop/packages/core/src/pi-runtime/piSessionController.ts@@ -1177,7 +1177,9 @@ export class PiSessionController {failure: PromptFailure,): string {if (failure.kind === "usage_limit") {- return "Usage limit reached";+ return failure.limitCause === "model_unavailable"+ ? "Model not available"+ : "Usage limit reached";}if (failure.kind === "transient") {return "Provider temporarily unavailable";diff --git a/products/desktop/packages/shared/src/analytics-events.ts b/products/desktop/packages/shared/src/analytics-events.tsindex 419603f4f749..d0bb4241602f 100644--- a/products/desktop/packages/shared/src/analytics-events.ts+++ b/products/desktop/packages/shared/src/analytics-events.ts@@ -1262,7 +1262,7 @@ export type UpgradePromptClickedSurface =| "billing_announcement"| "model_picker";-type UpgradePromptCause = "model_gate" | "org_limit";+type UpgradePromptCause = "model_gate" | "model_unavailable" | "org_limit";export interface UpgradePromptShownProperties {surface: UpgradePromptShownSurface;diff --git a/products/desktop/packages/shared/src/errors.test.ts b/products/desktop/packages/shared/src/errors.test.tsindex 999586e3eb55..3f59c8ba0d7e 100644--- a/products/desktop/packages/shared/src/errors.test.ts+++ b/products/desktop/packages/shared/src/errors.test.ts@@ -99,6 +99,22 @@ describe("classifyGatewayLimitError", () => {"API Error: 403 Model 'gpt-5.5' needs a paid PostHog plan. (rate_limit)","model_gate",],+ [+ `Internal error: API Error: 403 {"error":{"message":"Nope.","type":"permission_error","code":"model_gate"}}`,+ "model_gate",+ ],+ [+ `Internal error: API Error: 403 {"error":{"message":"Model 'moonshotai/kimi-k3' is not available for your account. Choose another model.","type":"permission_error","code":"model_gate","reason":"model_not_available"}}`,+ "model_unavailable",+ ],+ [+ `Internal error: API Error: 403 {"error":{"message":"Model 'moonshotai/kimi-k3' is not available. Choose another model. (rate_limit)","type":"permission_error","code":"model_gate"}}`,+ "model_unavailable",+ ],+ [+ "API Error: 403 Model 'moonshotai/kimi-k3' is not available for your account. Choose another model.",+ "model_unavailable",+ ],[// Bare FastAPI detail from gateways predating the error envelope.`Internal error: API Error: 403 {"detail":"Model 'claude-opus-4-8' needs a paid PostHog plan."}`,@@ -182,6 +198,14 @@ describe("isFatalSessionError", () => {expect(isFatalSessionError(message)).toBe(true);});+ it("does not tear the session down over a model the account can't use", () => {+ expect(+ isFatalSessionError(+ `Internal error: API Error: 403 {"error":{"message":"Model 'moonshotai/kimi-k3' is not available for your account. Choose another model.","type":"permission_error","code":"model_gate","reason":"model_not_available"}}`,+ ),+ ).toBe(false);+ });+it("does not treat a rate-limit error as fatal even if a fatal phrase is present", () => {expect(isFatalSessionError("process exited", "rate limit exceeded")).toBe(false,diff --git a/products/desktop/packages/shared/src/errors.ts b/products/desktop/packages/shared/src/errors.tsindex 3b827f135350..7b4d7e798533 100644--- a/products/desktop/packages/shared/src/errors.ts+++ b/products/desktop/packages/shared/src/errors.ts@@ -74,10 +74,21 @@ const RATE_LIMIT_PATTERNS = ["[429]",] as const;-export type GatewayLimitCause = "model_gate" | "org_limit";+export type GatewayLimitCause =+ | "model_gate"+ | "model_unavailable"+ | "org_limit";++const MODEL_GATE_CODE_REGEX = /"code"\s*:\s*"model_gate"/;+const MODEL_UNAVAILABLE_REASON_REGEX = /"reason"\s*:\s*"model_not_available"/;const MODEL_GATE_PATTERNS = ["needs a paid posthog plan"] as const;+const MODEL_UNAVAILABLE_PATTERNS = [+ "is not available for your account",+ "is not available. choose another model. (rate_limit)",+] as const;+const ORG_LIMIT_PATTERNS = ["cloud usage limit reached","reached its posthog desktop usage limit",@@ -150,7 +161,17 @@ export function classifyGatewayLimitError(): GatewayLimitCause | null {const matches = (patterns: readonly string[]) =>includesAny(errorMessage, patterns) || includesAny(errorDetails, patterns);- if (matches(MODEL_GATE_PATTERNS)) return "model_gate";+ const matchesRegex = (regex: RegExp) =>+ regex.test(errorMessage) || (!!errorDetails && regex.test(errorDetails));+ if (+ matchesRegex(MODEL_UNAVAILABLE_REASON_REGEX) ||+ matches(MODEL_UNAVAILABLE_PATTERNS)+ ) {+ return "model_unavailable";+ }+ if (matchesRegex(MODEL_GATE_CODE_REGEX) || matches(MODEL_GATE_PATTERNS)) {+ return "model_gate";+ }if (matches(ORG_LIMIT_PATTERNS)) return "org_limit";return null;}@@ -257,7 +278,7 @@ export function isFatalSessionError(if (isRateLimitError(errorMessage, errorDetails)) return false;if (isTurnEndedWithoutResponseError(errorMessage, errorDetails)) return false;if (isTransientUpstreamError(errorMessage, errorDetails)) return false;- if (classifyGatewayLimitError(errorMessage, errorDetails) === "model_gate") {+ if (classifyGatewayLimitError(errorMessage, errorDetails) !== null) {return false;}return (diff --git a/services/llm-gateway/PARITY.md b/services/llm-gateway/PARITY.mdindex a17c1e2d8ca5..a38ff011a535 100644--- a/services/llm-gateway/PARITY.md+++ b/services/llm-gateway/PARITY.md@@ -78,7 +78,7 @@ These are compatibility checks, not automatic blockers:| OpenAI APIs | Chat Completions, Responses, bare Responses alias, and normalized router chat. | Audio transcription and broader LiteLLM translation. || Anthropic APIs | Messages and token counting, including Bedrock-hosted models. | OpenAI models exposed through the Anthropic shape and Python-specific Bedrock opt-in behavior. || Providers | OpenAI, Anthropic, Azure OpenAI, Bedrock, and configured Modal, Fireworks, and Baseten hosts. | OpenRouter and Cloudflare Workers AI. |-| Models | Gateway-owned catalog, canonical IDs and aliases, capability checks, router categories, and OpenRouter-shaped pricing. | Broader LiteLLM model acceptance, Python product allowlists, per-model access flags, and product-scoped model pricing. |+| Models | Gateway-owned catalog, canonical IDs and aliases, capability checks, router categories, and OpenRouter-shaped pricing. | Broader LiteLLM model acceptance, Python product allowlists, per-model access flags with caller-filtered listings, and product-scoped model pricing. || Routing and failure behavior | Operator-managed provider plans, health-aware ordering, circuit breakers, hosted-provider failover, and strict provider pinning. | Caller opt-in Bedrock fallback and provider-specific Python routing. || Event metadata | One `X-PostHog-Properties` JSON object plus dedicated product, user, obo, distinct ID, trace ID, and provider headers. | `X-POSTHOG-PROPERTY-*` and `X-POSTHOG-FLAG-*` headers. || Session attribution | `X-PostHog-Session-Id` is recorded as the gateway-owned `$ai_session_id`. | The per-key property header can also emit `$ai_session_id`. |@@ -97,10 +97,10 @@ Run `/migrating-llm-gateway-callers` to inventory and convert a caller.Run `/auditing-llm-gateway-parity` after either gateway changes auth, attribution, billing, endpoints, providers, models, routing, or event metadata. The skill audits implementation sources in both repositories and updates this file without migrating callers.-Last verified on 2026-08-27 against:+Last verified on 2026-09-03 against:-- `PostHog/posthog` working tree compared with master at `88997b515b337b2482814df60c132f60d5de5be4`-- `PostHog/ai-gateway` main at `37ee8bca725a13bca71e40b36f916765f625f939`+- `PostHog/posthog` working tree compared with master at `17484bc3a0b01d930fbcf512ca9f1f2489d7aa84`+- `PostHog/ai-gateway` main at `fb1afc8bebb40ffb43dbd42f2b5a9531cf8f2cb8`## Referencesdiff --git a/services/llm-gateway/src/llm_gateway/api/models.py b/services/llm-gateway/src/llm_gateway/api/models.pyindex 13aecfb7e814..602acf4f39cd 100644--- a/services/llm-gateway/src/llm_gateway/api/models.py+++ b/services/llm-gateway/src/llm_gateway/api/models.py@@ -7,10 +7,13 @@ from pydantic import BaseModelfrom llm_gateway.auth.models import AuthenticatedUserfrom llm_gateway.auth.service import InvalidProjectScopeError, UnauthorizedProjectScopeError, get_auth_service+from llm_gateway.config import get_settings+from llm_gateway.flags import evaluate_flagsfrom llm_gateway.products.config import (FREE_TIER_RESTRICTION_REASON,CreditBucket,filter_to_free_tier_models,+ get_required_model_flag,validate_product,)from llm_gateway.rate_limiting.model_cost_service import ModelCostService@@ -73,6 +76,10 @@ class ModelsResponse(BaseModel):models: list[ModelObject] = [] # Alias for `data` — codex-acp expects this field+def _models_response(models: list[ModelObject]) -> ModelsResponse:+ return ModelsResponse(data=models, models=models)++def _format_rate(rate: float) -> str:return format(Decimal(str(rate)), "f")@@ -113,7 +120,7 @@ def _build_response(product: str) -> ModelsResponse:)for m in models]- return ModelsResponse(data=model_objects, models=model_objects)+ return _models_response(model_objects)async def _authenticated_caller(request: Request) -> AuthenticatedUser | None:@@ -153,10 +160,27 @@ async def _caller_confirmed_free_tier(request: Request, user: AuthenticatedUserreturn not quota_status.code_usage_billing_active+async def _drop_flag_gated_models(models: list[ModelObject], user: AuthenticatedUser | None) -> list[ModelObject]:+ """Models behind an access flag the caller does not hold, removed from the listing.+ Enforcement rejects them on the request path, so listing one only offers a pick that+ fails after a picker already committed to it. Dropped rather than marked `allowed: False`:+ a mark reads as a plan restriction, and no plan change clears a rollout flag.+ Unidentifiable callers keep the full list — there is no identity to evaluate."""+ if user is None or get_settings().debug:+ return models+ required_flag = {m.id: flag for m in models if (flag := get_required_model_flag(m.id)) is not None}+ if not required_flag:+ return models+ flags = sorted(set(required_flag.values()))+ enabled = await evaluate_flags(flags, user.distinct_id)+ return [m for m in models if m.id not in required_flag or enabled.get(required_flag[m.id]) is True]++@models_router.get("/v1/models")async def list_models(request: Request) -> ModelsResponse:- await _authenticated_caller(request)- return _build_response("llm_gateway")+ user = await _authenticated_caller(request)+ response = _build_response("llm_gateway")+ return _models_response(await _drop_flag_gated_models(response.data, user))@models_router.get("/{product}/v1/models")@@ -165,6 +189,7 @@ async def list_models_for_product(product: str, request: Request) -> ModelsResporesponse = _build_response(product)user = await _authenticated_caller(request)+ response = _models_response(await _drop_flag_gated_models(response.data, user))if resolved != "posthog_code":return response@@ -178,4 +203,4 @@ async def list_models_for_product(product: str, request: Request) -> ModelsRespoelse m.model_copy(update={"allowed": False, "restriction_reason": FREE_TIER_RESTRICTION_REASON})for m in response.data]- return ModelsResponse(data=annotated, models=annotated)+ return _models_response(annotated)diff --git a/services/llm-gateway/src/llm_gateway/dependencies.py b/services/llm-gateway/src/llm_gateway/dependencies.pyindex 043c0905a460..3b5e5e2532c7 100644--- a/services/llm-gateway/src/llm_gateway/dependencies.py+++ b/services/llm-gateway/src/llm_gateway/dependencies.py@@ -301,6 +301,28 @@ async def enforce_throttles(model = await get_model_from_request(request)+ access_flag = get_required_model_flag(model)+ if access_flag is not None and not get_settings().debug:+ if not await evaluate_flag(access_flag, user.distinct_id):+ logger.warning(+ "model_access_blocked",+ user_id=user.user_id,+ team_id=user.team_id,+ product=product,+ flag=access_flag,+ )+ raise HTTPException(+ status_code=status.HTTP_403_FORBIDDEN,+ detail={+ "error": {+ "message": f"Model '{model}' is not available for your account. Choose another model. (rate_limit)",+ "type": "permission_error",+ "code": "model_gate",+ "reason": "model_not_available",+ }+ },+ )+model_allowed, model_error = check_free_tier_model_access(product=product,model=model,@@ -326,30 +348,6 @@ async def enforce_throttles(},)- # Entitlement gate for models not cleared for general use on this path (e.g. Kimi K3,- # Baseten-only DeepSeek). Each maps to its own access flag. Fails closed (a None eval outage- # blocks) since these decide spend / backend rollout.- access_flag = get_required_model_flag(model)- if access_flag is not None and not get_settings().debug:- if not await evaluate_flag(access_flag, user.distinct_id):- logger.warning(- "model_access_blocked",- user_id=user.user_id,- team_id=user.team_id,- product=product,- flag=access_flag,- )- raise HTTPException(- status_code=status.HTTP_403_FORBIDDEN,- detail={- "error": {- "message": f"Model '{model}' is not available. Choose another model. (rate_limit)",- "type": "permission_error",- "code": "model_gate",- }- },- )-context = ThrottleContext(user=user,product=product,diff --git a/services/llm-gateway/src/llm_gateway/flags.py b/services/llm-gateway/src/llm_gateway/flags.pyindex 96c9ae3cad96..f4bc4e612234 100644--- a/services/llm-gateway/src/llm_gateway/flags.py+++ b/services/llm-gateway/src/llm_gateway/flags.py@@ -35,27 +35,49 @@ def _get_client() -> Posthog | None:return _client-async def evaluate_flag(flag_key: str, distinct_id: str) -> bool | None:- """None when evaluation is unavailable — callers fall back to their own default."""- cache_key = (flag_key, distinct_id)- if cache_key in _flag_cache:- return _flag_cache[cache_key]- if flag_key in _flag_unavailable_cache:- return None+async def evaluate_flags(flag_keys: list[str], distinct_id: str) -> dict[str, bool | None]:+ unique_keys = list(dict.fromkeys(flag_keys))+ results: dict[str, bool | None] = {}+ missing_keys: list[str] = []+ for flag_key in unique_keys:+ cache_key = (flag_key, distinct_id)+ if cache_key in _flag_cache:+ results[flag_key] = _flag_cache[cache_key]+ elif flag_key in _flag_unavailable_cache:+ results[flag_key] = None+ else:+ missing_keys.append(flag_key)++ if not missing_keys:+ return results+client = _get_client()if client is None:- return None+ return {flag_key: results.get(flag_key) for flag_key in unique_keys}+try:- # Blocking /flags roundtrip — keep it off the event loop. send_feature_flag_events=False:- # with sync_mode the default would also block on a $feature_flag_called capture upload- # (15s SDK timeout) for every uncached user.- enabled = await asyncio.to_thread(client.feature_enabled, flag_key, distinct_id, send_feature_flag_events=False)+ snapshot = await asyncio.to_thread(client.evaluate_flags, distinct_id, flag_keys=missing_keys)except Exception as exc:- logger.warning("flag_evaluation_failed", flag=flag_key, error=str(exc))- _flag_unavailable_cache[flag_key] = True- return None- if enabled is None:- _flag_unavailable_cache[flag_key] = True- return None- _flag_cache[cache_key] = bool(enabled)- return bool(enabled)+ logger.warning("flag_evaluation_failed", flags=missing_keys, error=str(exc))+ for flag_key in missing_keys:+ _flag_unavailable_cache[flag_key] = True+ results[flag_key] = None+ return {flag_key: results[flag_key] for flag_key in unique_keys}++ evaluated_keys = set(snapshot.keys)++ for flag_key in missing_keys:+ if flag_key not in evaluated_keys:+ _flag_unavailable_cache[flag_key] = True+ results[flag_key] = None+ continue+ enabled = snapshot.is_enabled(flag_key)+ _flag_cache[(flag_key, distinct_id)] = enabled+ results[flag_key] = enabled++ return {flag_key: results[flag_key] for flag_key in unique_keys}+++async def evaluate_flag(flag_key: str, distinct_id: str) -> bool | None:+ """None when evaluation is unavailable, so callers can apply their default."""+ return (await evaluate_flags([flag_key], distinct_id))[flag_key]diff --git a/services/llm-gateway/tests/test_dependencies.py b/services/llm-gateway/tests/test_dependencies.pyindex 4f236f2a2a92..73bfaca697d3 100644--- a/services/llm-gateway/tests/test_dependencies.py+++ b/services/llm-gateway/tests/test_dependencies.py@@ -443,6 +443,7 @@ class TestPreviewModelGateWiring:assert error["code"] == "model_gate"assert "moonshotai/kimi-k3" in error["message"]assert error["message"].endswith("(rate_limit)")+ assert error["reason"] == "model_not_available"@pytest.mark.asyncioasync def test_preview_model_allowed_when_flag_enabled(self) -> None:@@ -522,6 +523,34 @@ class TestBasetenExclusiveModelGateWiring:):await enforce_throttles(request=request, user=user, runner=runner)+ @pytest.mark.asyncio+ @pytest.mark.parametrize("flag_result", [False, None])+ async def test_unbilled_glm_gets_rollout_denial_before_billing_denial(self, flag_result: bool | None) -> None:+ request = _make_request({"model": BASETEN_GLM53_PUBLIC_MODEL, "messages": []}, path="/posthog_code/v1/messages")+ user = _make_user(auth_method="oauth_access_token", user_id=7)+ runner = MagicMock()+ runner.check = AsyncMock(return_value=ThrottleResult.allow())++ with (+ patch(+ "llm_gateway.dependencies.resolve_plan_and_quota",+ AsyncMock(+ return_value=(+ MagicMock(),+ QuotaResourceStatus(limited=False, code_usage_billing_active=False),+ )+ ),+ ),+ patch("llm_gateway.dependencies.ensure_costs_fresh"),+ patch("llm_gateway.dependencies.evaluate_flag", AsyncMock(return_value=flag_result)),+ ):+ with pytest.raises(HTTPException) as exc_info:+ await enforce_throttles(request=request, user=user, runner=runner)++ error = exc_info.value.detail["error"]+ assert error["reason"] == "model_not_available"+ assert "payment method" not in error["message"].lower()+class TestServerCredentialRequirementWiring:# The signals path only accepts the Signals app now, so the marker wiring is pinned with itdiff --git a/services/llm-gateway/tests/test_flags.py b/services/llm-gateway/tests/test_flags.pyindex b79a2d8be0ff..69f3ba4bb654 100644--- a/services/llm-gateway/tests/test_flags.py+++ b/services/llm-gateway/tests/test_flags.py@@ -11,19 +11,37 @@ def clear_flag_caches() -> None:flags._flag_unavailable_cache.clear()+def flag_snapshot(values: dict[str, bool]) -> MagicMock:+ snapshot = MagicMock()+ snapshot.keys = list(values)+ snapshot.is_enabled.side_effect = values.__getitem__+ return snapshot++@pytest.mark.parametrize("enabled", [True, False])async def test_evaluate_flag_caches_definitive_answers(enabled: bool) -> None:# Both definitive answers must cache — False (flag disabled) is the normal rollout state, and# caching only True would re-hit /flags on every GLM request while the ramp is off.client = MagicMock()- client.feature_enabled.return_value = enabled+ client.evaluate_flags.return_value = flag_snapshot({"some-flag": enabled})with patch("llm_gateway.flags._get_client", return_value=client):assert await flags.evaluate_flag("some-flag", "user-a") is enabledassert await flags.evaluate_flag("some-flag", "user-a") is enabled# One roundtrip per (flag, user) within the TTL — flag checks sit on the GLM hot path.- assert client.feature_enabled.call_count == 1- # sync_mode would otherwise block each uncached evaluation on a $feature_flag_called upload.- assert client.feature_enabled.call_args.kwargs["send_feature_flag_events"] is False+ assert client.evaluate_flags.call_count == 1+++async def test_evaluate_flags_batches_uncached_keys() -> None:+ client = MagicMock()+ client.evaluate_flags.return_value = flag_snapshot({"flag-a": True, "flag-b": False})++ with patch("llm_gateway.flags._get_client", return_value=client):+ assert await flags.evaluate_flags(["flag-a", "flag-b"], "user-a") == {+ "flag-a": True,+ "flag-b": False,+ }++ client.evaluate_flags.assert_called_once_with("user-a", flag_keys=["flag-a", "flag-b"])@pytest.mark.parametrize("failure_mode", ["sdk_error", "sdk_none"])@@ -33,10 +51,10 @@ async def test_evaluate_flag_backs_off_globally_when_unavailable(failure_mode: s# first miss everyone gets the fallback answer until the backoff expires.client = MagicMock()if failure_mode == "sdk_error":- client.feature_enabled.side_effect = RuntimeError("posthog down")+ client.evaluate_flags.side_effect = RuntimeError("posthog down")else:- client.feature_enabled.return_value = None+ client.evaluate_flags.return_value = flag_snapshot({})with patch("llm_gateway.flags._get_client", return_value=client):assert await flags.evaluate_flag("some-flag", "user-a") is Noneassert await flags.evaluate_flag("some-flag", "user-b") is None- assert client.feature_enabled.call_count == 1+ assert client.evaluate_flags.call_count == 1diff --git a/services/llm-gateway/tests/test_models_api.py b/services/llm-gateway/tests/test_models_api.pyindex 7691a937edbf..97107a0a6421 100644--- a/services/llm-gateway/tests/test_models_api.py+++ b/services/llm-gateway/tests/test_models_api.py@@ -385,14 +385,33 @@ class TestFreeTierModelListing:assert premium["allowed"] is Falseassert premium["restriction_reason"] == "paid_plan_required"# exact, not subset: the default free model must survive the allowlist- # and the annotation, or free-tier callers have no usable model- assert {m["id"] for m in body["data"] if m["allowed"]} == {- "@cf/zai-org/glm-5.2",- "deepseek-ai/deepseek-v4-flash-0731",- }+ assert {m["id"] for m in body["data"] if m["allowed"]} == {"@cf/zai-org/glm-5.2"}# codex reads the `models` mirror; the marks must be there tooassert body["models"] == body["data"]+ @pytest.mark.parametrize(+ "flag_enabled,listed",+ [(True, True), (False, False), (None, False)],+ ids=["flag_on", "flag_off", "flag_unavailable"],+ )+ def test_flag_gated_model_is_listed_only_when_its_flag_clears(+ self, app, mock_db_pool, flag_enabled: bool | None, listed: bool+ ):+ _wire_authenticated_user(mock_db_pool, "gated-user")++ evaluate = AsyncMock(side_effect=lambda flag_keys, _: dict.fromkeys(flag_keys, flag_enabled))+ with (+ patch("llm_gateway.api.models.evaluate_flags", evaluate),+ TestClient(app) as c,+ ):+ response = c.get("/posthog_code/v1/models", headers={"Authorization": "Bearer phx_gated_models"})++ assert response.status_code == 200+ evaluate.assert_awaited_once()+ body = response.json()+ assert ("deepseek-ai/deepseek-v4-flash-0731" in {m["id"] for m in body["data"]}) is listed+ assert body["models"] == body["data"]+def test_billed_org_sees_full_list(self, app, mock_db_pool):from unittest.mock import AsyncMock