: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): scope Code limits to organizations (#77438)
Adam Bowkera81391763262
diff --git a/services/llm-gateway/src/llm_gateway/config.py b/services/llm-gateway/src/llm_gateway/config.pyindex 843d99fe7bd3..e6b174bc9bcc 100644--- a/services/llm-gateway/src/llm_gateway/config.py+++ b/services/llm-gateway/src/llm_gateway/config.py@@ -49,12 +49,6 @@ DEFAULT_USER_COST_LIMITS: dict[str, "UserCostLimit"] = {sustained_limit_usd=100.0,sustained_window_seconds=2592000, # 30 days),- "posthog_code": UserCostLimit(- burst_limit_usd=500.0,- burst_window_seconds=86400,- sustained_limit_usd=3000.0,- sustained_window_seconds=2592000,- ),"background_agents": UserCostLimit(burst_limit_usd=500.0,burst_window_seconds=604800,@@ -82,21 +76,6 @@ DEFAULT_USER_COST_LIMITS: dict[str, "UserCostLimit"] = {),}-FREE_PLAN_COST_LIMIT = UserCostLimit(- burst_limit_usd=20.0,- burst_window_seconds=86400,- sustained_limit_usd=20.0,- sustained_window_seconds=2592000,-)--ORG_BILLED_USER_COST_LIMIT = UserCostLimit(- burst_limit_usd=float("inf"),- burst_window_seconds=86400,- sustained_limit_usd=float("inf"),- sustained_window_seconds=2592000,-)--_COST_LIMIT_KEY_ALIASES: dict[str, str] = {"array": "posthog_code","twig": "posthog_code",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 593dd6ce604c..0ac849400ce8 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@@ -7,12 +7,7 @@ from typing import TYPE_CHECKINGimport structlogfrom redis.asyncio import Redis-from llm_gateway.config import (- DEFAULT_USER_COST_LIMIT,- FREE_PLAN_COST_LIMIT,- ORG_BILLED_USER_COST_LIMIT,- get_settings,-)+from llm_gateway.config import DEFAULT_USER_COST_LIMIT, get_settingsif TYPE_CHECKING:from llm_gateway.config import UserCostLimit@@ -24,7 +19,7 @@ from llm_gateway.rate_limiting.throttles import (get_rate_limit_multiplier,is_usage_unlimited,)-from llm_gateway.services.plan_resolver import POSTHOG_CODE_PRODUCT, get_billing_period_number, is_pro_plan+from llm_gateway.services.plan_resolver import POSTHOG_CODE_PRODUCTlogger = structlog.get_logger(__name__)@@ -38,18 +33,6 @@ class CostStatus:exceeded: bool-def _is_free_plan_throttled(context: ThrottleContext) -> bool:- return (- context.product == POSTHOG_CODE_PRODUCT- and not is_pro_plan(context.plan_key)- and (context.seat_created_at is not None or context.seat_missing)- )---def _is_org_billed_seatless(context: ThrottleContext) -> bool:- return context.product == POSTHOG_CODE_PRODUCT and context.seat_missing and context.code_usage_billed--class CostThrottle(Throttle):scope: str@@ -250,13 +233,6 @@ class _UserCostThrottleBase(CostThrottle):return f"{base}:m{mult}"def _get_config(self, context: ThrottleContext) -> UserCostLimit:- # Precedence matters: an org-billed seatless user is uncapped even though- # seat_missing would otherwise select the free-plan cap below.- if _is_org_billed_seatless(context):- return ORG_BILLED_USER_COST_LIMIT- if _is_free_plan_throttled(context):- return FREE_PLAN_COST_LIMIT-config = get_settings().user_cost_limits.get(context.product)if not config:if context.end_user_id and context.product not in self._warned_products:@@ -270,7 +246,7 @@ class _UserCostThrottleBase(CostThrottle):return configasync def allow_request(self, context: ThrottleContext) -> ThrottleResult:- if not context.end_user_id:+ if not context.end_user_id or context.product == POSTHOG_CODE_PRODUCT:return ThrottleResult.allow()if is_usage_unlimited(context.user):return ThrottleResult.allow()@@ -281,7 +257,7 @@ class _UserCostThrottleBase(CostThrottle):return await super().allow_request(context)async def get_status(self, context: ThrottleContext) -> CostStatus:- if is_usage_unlimited(context.user):+ if context.product == POSTHOG_CODE_PRODUCT or is_usage_unlimited(context.user):# Staff have no per-user cap: report an effectively unlimited budget# so the usage endpoint computes 0% used and never flags the user as# rate limited. `float("inf")` never crosses the wire — only@@ -297,7 +273,7 @@ class _UserCostThrottleBase(CostThrottle):return await super().get_status(context)async def record_cost(self, context: ThrottleContext, cost: float) -> None:- if not context.end_user_id:+ if not context.end_user_id or context.product == POSTHOG_CODE_PRODUCT:returnawait super().record_cost(context, cost)@@ -320,19 +296,6 @@ class UserCostSustainedThrottle(_UserCostThrottleBase):def _get_limit_exceeded_detail(self) -> str:return "User sustained rate limit exceeded"- def _get_cache_key(self, context: ThrottleContext) -> str:- base_key = super()._get_cache_key(context)- if not base_key:- return base_key- if context.product == POSTHOG_CODE_PRODUCT:- period = get_billing_period_number(- context.seat_created_at,- get_settings().billing_period_days,- billing_period_start=context.billing_period_start,- )- return f"{base_key}:period:{period}"- return base_key-def _get_limit_and_window(self, context: ThrottleContext) -> tuple[float, int]:config = self._get_config(context)mult = self._get_multiplier(context)diff --git a/services/llm-gateway/tests/test_cost_throttles.py b/services/llm-gateway/tests/test_cost_throttles.pyindex 6e089aeab5a3..de09adc1d12b 100644--- a/services/llm-gateway/tests/test_cost_throttles.py+++ b/services/llm-gateway/tests/test_cost_throttles.py@@ -2,7 +2,12 @@ import pytestfrom llm_gateway.auth.models import AuthenticatedUserfrom llm_gateway.config import get_settings-from llm_gateway.rate_limiting.cost_throttles import CostThrottle+from llm_gateway.rate_limiting.cost_throttles import (+ CostThrottle,+ UserCostBurstThrottle,+ UserCostSustainedThrottle,+ _UserCostThrottleBase,+)from llm_gateway.rate_limiting.throttles import ThrottleContext@@ -91,12 +96,8 @@ class TestUserCostLimitConfig:def test_default_user_cost_limits(self) -> None:get_settings.cache_clear()settings = get_settings()- assert "posthog_code" in settings.user_cost_limits- posthog_code = settings.user_cost_limits["posthog_code"]- assert posthog_code.burst_limit_usd == 500.0- assert posthog_code.burst_window_seconds == 86400- assert posthog_code.sustained_limit_usd == 3000.0- assert posthog_code.sustained_window_seconds == 2592000+ assert "posthog_code" not in settings.user_cost_limits+ assert "background_agents" in settings.user_cost_limitsget_settings.cache_clear()def test_parses_json_string(self, monkeypatch: pytest.MonkeyPatch) -> None:@@ -114,7 +115,7 @@ class TestUserCostLimitConfig:def test_unset_env_returns_defaults(self) -> None:get_settings.cache_clear()settings = get_settings()- assert "posthog_code" in settings.user_cost_limits+ assert "posthog_code" not in settings.user_cost_limitsget_settings.cache_clear()def test_legacy_twig_key_normalizes_to_posthog_code(self, monkeypatch: pytest.MonkeyPatch) -> None:@@ -244,7 +245,7 @@ class TestUserCostBurstThrottle:from llm_gateway.rate_limiting.cost_throttles import UserCostBurstThrottlethrottle = UserCostBurstThrottle(redis=None)- context = make_context(product="posthog_code")+ context = make_context(product="background_agents")result = await throttle.allow_request(context)assert result.allowed is True@@ -256,7 +257,7 @@ class TestUserCostBurstThrottle:from llm_gateway.rate_limiting.cost_throttles import UserCostBurstThrottlethrottle = UserCostBurstThrottle(redis=None)- context = make_context(product="posthog_code")+ context = make_context(product="background_agents")await throttle.record_cost(context, 500.0)@@ -290,7 +291,7 @@ class TestUserCostBurstThrottle:throttle = UserCostBurstThrottle(redis=None)user = make_user(user_id=1, auth_method="personal_api_key")- context = make_context(user=user, product="posthog_code", end_user_id=None)+ context = make_context(user=user, product="background_agents", end_user_id=None)await throttle.record_cost(context, 99999.0)result = await throttle.allow_request(context)@@ -316,8 +317,8 @@ class TestUserCostBurstThrottle:user1 = make_user(user_id=1)user2 = make_user(user_id=2)- ctx1 = make_context(user=user1, product="posthog_code")- ctx2 = make_context(user=user2, product="posthog_code")+ ctx1 = make_context(user=user1, product="background_agents")+ ctx2 = make_context(user=user2, product="background_agents")await throttle.record_cost(ctx1, 500.0)@@ -333,7 +334,7 @@ class TestUserCostSustainedThrottle:from llm_gateway.rate_limiting.cost_throttles import UserCostSustainedThrottlethrottle = UserCostSustainedThrottle(redis=None)- context = make_context(product="posthog_code")+ context = make_context(product="background_agents")result = await throttle.allow_request(context)assert result.allowed is True@@ -345,7 +346,7 @@ class TestUserCostSustainedThrottle:from llm_gateway.rate_limiting.cost_throttles import UserCostSustainedThrottlethrottle = UserCostSustainedThrottle(redis=None)- context = make_context(product="posthog_code")+ context = make_context(product="background_agents")await throttle.record_cost(context, 3000.0)@@ -372,107 +373,6 @@ class TestUserCostSustainedThrottle:assert result.allowed is Falseget_settings.cache_clear()- @pytest.mark.asyncio- async def test_cache_key_includes_product_scope_and_period(self) -> None:- from llm_gateway.rate_limiting.cost_throttles import UserCostSustainedThrottle-- throttle = UserCostSustainedThrottle(redis=None)- context = make_context(product="posthog_code", end_user_id="42")-- key = throttle._get_cache_key(context)- assert key == "cost:user:user_cost_sustained:posthog_code:42:period:0"-- @pytest.mark.asyncio- async def test_cache_key_includes_period_for_free_plan(self) -> None:- from datetime import UTC, datetime, timedelta-- from llm_gateway.rate_limiting.cost_throttles import UserCostSustainedThrottle-- throttle = UserCostSustainedThrottle(redis=None)- created = (datetime.now(tz=UTC) - timedelta(days=5)).isoformat()- context = make_context(- product="posthog_code",- end_user_id="42",- plan_key="posthog-code-free-20260301",- seat_created_at=created,- )-- key = throttle._get_cache_key(context)- assert key == "cost:user:user_cost_sustained:posthog_code:42:period:0"-- @pytest.mark.asyncio- async def test_cache_key_period_increments_after_period_days(self) -> None:- from datetime import UTC, datetime, timedelta-- from llm_gateway.rate_limiting.cost_throttles import UserCostSustainedThrottle-- throttle = UserCostSustainedThrottle(redis=None)- created = (datetime.now(tz=UTC) - timedelta(days=35)).isoformat()- context = make_context(- product="posthog_code",- end_user_id="42",- plan_key="posthog-code-free-20260301",- seat_created_at=created,- )-- key = throttle._get_cache_key(context)- assert key == "cost:user:user_cost_sustained:posthog_code:42:period:1"-- def test_cache_key_uses_billing_period_start_over_seat_created_at(self) -> None:- from datetime import UTC, datetime, timedelta-- from llm_gateway.rate_limiting.cost_throttles import UserCostSustainedThrottle-- throttle = UserCostSustainedThrottle(redis=None)- old_seat = (datetime.now(tz=UTC) - timedelta(days=35)).isoformat()- recent_period = (datetime.now(tz=UTC) - timedelta(days=5)).isoformat()- context = make_context(- product="posthog_code",- end_user_id="42",- plan_key="posthog-code-pro-200-20260301",- seat_created_at=old_seat,- billing_period_start=recent_period,- )-- key = throttle._get_cache_key(context)- assert key == "cost:user:user_cost_sustained:posthog_code:42:period:0"-- def test_cache_key_falls_back_to_seat_created_at_without_billing_period(self) -> None:- from datetime import UTC, datetime, timedelta-- from llm_gateway.rate_limiting.cost_throttles import UserCostSustainedThrottle-- throttle = UserCostSustainedThrottle(redis=None)- old_seat = (datetime.now(tz=UTC) - timedelta(days=35)).isoformat()- context = make_context(- product="posthog_code",- end_user_id="42",- plan_key="posthog-code-pro-200-20260301",- seat_created_at=old_seat,- billing_period_start=None,- )-- key = throttle._get_cache_key(context)- assert key == "cost:user:user_cost_sustained:posthog_code:42:period:1"-- @pytest.mark.asyncio- async def test_cache_key_includes_period_for_pro_plan(self) -> None:- from datetime import UTC, datetime, timedelta-- from llm_gateway.rate_limiting.cost_throttles import UserCostSustainedThrottle-- throttle = UserCostSustainedThrottle(redis=None)- created = (datetime.now(tz=UTC) - timedelta(days=5)).isoformat()- context = make_context(- product="posthog_code",- end_user_id="42",- plan_key="posthog-code-200-20260301",- seat_created_at=created,- )-- key = throttle._get_cache_key(context)- assert key == "cost:user:user_cost_sustained:posthog_code:42:period:0"-class TestBurstSustainedInteraction:@pytest.mark.asyncio@@ -482,7 +382,7 @@ class TestBurstSustainedInteraction:burst = UserCostBurstThrottle(redis=None)sustained = UserCostSustainedThrottle(redis=None)- context = make_context(product="posthog_code")+ context = make_context(product="background_agents")await burst.record_cost(context, 500.0)await sustained.record_cost(context, 100.0)@@ -498,7 +398,7 @@ class TestBurstSustainedInteraction:burst = UserCostBurstThrottle(redis=None)sustained = UserCostSustainedThrottle(redis=None)- context = make_context(product="posthog_code")+ context = make_context(product="background_agents")await burst.record_cost(context, 50.0)await sustained.record_cost(context, 3000.0)@@ -511,13 +411,13 @@ class TestBurstSustainedInteraction:async def test_custom_limits_via_env(self, monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setenv("LLM_GATEWAY_USER_COST_LIMITS",- '{"posthog_code": {"burst_limit_usd": 200, "burst_window_seconds": 86400, "sustained_limit_usd": 2000, "sustained_window_seconds": 2592000}}',+ '{"background_agents": {"burst_limit_usd": 200, "burst_window_seconds": 86400, "sustained_limit_usd": 2000, "sustained_window_seconds": 2592000}}',)get_settings.cache_clear()from llm_gateway.rate_limiting.cost_throttles import UserCostBurstThrottlethrottle = UserCostBurstThrottle(redis=None)- context = make_context(product="posthog_code")+ context = make_context(product="background_agents")await throttle.record_cost(context, 150.0)assert (await throttle.allow_request(context)).allowed is True@@ -535,7 +435,7 @@ class TestUserCostDisabledFlag:from llm_gateway.rate_limiting.cost_throttles import UserCostBurstThrottlethrottle = UserCostBurstThrottle(redis=None)- context = make_context(product="posthog_code")+ context = make_context(product="background_agents")await throttle.record_cost(context, 1000.0)result = await throttle.allow_request(context)@@ -551,7 +451,7 @@ class TestUserCostDisabledFlag:from llm_gateway.rate_limiting.cost_throttles import UserCostBurstThrottlethrottle = UserCostBurstThrottle(redis=None)- context = make_context(product="posthog_code")+ context = make_context(product="background_agents")await throttle.record_cost(context, 1000.0)result = await throttle.allow_request(context)@@ -567,7 +467,7 @@ class TestUserCostDisabledFlag:from llm_gateway.rate_limiting.cost_throttles import UserCostBurstThrottlethrottle = UserCostBurstThrottle(redis=None)- context = make_context(product="posthog_code")+ context = make_context(product="background_agents")await throttle.record_cost(context, 1000.0)result = await throttle.allow_request(context)@@ -584,7 +484,7 @@ class TestStaffUnlimitedUsage:from llm_gateway.rate_limiting.cost_throttles import UserCostBurstThrottlethrottle = UserCostBurstThrottle(redis=None)- context = make_context(user=make_user(is_staff=True), product="posthog_code")+ context = make_context(user=make_user(is_staff=True), product="background_agents")await throttle.record_cost(context, 100_000.0)# Observability guarantee: staff spend is still recorded even though the@@ -600,7 +500,7 @@ class TestStaffUnlimitedUsage:from llm_gateway.rate_limiting.cost_throttles import UserCostSustainedThrottlethrottle = UserCostSustainedThrottle(redis=None)- context = make_context(user=make_user(is_staff=True), product="posthog_code")+ context = make_context(user=make_user(is_staff=True), product="background_agents")await throttle.record_cost(context, 100_000.0)result = await throttle.allow_request(context)@@ -613,7 +513,7 @@ class TestStaffUnlimitedUsage:from llm_gateway.rate_limiting.cost_throttles import UserCostBurstThrottlethrottle = UserCostBurstThrottle(redis=None)- context = make_context(user=make_user(is_staff=True), product="posthog_code")+ context = make_context(user=make_user(is_staff=True), product="background_agents")await throttle.record_cost(context, 100_000.0)# Spend is recorded on the limiter even though the reported status hides it@@ -637,7 +537,7 @@ class TestStaffUnlimitedUsage:throttle = UserCostSustainedThrottle(redis=None)context = make_context(user=make_user(is_staff=True),- product="posthog_code",+ product="background_agents",plan_key="posthog-code-free-20260301",seat_created_at=(datetime.now(tz=UTC) - timedelta(days=5)).isoformat(),)@@ -652,7 +552,7 @@ class TestStaffUnlimitedUsage:from llm_gateway.rate_limiting.cost_throttles import UserCostBurstThrottlethrottle = UserCostBurstThrottle(redis=None)- context = make_context(user=make_user(is_staff=False), product="posthog_code")+ context = make_context(user=make_user(is_staff=False), product="background_agents")await throttle.record_cost(context, 500.0)result = await throttle.allow_request(context)@@ -668,7 +568,7 @@ class TestStaffUnlimitedUsage:throttle = UserCostBurstThrottle(redis=None)# With the bypass off, staff fall back to the multiplied finite cap# ($500 burst * 10 staff multiplier = $5000).- context = make_context(user=make_user(is_staff=True), product="posthog_code")+ context = make_context(user=make_user(is_staff=True), product="background_agents")await throttle.record_cost(context, 5_000.0)result = await throttle.allow_request(context)@@ -683,13 +583,13 @@ class TestRetryAfterHeader:from llm_gateway.rate_limiting.cost_throttles import UserCostBurstThrottlethrottle = UserCostBurstThrottle(redis=None)- context = make_context(product="posthog_code")+ context = make_context(product="background_agents")await throttle.record_cost(context, 500.0)result = await throttle.allow_request(context)assert result.allowed is False- assert result.retry_after == 86400+ assert result.retry_after == 604800get_settings.cache_clear()@pytest.mark.asyncio@@ -705,7 +605,7 @@ class TestRetryAfterHeader:mock_redis.ttl = AsyncMock(return_value=600)throttle = UserCostBurstThrottle(redis=mock_redis)- context = make_context(product="posthog_code")+ context = make_context(product="background_agents")result = await throttle.allow_request(context)@@ -721,7 +621,7 @@ class TestCostAccumulation:from llm_gateway.rate_limiting.cost_throttles import UserCostBurstThrottlethrottle = UserCostBurstThrottle(redis=None)- context = make_context(product="posthog_code")+ context = make_context(product="background_agents")for _ in range(49):await throttle.record_cost(context, 10.0)@@ -738,7 +638,7 @@ class TestCostAccumulation:from llm_gateway.rate_limiting.cost_throttles import UserCostBurstThrottlethrottle = UserCostBurstThrottle(redis=None)- context = make_context(product="posthog_code")+ context = make_context(product="background_agents")await throttle.record_cost(context, 0.0)await throttle.record_cost(context, -1.0)@@ -761,13 +661,13 @@ class TestCostRateLimiterRedisIntegration:mock_redis.get = AsyncMock(return_value=b"0.0")throttle = UserCostBurstThrottle(redis=mock_redis)- context = make_context(product="posthog_code")+ context = make_context(product="background_agents")await throttle.record_cost(context, 0.5)mock_redis.eval.assert_called_once()call_args = mock_redis.eval.call_args- assert "ratelimit:cost:user:user_cost_burst:posthog_code:1" in call_args[0]+ assert "ratelimit:cost:user:user_cost_burst:background_agents:1" in call_args[0]@pytest.mark.asyncioasync def test_redis_get_current_returns_accumulated_cost(self) -> None:@@ -779,7 +679,7 @@ class TestCostRateLimiterRedisIntegration:mock_redis.get = AsyncMock(return_value=b"1.5")throttle = UserCostBurstThrottle(redis=mock_redis)- context = make_context(product="posthog_code")+ context = make_context(product="background_agents")limiter = throttle._get_limiter(context)current = await limiter.get_current(throttle._get_cache_key(context))@@ -799,7 +699,7 @@ class TestCostRateLimiterRedisIntegration:mock_redis.ttl = AsyncMock(return_value=1800)throttle = UserCostBurstThrottle(redis=mock_redis)- context = make_context(product="posthog_code")+ context = make_context(product="background_agents")result = await throttle.allow_request(context)@@ -818,7 +718,7 @@ class TestCostRateLimiterRedisIntegration:mock_redis.get = AsyncMock(side_effect=Exception("Redis error"))throttle = UserCostBurstThrottle(redis=mock_redis)- context = make_context(product="posthog_code")+ context = make_context(product="background_agents")await throttle.record_cost(context, 0.1)@@ -836,11 +736,11 @@ class TestRateLimitMultiplier:throttle = UserCostBurstThrottle(redis=None)user = make_user(user_id=1, team_id=99, is_staff=False)- context = make_context(user=user, product="posthog_code")+ context = make_context(user=user, product="background_agents")key = throttle._get_cache_key(context)assert ":m" not in key- assert key == "cost:user:user_cost_burst:posthog_code:1"+ assert key == "cost:user:user_cost_burst:background_agents:1"get_settings.cache_clear()@pytest.mark.asyncio@@ -851,10 +751,10 @@ class TestRateLimitMultiplier:throttle = UserCostBurstThrottle(redis=None)user = make_user(user_id=1, team_id=2, is_staff=False)- context = make_context(user=user, product="posthog_code")+ context = make_context(user=user, product="background_agents")key = throttle._get_cache_key(context)- assert key == "cost:user:user_cost_burst:posthog_code:1:m10"+ assert key == "cost:user:user_cost_burst:background_agents:1:m10"get_settings.cache_clear()@pytest.mark.asyncio@@ -866,10 +766,10 @@ class TestRateLimitMultiplier: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")+ context = make_context(user=user, product="background_agents")key = throttle._get_cache_key(context)- assert key == "cost:user:user_cost_burst:posthog_code:1:m10"+ assert key == "cost:user:user_cost_burst:background_agents:1:m10"get_settings.cache_clear()@pytest.mark.asyncio@@ -880,7 +780,7 @@ class TestRateLimitMultiplier:throttle = UserCostBurstThrottle(redis=None)user = make_user(user_id=1, team_id=2, is_staff=False)- context = make_context(user=user, product="posthog_code")+ context = make_context(user=user, product="background_agents")await throttle.record_cost(context, 100.0)result = await throttle.allow_request(context)@@ -896,7 +796,7 @@ class TestRateLimitMultiplier: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")+ context = make_context(user=user, product="background_agents")await throttle.record_cost(context, 100.0)result = await throttle.allow_request(context)@@ -913,10 +813,10 @@ class TestRateLimitMultiplier: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")+ context = make_context(user=user, product="background_agents")key = throttle._get_cache_key(context)- assert key == "cost:user:user_cost_burst:posthog_code:1:m10"+ assert key == "cost:user:user_cost_burst:background_agents:1:m10"get_settings.cache_clear()@pytest.mark.asyncio@@ -980,17 +880,17 @@ class TestUnconfiguredProductsUseDefaults:burst = UserCostBurstThrottle(redis=None)sustained = UserCostSustainedThrottle(redis=None)- ctx_posthog_code = make_context(product="posthog_code")+ ctx_background_agents = make_context(product="background_agents")ctx_wizard = make_context(product="wizard")- await burst.record_cost(ctx_posthog_code, 500.0)+ await burst.record_cost(ctx_background_agents, 500.0)await burst.record_cost(ctx_wizard, 100.0)- await sustained.record_cost(ctx_posthog_code, 3000.0)+ await sustained.record_cost(ctx_background_agents, 3000.0)await sustained.record_cost(ctx_wizard, 1000.0)- assert (await burst.allow_request(ctx_posthog_code)).allowed is False+ assert (await burst.allow_request(ctx_background_agents)).allowed is Falseassert (await burst.allow_request(ctx_wizard)).allowed is False- assert (await sustained.allow_request(ctx_posthog_code)).allowed is False+ assert (await sustained.allow_request(ctx_background_agents)).allowed is Falseassert (await sustained.allow_request(ctx_wizard)).allowed is Falseget_settings.cache_clear()@@ -1067,7 +967,7 @@ class TestUserCostEdgeCases:throttle = UserCostSustainedThrottle(redis=None)user = make_user(user_id=1, auth_method="personal_api_key")- context = make_context(user=user, product="posthog_code", end_user_id=None)+ context = make_context(user=user, product="background_agents", end_user_id=None)await throttle.record_cost(context, 99999.0)result = await throttle.allow_request(context)@@ -1081,7 +981,7 @@ class TestUserCostEdgeCases:throttle = UserCostBurstThrottle(redis=None)user = make_user(user_id=1, auth_method="personal_api_key")- context = make_context(user=user, product="posthog_code", end_user_id="")+ context = make_context(user=user, product="background_agents", end_user_id="")await throttle.record_cost(context, 99999.0)result = await throttle.allow_request(context)@@ -1095,7 +995,7 @@ class TestUserCostEdgeCases:throttle = UserCostBurstThrottle(redis=None)user = make_user(user_id=1, auth_method="personal_api_key")- context = make_context(user=user, product="posthog_code", end_user_id="ext-user-42")+ context = make_context(user=user, product="background_agents", end_user_id="ext-user-42")await throttle.record_cost(context, 500.0)result = await throttle.allow_request(context)@@ -1124,7 +1024,7 @@ class TestUserCostEdgeCases:throttle = UserCostBurstThrottle(redis=None)user = make_user(auth_method="personal_api_key")- context = make_context(user=user, product="posthog_code", end_user_id=None)+ context = make_context(user=user, product="background_agents", end_user_id=None)assert throttle._get_cache_key(context) == ""@@ -1158,7 +1058,7 @@ class TestUserCostEdgeCases:from llm_gateway.rate_limiting.cost_throttles import UserCostBurstThrottlethrottle = UserCostBurstThrottle(redis=None)- context = make_context(product="posthog_code")+ context = make_context(product="background_agents")await throttle.record_cost(context, 199.99)result = await throttle.allow_request(context)@@ -1171,7 +1071,7 @@ class TestUserCostEdgeCases:from llm_gateway.rate_limiting.cost_throttles import UserCostBurstThrottlethrottle = UserCostBurstThrottle(redis=None)- context = make_context(product="posthog_code")+ context = make_context(product="background_agents")await throttle.record_cost(context, 500.0)result = await throttle.allow_request(context)@@ -1187,7 +1087,7 @@ class TestUserCostDisabledSustained:from llm_gateway.rate_limiting.cost_throttles import UserCostSustainedThrottlethrottle = UserCostSustainedThrottle(redis=None)- context = make_context(product="posthog_code")+ context = make_context(product="background_agents")await throttle.record_cost(context, 9999.0)result = await throttle.allow_request(context)@@ -1202,7 +1102,7 @@ class TestUserCostDisabledSustained:burst = UserCostBurstThrottle(redis=None)sustained = UserCostSustainedThrottle(redis=None)- context = make_context(product="posthog_code")+ context = make_context(product="background_agents")await burst.record_cost(context, 9999.0)await sustained.record_cost(context, 9999.0)@@ -1230,8 +1130,8 @@ class TestRateLimitPoisoningPrevention:attacker = make_user(user_id=999, auth_method="personal_api_key")victim = make_user(user_id=42, auth_method="oauth_access_token")- attacker_ctx = make_context(user=attacker, product="posthog_code", end_user_id="999")- victim_ctx = make_context(user=victim, product="posthog_code")+ attacker_ctx = make_context(user=attacker, product="background_agents", end_user_id="999")+ victim_ctx = make_context(user=victim, product="background_agents")await throttle.record_cost(attacker_ctx, 500.0)@@ -1250,7 +1150,7 @@ class TestRateLimitPoisoningPrevention:throttle = UserCostBurstThrottle(redis=None)user = make_user(user_id=999, auth_method="personal_api_key")- context = make_context(user=user, product="posthog_code", end_user_id="999")+ context = make_context(user=user, product="background_agents", end_user_id="999")await throttle.record_cost(context, 500.0)result = await throttle.allow_request(context)@@ -1277,184 +1177,18 @@ class TestRateLimitPoisoningPrevention:assert ":42" in victim_key-class TestPlanAwareThrottling:- @pytest.mark.asyncio- async def test_free_user_gets_limit_of_20(self) -> None:- from llm_gateway.rate_limiting.cost_throttles import UserCostBurstThrottle-- throttle = UserCostBurstThrottle(redis=None)- context = make_context(product="posthog_code", plan_key=None, seat_created_at="2026-01-01T00:00:00+00:00")-- await throttle.record_cost(context, 20.0)- result = await throttle.allow_request(context)- assert result.allowed is False-- @pytest.mark.asyncio- async def test_free_user_gets_sustained_limit_of_20(self) -> None:- from llm_gateway.rate_limiting.cost_throttles import UserCostSustainedThrottle-- throttle = UserCostSustainedThrottle(redis=None)- context = make_context(product="posthog_code", plan_key=None, seat_created_at="2026-01-01T00:00:00+00:00")-- await throttle.record_cost(context, 20.0)- result = await throttle.allow_request(context)- assert result.allowed is False-+class TestPostHogCodeUserThrottling:@pytest.mark.asyncio- async def test_old_free_user_still_gets_burst_limit(self) -> None:- from llm_gateway.rate_limiting.cost_throttles import UserCostBurstThrottle-- throttle = UserCostBurstThrottle(redis=None)- context = make_context(product="posthog_code", plan_key=None, seat_created_at="2025-01-01T00:00:00+00:00")-- await throttle.record_cost(context, 4.0)- result = await throttle.allow_request(context)- assert result.allowed is True-- @pytest.mark.asyncio- async def test_old_free_user_still_gets_sustained_limit(self) -> None:- from llm_gateway.rate_limiting.cost_throttles import UserCostSustainedThrottle-- throttle = UserCostSustainedThrottle(redis=None)- context = make_context(product="posthog_code", plan_key=None, seat_created_at="2025-01-01T00:00:00+00:00")-- await throttle.record_cost(context, 19.0)- result = await throttle.allow_request(context)- assert result.allowed is True-- @pytest.mark.asyncio- async def test_no_seat_gets_pro_limits(self) -> None:- from llm_gateway.rate_limiting.cost_throttles import UserCostBurstThrottle-- throttle = UserCostBurstThrottle(redis=None)- context = make_context(product="posthog_code", plan_key=None, seat_created_at=None)-- await throttle.record_cost(context, 50.0)- result = await throttle.allow_request(context)- assert result.allowed is True-- @pytest.mark.asyncio- async def test_pro_plan_allows_higher_usage(self) -> None:- from llm_gateway.rate_limiting.cost_throttles import UserCostBurstThrottle-- throttle = UserCostBurstThrottle(redis=None)- context = make_context(product="posthog_code", plan_key="posthog-code-200-20260301")-- await throttle.record_cost(context, 50.0)- result = await throttle.allow_request(context)- assert result.allowed is True-- @pytest.mark.asyncio- async def test_renamed_pro_plan_allows_higher_usage(self) -> None:- from llm_gateway.rate_limiting.cost_throttles import UserCostBurstThrottle-- throttle = UserCostBurstThrottle(redis=None)- context = make_context(product="posthog_code", plan_key="posthog-code-pro-200-20260301")-- await throttle.record_cost(context, 50.0)- result = await throttle.allow_request(context)- assert result.allowed is True-- @pytest.mark.asyncio- async def test_zero_dollar_pro_plan_allows_higher_usage(self) -> None:- from llm_gateway.rate_limiting.cost_throttles import UserCostBurstThrottle-- throttle = UserCostBurstThrottle(redis=None)- context = make_context(product="posthog_code", plan_key="posthog-code-pro-0-20260422")-- await throttle.record_cost(context, 50.0)- result = await throttle.allow_request(context)- assert result.allowed is True-- @pytest.mark.asyncio- async def test_free_plan_key_gets_free_limits(self) -> None:- from llm_gateway.rate_limiting.cost_throttles import UserCostBurstThrottle-- throttle = UserCostBurstThrottle(redis=None)- context = make_context(- product="posthog_code",- plan_key="posthog-code-free-20260301",- seat_created_at="2026-01-01T00:00:00+00:00",- )-- await throttle.record_cost(context, 4.0)- result = await throttle.allow_request(context)- assert result.allowed is True-- @pytest.mark.asyncio- @pytest.mark.parametrize(- ("seat_missing", "expected_allowed"),- [- # Confirmed no seat (404) → free cap: $80 spent exceeds the $20 limit.- (True, False),- # Plan resolution failed → default limits ($500/day): fail loose so an- # outage never clamps paying users whose plan couldn't be resolved.- (False, True),- ],- )- async def test_seatless_user_limit_depends_on_seat_missing(- self, seat_missing: bool, expected_allowed: bool- ) -> None:- from llm_gateway.rate_limiting.cost_throttles import UserCostBurstThrottle-- throttle = UserCostBurstThrottle(redis=None)- context = make_context(- product="posthog_code",- plan_key=None,- seat_created_at=None,- seat_missing=seat_missing,- )-- await throttle.record_cost(context, 80.0)- result = await throttle.allow_request(context)- assert result.allowed is expected_allowed-- @pytest.mark.asyncio- @pytest.mark.parametrize(- ("seat_missing", "code_usage_billed", "expected_allowed"),- [- # Seatless + org-billed Desktop usage: bills to the org - no per-user cap.- # $600 spent clears both the $20 free cap and the $500/day default.- (True, True, True),- # Seatless + not billed: the free cap holds (this pair pins that the- # bypass never leaks to orgs that would get the usage for free).- (True, False, False),- # Seat still exists (pre-retirement): org billing doesn't lift the cap -- # seat-covered usage stays bounded until the seat is deleted.- (False, True, False),- ],- )- async def test_code_usage_billing_gates_seatless_cap_bypass(- self, seat_missing: bool, code_usage_billed: bool, expected_allowed: bool- ) -> None:- from llm_gateway.rate_limiting.cost_throttles import UserCostBurstThrottle-- throttle = UserCostBurstThrottle(redis=None)- context = make_context(- product="posthog_code",- plan_key=None if seat_missing else "posthog-code-free-20260301",- seat_created_at=None if seat_missing else "2026-01-01T00:00:00+00:00",- seat_missing=seat_missing,- code_usage_billed=code_usage_billed,- )+ @pytest.mark.parametrize("throttle_type", [UserCostBurstThrottle, UserCostSustainedThrottle])+ async def test_posthog_code_has_no_user_cost_limit(self, throttle_type: type[_UserCostThrottleBase]) -> None:+ throttle = throttle_type(redis=None)+ context = make_context(product="posthog_code", plan_key=None, seat_missing=True)await throttle.record_cost(context, 600.0)- result = await throttle.allow_request(context)- assert result.allowed is expected_allowed- @pytest.mark.asyncio- async def test_org_billed_seatless_status_reports_unlimited(self) -> None:- from llm_gateway.rate_limiting.cost_throttles import UserCostBurstThrottle-- throttle = UserCostBurstThrottle(redis=None)- context = make_context(- product="posthog_code", plan_key=None, seat_created_at=None, seat_missing=True, code_usage_billed=True- )-- await throttle.record_cost(context, 600.0)+ result = await throttle.allow_request(context)status = await throttle.get_status(context)- # The usage endpoint renders this - it must agree with enforcement (never- # show a paying user as rate limited when nothing would block them).+ assert result.allowed is Trueassert status.exceeded is Falseassert status.limit_usd == float("inf")