: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
chore(llm-gateway): remove Code model gate setting (#81487)
Adam Bowkerbb48e70c5c7a
diff --git a/services/llm-gateway/src/llm_gateway/api/models.py b/services/llm-gateway/src/llm_gateway/api/models.pyindex 369ebb3cd2c1..13aecfb7e814 100644--- a/services/llm-gateway/src/llm_gateway/api/models.py+++ b/services/llm-gateway/src/llm_gateway/api/models.py@@ -7,7 +7,6 @@ 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_settingsfrom llm_gateway.products.config import (FREE_TIER_RESTRICTION_REASON,CreditBucket,@@ -167,7 +166,7 @@ async def list_models_for_product(product: str, request: Request) -> ModelsRespouser = await _authenticated_caller(request)- if resolved != "posthog_code" or not get_settings().posthog_code_model_gate_enabled:+ if resolved != "posthog_code":return responseif not await _caller_confirmed_free_tier(request, user):return responsediff --git a/services/llm-gateway/src/llm_gateway/config.py b/services/llm-gateway/src/llm_gateway/config.pyindex aa2fe21a72cd..d817aebd632d 100644--- a/services/llm-gateway/src/llm_gateway/config.py+++ b/services/llm-gateway/src/llm_gateway/config.py@@ -201,8 +201,6 @@ class Settings(BaseSettings):user_cost_limits: dict[str, UserCostLimit] = DEFAULT_USER_COST_LIMITSuser_cost_limits_disabled: bool = False- # TODO: flip on when Code migrates all users to usage-based billing- posthog_code_model_gate_enabled: bool = Falseposthog_code_free_tier_models: list[str] = ["@cf/zai-org/glm-5.2","deepseek-ai/deepseek-v4-flash-0731",diff --git a/services/llm-gateway/src/llm_gateway/products/config.py b/services/llm-gateway/src/llm_gateway/products/config.pyindex 0e207846dc65..247e9de2b320 100644--- a/services/llm-gateway/src/llm_gateway/products/config.py+++ b/services/llm-gateway/src/llm_gateway/products/config.py@@ -92,18 +92,6 @@ _POSTHOG_CODE_AGENT_MODELS: Final[frozenset[str]] = frozenset(})-# Products whose requires_server_credential applies right away rather than waiting for-# posthog_code_model_gate_enabled. The flag exists so products that already shipped accepting plain-# Code OAuth tokens keep working until the Code billing cutover. A product that never had such a-# permissive period has nothing to stay compatible with, and leaving it flag-gated would ship an-# unbilled route open to any Code OAuth token for as long as the flag is off.-UNCONDITIONAL_SERVER_CREDENTIAL_PRODUCTS: Final[frozenset[str]] = frozenset(- {- "custom_image_scans",- "onboarding",- }-)-# Models reserved for specific products must stay restricted even when a product otherwise allows# every model (`allowed_models=None`). This is an authorization boundary, not merely a# model-registry advertising filter; the registry also derives its advertising from it so the two@@ -433,15 +421,13 @@ def check_free_tier_model_access(code_usage_billed: bool,usage_unlimited: bool,) -> tuple[bool, str | None]:- settings = get_settings()- if not settings.posthog_code_model_gate_enabled:- return True, Noneif resolve_product_alias(product) != "posthog_code":return True, None# model=None is safe: every route requires a model at validation, so the request 422sif code_usage_billed or usage_unlimited or model is None:return True, None+ settings = get_settings()free_models = frozenset(settings.posthog_code_free_tier_models)if _model_matches_product_allowlist(model, free_models, provider=provider, settings=settings):return True, None@@ -521,15 +507,8 @@ def check_product_access(# and route around the posthog_code free-tier model gate. Require the internal marker that# only server-minted tokens carry. OAuth-only: personal API keys reach the gateway with an# explicit, feature-gated llm_gateway:read scope (a `*` PAK is rejected at auth), so the- # shared server-side gateway key still works here. Products that shipped before this check- # existed stay behind the free-tier flag so they keep working until the Code billing cutover;- # the rest enforce it now, per UNCONDITIONAL_SERVER_CREDENTIAL_PRODUCTS.- if (- config.requires_server_credential- and is_oauth- and INTERNAL_RUN_SCOPE not in (scopes or [])- and (settings.posthog_code_model_gate_enabled or resolved_product in UNCONDITIONAL_SERVER_CREDENTIAL_PRODUCTS)- ):+ # shared server-side gateway key still works here.+ if config.requires_server_credential and is_oauth and INTERNAL_RUN_SCOPE not in (scopes or []):return False, f"Product '{product}' requires a server-minted credential"if model and is_model_restricted_for_product(model, resolved_product):diff --git a/services/llm-gateway/tests/test_dependencies.py b/services/llm-gateway/tests/test_dependencies.pyindex b04d8f45eaa6..a02fc12e5af2 100644--- a/services/llm-gateway/tests/test_dependencies.py+++ b/services/llm-gateway/tests/test_dependencies.py@@ -351,7 +351,6 @@ class TestFreeTierModelGateWiring:# the gate must see form-encoded models, not just JSON onesfrom llm_gateway.config import get_settings- monkeypatch.setenv("LLM_GATEWAY_POSTHOG_CODE_MODEL_GATE_ENABLED", "true")get_settings.cache_clear()try:request = _make_form_request(@@ -378,7 +377,6 @@ class TestFreeTierModelGateWiring:# pins that enforce_throttles actually consults the gate on the request pathfrom llm_gateway.config import get_settings- monkeypatch.setenv("LLM_GATEWAY_POSTHOG_CODE_MODEL_GATE_ENABLED", "true")get_settings.cache_clear()try:request = _make_request({"model": "claude-fable-5", "messages": []}, path="/array/v1/messages")@@ -404,6 +402,14 @@ class TestFreeTierModelGateWiring:class TestPreviewModelGateWiring:+ @pytest.fixture(autouse=True)+ def billed_org(self):+ with patch(+ "llm_gateway.dependencies.resolve_plan_and_quota",+ AsyncMock(return_value=(MagicMock(), QuotaResourceStatus(limited=False, code_usage_billing_active=True))),+ ):+ yield+@pytest.mark.asyncio@pytest.mark.parametrize("flag_result", [False, None])async def test_preview_model_blocked_when_flag_off_or_unavailable(self, flag_result: bool | None) -> None:@@ -447,6 +453,14 @@ class TestPreviewModelGateWiring:class TestBasetenExclusiveModelGateWiring:+ @pytest.fixture(autouse=True)+ def billed_org(self):+ with patch(+ "llm_gateway.dependencies.resolve_plan_and_quota",+ AsyncMock(return_value=(MagicMock(), QuotaResourceStatus(limited=False, code_usage_billing_active=True))),+ ):+ yield+# DeepSeek V4 Flash is Baseten-only with no fallback and isn't cleared for external rollout,# so it's blocked behind its own access flag (not the GLM Baseten routing flag).@pytest.mark.asyncio@@ -505,7 +519,6 @@ class TestServerCredentialRequirementWiring:# pins that enforce_product_access actually applies the server-credential check on the pathfrom llm_gateway.config import get_settings- monkeypatch.setenv("LLM_GATEWAY_POSTHOG_CODE_MODEL_GATE_ENABLED", "true")get_settings.cache_clear()try:request = _make_request({"model": "claude-sonnet-5", "messages": []}, path="/signals/v1/messages")@@ -522,7 +535,6 @@ class TestServerCredentialRequirementWiring:# real server-minted token (carrying the marker) would be wrongly rejected here.from llm_gateway.config import get_settings- monkeypatch.setenv("LLM_GATEWAY_POSTHOG_CODE_MODEL_GATE_ENABLED", "true")get_settings.cache_clear()try:request = _make_request({"model": "claude-sonnet-5", "messages": []}, path="/signals/v1/messages")diff --git a/services/llm-gateway/tests/test_models_api.py b/services/llm-gateway/tests/test_models_api.pyindex 0d29408ca3f3..7691a937edbf 100644--- a/services/llm-gateway/tests/test_models_api.py+++ b/services/llm-gateway/tests/test_models_api.py@@ -320,15 +320,6 @@ def _wire_authenticated_user(mock_db_pool, distinct_id: str):class TestFreeTierModelListing:- @pytest.fixture(autouse=True)- def gate_enabled(self, monkeypatch: pytest.MonkeyPatch):- from llm_gateway.config import get_settings-- monkeypatch.setenv("LLM_GATEWAY_POSTHOG_CODE_MODEL_GATE_ENABLED", "true")- get_settings.cache_clear()- yield- get_settings.cache_clear()-def test_anonymous_caller_gets_full_unrestricted_list(self, client: TestClient):# an unidentifiable caller may be a billed org; never mark for thoseresponse = client.get("/posthog_code/v1/models")@@ -337,7 +328,6 @@ class TestFreeTierModelListing:assert "claude-opus-4-5" in {m["id"] for m in models}assert all(m["allowed"] for m in models)- @pytest.mark.parametrize("gate_flag", ["true", "false"], ids=["gate_on", "gate_off"])@pytest.mark.parametrize("error,expected_status",[@@ -351,12 +341,7 @@ class TestFreeTierModelListing:monkeypatch: pytest.MonkeyPatch,error: Exception,expected_status: int,- gate_flag: str,):- from llm_gateway.config import get_settings-- monkeypatch.setenv("LLM_GATEWAY_POSTHOG_CODE_MODEL_GATE_ENABLED", gate_flag)- get_settings.cache_clear()auth_service = MagicMock()auth_service.authenticate_request = AsyncMock(side_effect=error)@@ -380,23 +365,6 @@ class TestFreeTierModelListing:assert response.status_code == 403- def test_gate_off_valid_project_scope_returns_unrestricted_list(self, app, monkeypatch: pytest.MonkeyPatch):- from llm_gateway.config import get_settings-- monkeypatch.setenv("LLM_GATEWAY_POSTHOG_CODE_MODEL_GATE_ENABLED", "false")- get_settings.cache_clear()- auth_service = MagicMock()- auth_service.authenticate_request = AsyncMock(return_value=MagicMock(team_id=123, is_staff=False))-- with patch("llm_gateway.api.models.get_auth_service", return_value=auth_service), TestClient(app) as client:- response = client.get(- "/posthog_code/v1/models",- headers={"Authorization": "Bearer pha_scoped_models", "X-PostHog-Project-Id": "123"},- )-- assert response.status_code == 200- assert all(m["allowed"] for m in response.json()["data"])-def test_unbilled_org_gets_full_list_with_premium_models_marked(self, app, mock_db_pool):from unittest.mock import AsyncMockdiff --git a/services/llm-gateway/tests/test_product_config.py b/services/llm-gateway/tests/test_product_config.pyindex fcf68eb7cc81..d02852112ed4 100644--- a/services/llm-gateway/tests/test_product_config.py+++ b/services/llm-gateway/tests/test_product_config.py@@ -17,16 +17,35 @@ from llm_gateway.products.config import (PRODUCTS,TWIG_EU_APP_ID,TWIG_US_APP_ID,- UNCONDITIONAL_SERVER_CREDENTIAL_PRODUCTS,WIZARD_EU_APP_ID,WIZARD_US_APP_ID,check_free_tier_model_access,- check_product_access,get_product_config,get_required_model_flag,resolve_product_alias,validate_product,)+from llm_gateway.products.config import (+ check_product_access as _check_product_access,+)+++def check_product_access(+ product: str,+ auth_method: str,+ application_id: str | None,+ model: str | None,+ provider: str | None = None,+ scopes: list[str] | None = None,+) -> tuple[bool, str | None]:+ return _check_product_access(+ product,+ auth_method,+ application_id,+ model,+ provider,+ scopes if scopes is not None else ["internal_run:read"],+ )class TestGetProductConfig:@@ -96,8 +115,8 @@ class TestCheckProductAccess:"oauth_access_token",POSTHOG_CODE_US_APP_ID,"@cf/zai-org/glm-5.2",- False,- "server-minted",+ True,+ None,),# llma_translation allows API keys but only gpt-4.1-mini; OAuth rejected (no app IDs configured)("llma_translation", "personal_api_key", None, "gpt-4.1-mini", True, None),@@ -295,7 +314,7 @@ class TestCheckProductAccess:@patch("llm_gateway.products.config.get_settings",- return_value=MagicMock(debug=False, bedrock_region_name="us-east-1", posthog_code_model_gate_enabled=False),+ return_value=MagicMock(debug=False, bedrock_region_name="us-east-1"),)def test_posthog_code_rejects_unallowed_model_via_bedrock_provider(self, mock_get_settings: MagicMock):# A model outside the allowlist with no Bedrock mapping must stay rejected on the bedrock@@ -350,7 +369,7 @@ class TestCheckProductAccess:@patch("llm_gateway.products.config.get_settings",- return_value=MagicMock(debug=False, bedrock_region_name="us-east-1", posthog_code_model_gate_enabled=False),+ return_value=MagicMock(debug=False, bedrock_region_name="us-east-1"),)def test_background_agents_allows_claude_sonnet_4_6_via_bedrock_provider(self, mock_get_settings: MagicMock):allowed, error = check_product_access(@@ -515,31 +534,6 @@ class TestValidateProduct:class TestCheckFreeTierModelAccess:- @pytest.fixture(autouse=True)- def gate_enabled(self, monkeypatch: pytest.MonkeyPatch):- from llm_gateway.config import get_settings-- monkeypatch.setenv("LLM_GATEWAY_POSTHOG_CODE_MODEL_GATE_ENABLED", "true")- get_settings.cache_clear()- yield- get_settings.cache_clear()-- def test_gate_disabled_by_default_allows_premium_models(self, monkeypatch: pytest.MonkeyPatch):- # the PR deploys inert: behavior changes only when the env flag flips- from llm_gateway.config import get_settings-- monkeypatch.delenv("LLM_GATEWAY_POSTHOG_CODE_MODEL_GATE_ENABLED", raising=False)- get_settings.cache_clear()- allowed, error = check_free_tier_model_access(- product="posthog_code",- model="claude-fable-5",- provider=None,- code_usage_billed=False,- usage_unlimited=False,- )- assert allowed is True- assert error is None-@pytest.mark.parametrize("product,model,code_usage_billed,usage_unlimited,expected_allowed",[@@ -614,15 +608,6 @@ class TestServerCredentialRequirement:_MARKER_SCOPES = ["llm_gateway:read", "task:write", "internal_run:read"]- @pytest.fixture(autouse=True)- def gate_enabled(self, monkeypatch: pytest.MonkeyPatch):- from llm_gateway.config import get_settings-- monkeypatch.setenv("LLM_GATEWAY_POSTHOG_CODE_MODEL_GATE_ENABLED", "true")- get_settings.cache_clear()- yield- get_settings.cache_clear()-@pytest.mark.parametrize("product", ["background_agents", "signals", "slack_app", "conversations", "onboarding"])def test_oauth_without_marker_is_rejected(self, product: str):# a desktop Code token (wildcard scope, no internal marker); claude-sonnet-5 is in every@@ -657,45 +642,6 @@ class TestServerCredentialRequirement:assert allowed is Trueassert error is None- def test_gate_disabled_leaves_sibling_access_unchanged(self, monkeypatch: pytest.MonkeyPatch):- # deploys inert: with the flag off, a marker-less token still reaches the siblings- from llm_gateway.config import get_settings-- monkeypatch.delenv("LLM_GATEWAY_POSTHOG_CODE_MODEL_GATE_ENABLED", raising=False)- get_settings.cache_clear()- allowed, error = check_product_access(- "signals", "oauth_access_token", POSTHOG_CODE_US_APP_ID, "claude-sonnet-5", scopes=["*"]- )- assert allowed is True- assert error is None-- # The rest of this class runs with the gate forced on, which is the state in which the- # requirement was already known to hold. These cover the default state, where the products that- # never shipped without the check have to enforce it anyway. Spelled out rather than derived- # from UNCONDITIONAL_SERVER_CREDENTIAL_PRODUCTS: parameterizing over the set under test would- # make dropping a product from it delete its own coverage instead of failing.- @pytest.mark.parametrize("product", ["custom_image_scans", "onboarding"])- def test_gate_disabled_still_refuses_unconditional_products(self, product: str, monkeypatch: pytest.MonkeyPatch):- from llm_gateway.config import get_settings-- monkeypatch.delenv("LLM_GATEWAY_POSTHOG_CODE_MODEL_GATE_ENABLED", raising=False)- get_settings.cache_clear()- allowed, error = check_product_access(product, "oauth_access_token", POSTHOG_CODE_US_APP_ID, None, scopes=["*"])- assert allowed is False- assert error is not None and "server-minted" in error-- @pytest.mark.parametrize("product", ["custom_image_scans", "onboarding"])- def test_gate_disabled_still_admits_server_minted_tokens(self, product: str, monkeypatch: pytest.MonkeyPatch):- from llm_gateway.config import get_settings-- monkeypatch.delenv("LLM_GATEWAY_POSTHOG_CODE_MODEL_GATE_ENABLED", raising=False)- get_settings.cache_clear()- allowed, error = check_product_access(- product, "oauth_access_token", POSTHOG_CODE_US_APP_ID, None, scopes=self._MARKER_SCOPES- )- assert allowed is True- assert error is None-_CODE_APP_IDS = frozenset({POSTHOG_CODE_DEV_APP_ID, POSTHOG_CODE_EU_APP_ID, POSTHOG_CODE_US_APP_ID})_CODE_APP_PRODUCTS = [@@ -718,12 +664,6 @@ class TestServerCredentialConfigInvariant:"posthog_code free-tier model gate")- def test_unconditional_products_are_the_ones_enforcing_without_the_flag(self):- # Pairs with the two flag-off tests above, which name their products literally. If a- # product is added here without flag-off coverage, or removed from here while still- # expected to enforce, exactly one of the two sides fails.- assert UNCONDITIONAL_SERVER_CREDENTIAL_PRODUCTS == frozenset({"custom_image_scans", "onboarding"})-def test_posthog_code_is_the_only_code_app_product_open_to_user_tokens(self):# desktop users hold marker-less Code tokens; requiring the marker on the# user-facing product would lock them all out. Membership is asserted so adiff --git a/services/llm-gateway/tests/test_rate_limiting.py b/services/llm-gateway/tests/test_rate_limiting.pyindex 31b0738b72f6..b39cd4a74cfd 100644--- a/services/llm-gateway/tests/test_rate_limiting.py+++ b/services/llm-gateway/tests/test_rate_limiting.py@@ -271,7 +271,6 @@ class TestFreeTierModelGateErrorBody:from llm_gateway.dependencies import get_authenticated_userfrom llm_gateway.products.config import POSTHOG_CODE_US_APP_ID- monkeypatch.setenv("LLM_GATEWAY_POSTHOG_CODE_MODEL_GATE_ENABLED", "true")get_settings.cache_clear()try:app = create_test_app(mock_db_pool)