: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
feat(gateway): add staff rate-limit multiplier alongside team id (#63153)
Richard Solomou342997c5d7de
diff --git a/services/llm-gateway/src/llm_gateway/auth/authenticators.py b/services/llm-gateway/src/llm_gateway/auth/authenticators.pyindex 88685f50bf7c..815879e97000 100644--- a/services/llm-gateway/src/llm_gateway/auth/authenticators.py+++ b/services/llm-gateway/src/llm_gateway/auth/authenticators.py@@ -62,7 +62,7 @@ class PersonalApiKeyAuthenticator(Authenticator):async with acquire_connection(pool) as conn:row = await conn.fetchrow("""- SELECT pak.id, pak.user_id, pak.scopes, u.current_team_id, u.distinct_id+ SELECT pak.id, pak.user_id, pak.scopes, u.current_team_id, u.distinct_id, u.is_staffFROM posthog_personalapikey pakJOIN posthog_user u ON pak.user_id = u.idWHERE pak.secure_value = $1 AND u.is_active = true@@ -83,6 +83,7 @@ class PersonalApiKeyAuthenticator(Authenticator):auth_method=self.auth_type,distinct_id=row["distinct_id"],scopes=scopes,+ is_staff=row["is_staff"],)@@ -108,7 +109,7 @@ class OAuthAccessTokenAuthenticator(Authenticator):row = await conn.fetchrow("""SELECT oat.id, oat.user_id, oat.scope, oat.expires,- oat.application_id, u.current_team_id, u.distinct_id+ oat.application_id, u.current_team_id, u.distinct_id, u.is_staffFROM posthog_oauthaccesstoken oatJOIN posthog_user u ON oat.user_id = u.idWHERE oat.token_checksum = $1 AND u.is_active = true@@ -138,4 +139,5 @@ class OAuthAccessTokenAuthenticator(Authenticator):scopes=scopes,token_expires_at=expires,application_id=str(row["application_id"]),+ is_staff=row["is_staff"],)diff --git a/services/llm-gateway/src/llm_gateway/auth/models.py b/services/llm-gateway/src/llm_gateway/auth/models.pyindex 5bcad3e287cd..d83956bb1d04 100644--- a/services/llm-gateway/src/llm_gateway/auth/models.py+++ b/services/llm-gateway/src/llm_gateway/auth/models.py@@ -11,6 +11,7 @@ class AuthenticatedUser:scopes: list[str] | None = Nonetoken_expires_at: datetime | None = Noneapplication_id: str | None = None+ is_staff: bool = Falsedef resolve_distinct_id(auth_user: AuthenticatedUser, end_user_id: str | None) -> str:diff --git a/services/llm-gateway/src/llm_gateway/config.py b/services/llm-gateway/src/llm_gateway/config.pyindex a50f8562e1d3..68a53dc1cd30 100644--- a/services/llm-gateway/src/llm_gateway/config.py+++ b/services/llm-gateway/src/llm_gateway/config.py@@ -158,6 +158,11 @@ class Settings(BaseSettings):team_rate_limit_multipliers: dict[int, int] = {}+ # Additional elevated cap for PostHog staff, keyed on the authenticated+ # user's is_staff flag rather than team id, so it survives impersonation.+ # Combined with the team multiplier by taking the larger of the two.+ staff_rate_limit_multiplier: int = 10+product_cost_limits: dict[str, ProductCostLimit] = DEFAULT_PRODUCT_COST_LIMITSuser_cost_limits: dict[str, UserCostLimit] = DEFAULT_USER_COST_LIMITS@@ -194,6 +199,13 @@ class Settings(BaseSettings):def parse_user_cost_limits(cls, v: str | dict | None) -> dict[str, UserCostLimit]:return _parse_model_dict(v, UserCostLimit, DEFAULT_USER_COST_LIMITS, "user_cost_limits")+ @field_validator("staff_rate_limit_multiplier")+ @classmethod+ def validate_staff_rate_limit_multiplier(cls, v: int) -> int:+ if v < 1:+ raise ValueError(f"staff_rate_limit_multiplier must be >= 1, got {v}")+ return v+@field_validator("team_rate_limit_multipliers", mode="before")@classmethoddef parse_team_multipliers(cls, v: str | dict[int, int] | None) -> dict[int, int]:diff --git a/services/llm-gateway/src/llm_gateway/metrics/prometheus.py b/services/llm-gateway/src/llm_gateway/metrics/prometheus.pyindex e42629ca9e92..9afe3830615a 100644--- a/services/llm-gateway/src/llm_gateway/metrics/prometheus.py+++ b/services/llm-gateway/src/llm_gateway/metrics/prometheus.py@@ -106,8 +106,8 @@ PRODUCT_COST_WINDOW_USD = Gauge("llm_gateway_product_cost_window_usd",("Current accumulated cost (USD) for a product within its configured window. "- "Reflects only the shared pool — spend from teams with a team_rate_limit_multipliers "- "override lives in a separate per-multiplier Redis bucket and is not included here."+ "Reflects only the shared pool — spend from teams or staff with a rate-limit "+ "multiplier lives in a separate per-multiplier Redis bucket and is not included here."),labelnames=["product"],)@@ -116,8 +116,8 @@ PRODUCT_COST_LIMIT_USD = Gauge("llm_gateway_product_cost_limit_usd",("Configured cost cap (USD) for a product within its configured window. "- "This is the base (team_mult=1) cap that pairs with llm_gateway_product_cost_window_usd; "- "teams with a team_rate_limit_multipliers override get a multiplied cap not reflected here."+ "This is the base (multiplier=1) cap that pairs with llm_gateway_product_cost_window_usd; "+ "teams or staff with a rate-limit multiplier get a multiplied cap not reflected here."),labelnames=["product"],)diff --git a/services/llm-gateway/src/llm_gateway/rate_limiting/cost_throttles.py b/services/llm-gateway/src/llm_gateway/rate_limiting/cost_throttles.pyindex 412ab587dae8..6657d835b435 100644--- a/services/llm-gateway/src/llm_gateway/rate_limiting/cost_throttles.py+++ b/services/llm-gateway/src/llm_gateway/rate_limiting/cost_throttles.py@@ -16,7 +16,7 @@ from llm_gateway.config import (if TYPE_CHECKING:from llm_gateway.config import UserCostLimitfrom llm_gateway.rate_limiting.redis_limiter import CostRateLimiter-from llm_gateway.rate_limiting.throttles import Throttle, ThrottleContext, ThrottleResult, get_team_multiplier+from llm_gateway.rate_limiting.throttles import Throttle, ThrottleContext, ThrottleResult, get_rate_limit_multiplierfrom llm_gateway.services.plan_resolver import POSTHOG_CODE_PRODUCT, get_billing_period_number, is_pro_planlogger = structlog.get_logger(__name__)@@ -46,8 +46,8 @@ class CostThrottle(Throttle):self._redis = redisself._limiters: dict[str, CostRateLimiter] = {}- def _get_team_multiplier(self, context: ThrottleContext) -> int:- return get_team_multiplier(context.user.team_id)+ def _get_multiplier(self, context: ThrottleContext) -> int:+ return get_rate_limit_multiplier(context.user)@abstractmethoddef _get_cache_key(self, context: ThrottleContext) -> str: ...@@ -165,11 +165,11 @@ class ProductCostThrottle(CostThrottle):return "Product rate limit exceeded"def _get_cache_key(self, context: ThrottleContext) -> str:- team_mult = self._get_team_multiplier(context)+ mult = self._get_multiplier(context)base = f"cost:product:{context.product}"- if team_mult == 1:+ if mult == 1:return base- return f"{base}:tm{team_mult}"+ return f"{base}:m{mult}"def _get_limit_and_window(self, context: ThrottleContext) -> tuple[float, int]:settings = get_settings()@@ -180,14 +180,14 @@ class ProductCostThrottle(CostThrottle):else:base_limit = 1000.0window = 86400- team_mult = self._get_team_multiplier(context)- return base_limit * team_mult, window+ mult = self._get_multiplier(context)+ return base_limit * mult, windowasync def get_status_for_product(self, product: str) -> CostStatus | None:- """Return CostStatus for a product using the shared (team multiplier = 1) pool.+ """Return CostStatus for a product using the shared (multiplier = 1) pool.Intended for monitoring/gauges, not throttling decisions — throttling needs- a full ThrottleContext to apply team multipliers. Returns None when the+ a full ThrottleContext to apply the rate-limit multiplier. Returns None when theproduct has no configured cost limit."""settings = get_settings()@@ -232,11 +232,11 @@ class _UserCostThrottleBase(CostThrottle):def _get_cache_key(self, context: ThrottleContext) -> str:if not context.end_user_id:return ""- team_mult = self._get_team_multiplier(context)+ mult = self._get_multiplier(context)base = f"cost:user:{self.scope}:{context.product}:{context.end_user_id}"- if team_mult == 1:+ if mult == 1:return base- return f"{base}:tm{team_mult}"+ return f"{base}:m{mult}"def _get_config(self, context: ThrottleContext) -> UserCostLimit:if _is_free_plan_throttled(context):@@ -277,8 +277,8 @@ class UserCostBurstThrottle(_UserCostThrottleBase):def _get_limit_and_window(self, context: ThrottleContext) -> tuple[float, int]:config = self._get_config(context)- team_mult = self._get_team_multiplier(context)- return config.burst_limit_usd * team_mult, config.burst_window_seconds+ mult = self._get_multiplier(context)+ return config.burst_limit_usd * mult, config.burst_window_secondsclass UserCostSustainedThrottle(_UserCostThrottleBase):@@ -302,5 +302,5 @@ class UserCostSustainedThrottle(_UserCostThrottleBase):def _get_limit_and_window(self, context: ThrottleContext) -> tuple[float, int]:config = self._get_config(context)- team_mult = self._get_team_multiplier(context)- return config.sustained_limit_usd * team_mult, config.sustained_window_seconds+ mult = self._get_multiplier(context)+ return config.sustained_limit_usd * mult, config.sustained_window_secondsdiff --git a/services/llm-gateway/src/llm_gateway/rate_limiting/throttles.py b/services/llm-gateway/src/llm_gateway/rate_limiting/throttles.pyindex 9f47757b1d89..8d88b6b08ca2 100644--- a/services/llm-gateway/src/llm_gateway/rate_limiting/throttles.py+++ b/services/llm-gateway/src/llm_gateway/rate_limiting/throttles.py@@ -14,6 +14,23 @@ def get_team_multiplier(team_id: int | None) -> int:return get_settings().team_rate_limit_multipliers.get(team_id, 1)+def get_staff_multiplier(user: AuthenticatedUser) -> int:+ """Elevated rate/cost cap for PostHog staff, applied regardless of which+ team they're acting on — so impersonating a customer doesn't drop the cap.+ Non-staff users get the unmodified base limit (1×)."""+ if not user.is_staff:+ return 1++ return get_settings().staff_rate_limit_multiplier+++def get_rate_limit_multiplier(user: AuthenticatedUser) -> int:+ """Effective multiplier: the larger of the user's team multiplier and the+ staff multiplier, so staff keep an elevated cap on any team while configured+ teams keep theirs."""+ return max(get_team_multiplier(user.team_id), get_staff_multiplier(user))++@dataclassclass ThrottleContext:user: AuthenticatedUserdiff --git a/services/llm-gateway/tests/conftest.py b/services/llm-gateway/tests/conftest.pyindex 6456b87e1c70..6c4538b75055 100644--- a/services/llm-gateway/tests/conftest.py+++ b/services/llm-gateway/tests/conftest.py@@ -114,6 +114,7 @@ def authenticated_client(mock_db_pool: MagicMock) -> Generator[TestClient]:"scopes": ["llm_gateway:read"],"current_team_id": 1,"distinct_id": "test-distinct-id",+ "is_staff": False,})mock_db_pool.acquire = AsyncMock(return_value=conn)diff --git a/services/llm-gateway/tests/integration/conftest.py b/services/llm-gateway/tests/integration/conftest.pyindex b8b36968ea97..b4548529cf09 100644--- a/services/llm-gateway/tests/integration/conftest.py+++ b/services/llm-gateway/tests/integration/conftest.py@@ -100,6 +100,7 @@ def create_mock_db_pool():"current_team_id": 456,"scopes": ["llm_gateway:read"],"distinct_id": "test-distinct-id",+ "is_staff": False,})pool.acquire = AsyncMock(return_value=conn)diff --git a/services/llm-gateway/tests/test_auth.py b/services/llm-gateway/tests/test_auth.pyindex ddae514c5594..c68827fe1340 100644--- a/services/llm-gateway/tests/test_auth.py+++ b/services/llm-gateway/tests/test_auth.py@@ -106,6 +106,7 @@ class TestAuthService:"current_team_id": 456,"application_id": 789,"distinct_id": "test-distinct-id",+ "is_staff": False,})@@ -131,6 +132,7 @@ class TestAuthService:"scopes": ["llm_gateway:read"],"current_team_id": 101,"distinct_id": "test-distinct-id",+ "is_staff": False,})@@ -206,6 +208,7 @@ class TestPersonalApiKeyAuthenticator:"scopes": ["llm_gateway:read"],"current_team_id": 456,"distinct_id": "test-distinct-id",+ "is_staff": False,})@@ -216,6 +219,7 @@ class TestPersonalApiKeyAuthenticator:assert result.user_id == 123assert result.team_id == 456assert result.auth_method == "personal_api_key"+ assert result.is_staff is False@pytest.mark.asyncio@pytest.mark.parametrize(@@ -307,6 +311,7 @@ class TestOAuthAccessTokenAuthenticator:"current_team_id": 456,"application_id": 789,"distinct_id": "test-distinct-id",+ "is_staff": False,})@@ -392,6 +397,7 @@ class TestOAuthAccessTokenAuthenticator:"current_team_id": 456,"application_id": 789,"distinct_id": "test-distinct-id",+ "is_staff": False,})@@ -415,6 +421,7 @@ class TestOAuthAccessTokenAuthenticator:"current_team_id": 456,"application_id": 789,"distinct_id": "test-distinct-id",+ "is_staff": True,})@@ -426,6 +433,7 @@ class TestOAuthAccessTokenAuthenticator:assert result.team_id == 456assert result.auth_method == "oauth_access_token"assert result.scopes == ["llm_gateway:read"]+ assert result.is_staff is True@pytest.mark.asyncioasync def test_valid_token_with_null_team_id(@@ -441,6 +449,7 @@ class TestOAuthAccessTokenAuthenticator:"current_team_id": None,"application_id": 789,"distinct_id": "test-distinct-id",+ "is_staff": False,})diff --git a/services/llm-gateway/tests/test_auth_cache.py b/services/llm-gateway/tests/test_auth_cache.pyindex c8139acdefd7..288fe13eba51 100644--- a/services/llm-gateway/tests/test_auth_cache.py+++ b/services/llm-gateway/tests/test_auth_cache.py@@ -238,6 +238,7 @@ class TestAuthServiceCaching:"scopes": ["llm_gateway:read"],"current_team_id": 456,"distinct_id": "test-distinct-id",+ "is_staff": False,})@@ -277,6 +278,7 @@ class TestAuthServiceCaching:"current_team_id": 456,"application_id": 789,"distinct_id": "test-distinct-id",+ "is_staff": False,})@@ -316,6 +318,7 @@ class TestAuthServiceCaching:"current_team_id": 456,"application_id": 789,"distinct_id": "test-distinct-id",+ "is_staff": False,})@@ -373,6 +376,7 @@ class TestAuthServiceMetrics:"application_id": 789,"expires": datetime.now(UTC) + timedelta(hours=1),"distinct_id": "test-distinct-id",+ "is_staff": False,})@@ -403,6 +407,7 @@ class TestAuthServiceMetrics:"application_id": 789,"expires": datetime.now(UTC) + timedelta(hours=1),"distinct_id": "test-distinct-id",+ "is_staff": False,})diff --git a/services/llm-gateway/tests/test_cost_throttles.py b/services/llm-gateway/tests/test_cost_throttles.pyindex 2d7557460984..08cdd05350d0 100644--- a/services/llm-gateway/tests/test_cost_throttles.py+++ b/services/llm-gateway/tests/test_cost_throttles.py@@ -5,13 +5,16 @@ from llm_gateway.config import get_settingsfrom llm_gateway.rate_limiting.throttles import ThrottleContext-def make_user(user_id: int = 1, team_id: int = 1, auth_method: str = "oauth_access_token") -> AuthenticatedUser:+def make_user(+ user_id: int = 1, team_id: int = 1, auth_method: str = "oauth_access_token", is_staff: bool = False+) -> AuthenticatedUser:return AuthenticatedUser(user_id=user_id,team_id=team_id,auth_method=auth_method,distinct_id=f"test-distinct-id-{user_id}",scopes=["llm_gateway:read"],+ is_staff=is_staff,)@@ -192,24 +195,26 @@ class TestProductCostThrottle:assert await throttle.get_status_for_product("not_a_real_product") is None@pytest.mark.asyncio- async def test_get_status_for_product_ignores_team_multiplier_suffix(self, monkeypatch: pytest.MonkeyPatch) -> None:- """Gauge readings track only the shared (team_mult=1) pool — spend from teams with a- rate-limit multiplier lands in a suffixed Redis bucket and is intentionally invisible- to the gauge, so alerts don't double-count multiplier teams against the shared cap."""- monkeypatch.setenv("LLM_GATEWAY_TEAM_RATE_LIMIT_MULTIPLIERS", '{"2": 10}')+ async def test_get_status_for_product_ignores_staff_multiplier_suffix(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ """Gauge readings track only the shared (multiplier=1) pool — staff spend lands in a+ suffixed Redis bucket and is intentionally invisible to the gauge, so alerts don't+ double-count staff against the shared cap."""+ monkeypatch.setenv("LLM_GATEWAY_STAFF_RATE_LIMIT_MULTIPLIER", "10")get_settings.cache_clear()from llm_gateway.rate_limiting.cost_throttles import ProductCostThrottlethrottle = ProductCostThrottle(redis=None)- multiplier_context = make_context(user=make_user(user_id=1, team_id=2), product="llm_gateway")- await throttle.record_cost(multiplier_context, 50.0)+ staff_context = make_context(user=make_user(user_id=1, is_staff=True), product="llm_gateway")+ await throttle.record_cost(staff_context, 50.0)status = await throttle.get_status_for_product("llm_gateway")assert status is not None- assert status.used_usd == pytest.approx(0.0), "multiplier-team spend must not appear in the shared-pool gauge"+ assert status.used_usd == pytest.approx(0.0), "staff spend must not appear in the shared-pool gauge"- shared_context = make_context(user=make_user(user_id=2, team_id=1), product="llm_gateway")+ shared_context = make_context(user=make_user(user_id=2, is_staff=False), product="llm_gateway")await throttle.record_cost(shared_context, 7.0)status = await throttle.get_status_for_product("llm_gateway")@@ -707,44 +712,60 @@ class TestCostRateLimiterRedisIntegration:assert result.allowed is True-class TestTeamRateLimitMultipliers:+class TestRateLimitMultiplier:@pytest.mark.asyncio- async def test_cache_key_has_no_suffix_for_default_multiplier(self, monkeypatch: pytest.MonkeyPatch) -> None:+ async def test_cache_key_has_no_suffix_for_plain_user(self, monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setenv("LLM_GATEWAY_TEAM_RATE_LIMIT_MULTIPLIERS", "{}")+ monkeypatch.setenv("LLM_GATEWAY_STAFF_RATE_LIMIT_MULTIPLIER", "10")get_settings.cache_clear()from llm_gateway.rate_limiting.cost_throttles import UserCostBurstThrottlethrottle = UserCostBurstThrottle(redis=None)- user = make_user(user_id=1, team_id=99)+ user = make_user(user_id=1, team_id=99, is_staff=False)context = make_context(user=user, product="posthog_code")key = throttle._get_cache_key(context)- assert ":tm" not in key+ assert ":m" not in keyassert key == "cost:user:user_cost_burst:posthog_code:1"get_settings.cache_clear()@pytest.mark.asyncio- async def test_cache_key_includes_multiplier_suffix(self, monkeypatch: pytest.MonkeyPatch) -> None:+ async def test_cache_key_suffix_from_team_multiplier(self, monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setenv("LLM_GATEWAY_TEAM_RATE_LIMIT_MULTIPLIERS", '{"2": 10}')get_settings.cache_clear()from llm_gateway.rate_limiting.cost_throttles import UserCostBurstThrottlethrottle = UserCostBurstThrottle(redis=None)- user = make_user(user_id=1, team_id=2)+ user = make_user(user_id=1, team_id=2, is_staff=False)+ context = make_context(user=user, product="posthog_code")++ key = throttle._get_cache_key(context)+ assert key == "cost:user:user_cost_burst:posthog_code:1:m10"+ get_settings.cache_clear()++ @pytest.mark.asyncio+ async def test_cache_key_suffix_from_staff_multiplier(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("LLM_GATEWAY_STAFF_RATE_LIMIT_MULTIPLIER", "10")+ get_settings.cache_clear()+ from llm_gateway.rate_limiting.cost_throttles import UserCostBurstThrottle++ throttle = UserCostBurstThrottle(redis=None)+ # Staff on an unconfigured team still gets the suffixed bucket.+ user = make_user(user_id=1, team_id=99, is_staff=True)context = make_context(user=user, product="posthog_code")key = throttle._get_cache_key(context)- assert key == "cost:user:user_cost_burst:posthog_code:1:tm10"+ assert key == "cost:user:user_cost_burst:posthog_code:1:m10"get_settings.cache_clear()@pytest.mark.asyncio- async def test_team_with_multiplier_gets_higher_limit(self, monkeypatch: pytest.MonkeyPatch) -> None:+ async def test_team_gets_higher_limit(self, monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setenv("LLM_GATEWAY_TEAM_RATE_LIMIT_MULTIPLIERS", '{"2": 10}')get_settings.cache_clear()from llm_gateway.rate_limiting.cost_throttles import UserCostBurstThrottlethrottle = UserCostBurstThrottle(redis=None)- user = make_user(user_id=1, team_id=2)+ user = make_user(user_id=1, team_id=2, is_staff=False)context = make_context(user=user, product="posthog_code")await throttle.record_cost(context, 100.0)@@ -753,18 +774,50 @@ class TestTeamRateLimitMultipliers:get_settings.cache_clear()@pytest.mark.asyncio- async def test_product_cache_key_includes_multiplier_suffix(self, monkeypatch: pytest.MonkeyPatch) -> None:+ async def test_staff_gets_higher_limit_on_any_team(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("LLM_GATEWAY_STAFF_RATE_LIMIT_MULTIPLIER", "10")+ get_settings.cache_clear()+ from llm_gateway.rate_limiting.cost_throttles import UserCostBurstThrottle++ throttle = UserCostBurstThrottle(redis=None)+ # Staff on an arbitrary team — the impersonation case — still gets the elevated cap.+ user = make_user(user_id=1, team_id=99, is_staff=True)+ context = make_context(user=user, product="posthog_code")++ await throttle.record_cost(context, 100.0)+ result = await throttle.allow_request(context)+ assert result.allowed is True, "Should allow - staff has 10x multiplier ($2000 limit vs $100 used)"+ get_settings.cache_clear()++ @pytest.mark.asyncio+ async def test_effective_multiplier_is_max_of_team_and_staff(self, monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setenv("LLM_GATEWAY_TEAM_RATE_LIMIT_MULTIPLIERS", '{"2": 10}')+ monkeypatch.setenv("LLM_GATEWAY_STAFF_RATE_LIMIT_MULTIPLIER", "3")+ get_settings.cache_clear()+ from llm_gateway.rate_limiting.cost_throttles import UserCostBurstThrottle++ throttle = UserCostBurstThrottle(redis=None)+ # Staff on a configured team gets the larger of the two multipliers (10, not 3).+ user = make_user(user_id=1, team_id=2, is_staff=True)+ context = make_context(user=user, product="posthog_code")++ key = throttle._get_cache_key(context)+ assert key == "cost:user:user_cost_burst:posthog_code:1:m10"+ get_settings.cache_clear()++ @pytest.mark.asyncio+ async def test_product_cache_key_includes_multiplier_suffix(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("LLM_GATEWAY_STAFF_RATE_LIMIT_MULTIPLIER", "10")get_settings.cache_clear()from llm_gateway.rate_limiting.cost_throttles import ProductCostThrottlethrottle = ProductCostThrottle(redis=None)- user = make_user(user_id=1, team_id=2)+ user = make_user(user_id=1, is_staff=True)context = make_context(user=user, product="wizard")key = throttle._get_cache_key(context)- assert key == "cost:product:wizard:tm10"+ assert key == "cost:product:wizard:m10"get_settings.cache_clear()diff --git a/services/llm-gateway/tests/test_openai.py b/services/llm-gateway/tests/test_openai.pyindex 17a81d86f3bc..38c7917afeff 100644--- a/services/llm-gateway/tests/test_openai.py+++ b/services/llm-gateway/tests/test_openai.py@@ -111,6 +111,7 @@ class TestChatCompletionsEndpoint:"scopes": ["llm_gateway:read"],"current_team_id": 1,"distinct_id": "test-distinct-id",+ "is_staff": False,})mock_db_pool.acquire = AsyncMock(return_value=conn)diff --git a/services/llm-gateway/tests/test_rate_limiting.py b/services/llm-gateway/tests/test_rate_limiting.pyindex 375574a13057..35a2dfb33a89 100644--- a/services/llm-gateway/tests/test_rate_limiting.py+++ b/services/llm-gateway/tests/test_rate_limiting.py@@ -230,6 +230,7 @@ class TestRateLimitResponseHeaders:"scopes": ["llm_gateway:read"],"current_team_id": 1,"distinct_id": "test-distinct-id",+ "is_staff": False,})mock_db_pool.acquire = AsyncMock(return_value=conn)diff --git a/services/llm-gateway/tests/test_throttles.py b/services/llm-gateway/tests/test_throttles.pyindex e7671cd75af3..7d2a84ee20d3 100644--- a/services/llm-gateway/tests/test_throttles.py+++ b/services/llm-gateway/tests/test_throttles.py@@ -14,6 +14,8 @@ from llm_gateway.rate_limiting.throttles import (Throttle,ThrottleContext,ThrottleResult,+ get_rate_limit_multiplier,+ get_staff_multiplier,get_team_multiplier,)@@ -24,6 +26,7 @@ def make_user(auth_method: str = "personal_api_key",scopes: list[str] | None = None,application_id: str | None = None,+ is_staff: bool = False,) -> AuthenticatedUser:return AuthenticatedUser(user_id=user_id,@@ -32,6 +35,7 @@ def make_user(distinct_id=f"test-distinct-id-{user_id}",scopes=scopes or ["llm_gateway:read"],application_id=application_id,+ is_staff=is_staff,)@@ -185,3 +189,49 @@ class TestGetTeamMultiplier:assert get_team_multiplier(2) == 10assert get_team_multiplier(5) == 5get_settings.cache_clear()+++class TestGetStaffMultiplier:+ def test_returns_1_for_non_staff_user(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("LLM_GATEWAY_STAFF_RATE_LIMIT_MULTIPLIER", "10")+ get_settings.cache_clear()+ assert get_staff_multiplier(make_user(is_staff=False)) == 1+ get_settings.cache_clear()++ def test_returns_configured_multiplier_for_staff_user(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("LLM_GATEWAY_STAFF_RATE_LIMIT_MULTIPLIER", "10")+ get_settings.cache_clear()+ assert get_staff_multiplier(make_user(is_staff=True)) == 10+ get_settings.cache_clear()++ def test_staff_multiplier_independent_of_team_id(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("LLM_GATEWAY_STAFF_RATE_LIMIT_MULTIPLIER", "7")+ get_settings.cache_clear()+ # Staff keep the elevated cap on any team — the impersonation case.+ assert get_staff_multiplier(make_user(team_id=99, is_staff=True)) == 7+ assert get_staff_multiplier(make_user(team_id=99, is_staff=False)) == 1+ get_settings.cache_clear()+++class TestGetRateLimitMultiplier:+ def test_takes_team_multiplier_when_higher(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("LLM_GATEWAY_TEAM_RATE_LIMIT_MULTIPLIERS", '{"2": 10}')+ monkeypatch.setenv("LLM_GATEWAY_STAFF_RATE_LIMIT_MULTIPLIER", "3")+ get_settings.cache_clear()+ assert get_rate_limit_multiplier(make_user(team_id=2, is_staff=True)) == 10+ get_settings.cache_clear()++ def test_takes_staff_multiplier_when_higher(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("LLM_GATEWAY_TEAM_RATE_LIMIT_MULTIPLIERS", '{"2": 3}')+ monkeypatch.setenv("LLM_GATEWAY_STAFF_RATE_LIMIT_MULTIPLIER", "10")+ get_settings.cache_clear()+ # Staff on an unconfigured team still gets the staff cap.+ assert get_rate_limit_multiplier(make_user(team_id=99, is_staff=True)) == 10+ get_settings.cache_clear()++ def test_defaults_to_1_for_plain_user(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("LLM_GATEWAY_TEAM_RATE_LIMIT_MULTIPLIERS", "{}")+ monkeypatch.setenv("LLM_GATEWAY_STAFF_RATE_LIMIT_MULTIPLIER", "10")+ get_settings.cache_clear()+ assert get_rate_limit_multiplier(make_user(team_id=99, is_staff=False)) == 1+ get_settings.cache_clear()diff --git a/services/llm-gateway/tests/test_usage.py b/services/llm-gateway/tests/test_usage.pyindex 3b75ada2366a..9f534125067d 100644--- a/services/llm-gateway/tests/test_usage.py+++ b/services/llm-gateway/tests/test_usage.py@@ -68,6 +68,7 @@ class TestUsageEndpoint:"scopes": ["llm_gateway:read"],"current_team_id": 1,"distinct_id": "test-distinct-id",+ "is_staff": False,})mock_db_pool.acquire = AsyncMock(return_value=conn)