Skip to content

: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.

fix(llm-gateway): free-cap posthog_code users with no seat (#70810)

Adam Bowker6c4263235946
diff --git a/products/tasks/backend/presentation/views/seat_api.py b/products/tasks/backend/presentation/views/seat_api.py
index 2688dee9c390..e114f5ea4628 100644
--- a/products/tasks/backend/presentation/views/seat_api.py
+++ b/products/tasks/backend/presentation/views/seat_api.py
@@ -281,29 +281,35 @@ class SeatViewSet(viewsets.ViewSet):
data = {**drf_resp.data, "organization_id": str(org.id), "organization_name": org.name}
return Response(data)
- def fetch_seat(org: Organization) -> tuple[Organization, dict[str, Any]] | None:
+ def fetch_seat(org: Organization) -> tuple[Organization, Response]:
headers = self._get_billing_headers_for_org(user, org)
- if not headers:
- return None
- resp = self._billing_request("GET", f"/api/v2/seats/{distinct_id}/", headers, query_params=query_params)
- drf_resp = self._forward_response(resp)
- if not 200 <= drf_resp.status_code < 300 or not isinstance(drf_resp.data, dict):
- return None
- return (org, drf_resp.data)
+ resp = (
+ self._billing_request("GET", f"/api/v2/seats/{distinct_id}/", headers, query_params=query_params)
+ if headers
+ else None
+ )
+ return (org, self._forward_response(resp))
results: list[tuple[Organization, dict[str, Any]]] = []
+ any_lookup_failed = False
with ThreadPoolExecutor(max_workers=min(len(orgs), 5)) as pool:
futures = {pool.submit(fetch_seat, org): org for org in orgs}
for future in as_completed(futures):
try:
- result = future.result()
+ org, drf_resp = future.result()
except Exception:
- logger.warning("fetch_seat_failed", org_id=str(futures[future].id))
+ logger.exception("fetch_seat_crashed", org_id=str(futures[future].id))
+ any_lookup_failed = True
continue
- if result:
- results.append(result)
+ if 200 <= drf_resp.status_code < 300 and isinstance(drf_resp.data, dict):
+ results.append((org, drf_resp.data))
+ elif drf_resp.status_code != status.HTTP_404_NOT_FOUND:
+ logger.warning("fetch_seat_failed", org_id=str(org.id), status_code=drf_resp.status_code)
+ any_lookup_failed = True
if not results:
+ if any_lookup_failed:
+ return Response({"detail": "Seat lookup incomplete"}, status=status.HTTP_503_SERVICE_UNAVAILABLE)
return Response(status=status.HTTP_404_NOT_FOUND)
best_org, best = max(results, key=lambda r: _seat_priority(r[1]))
diff --git a/products/tasks/backend/tests/test_seat_api.py b/products/tasks/backend/tests/test_seat_api.py
index e8959787efb1..e89fecf11efb 100644
--- a/products/tasks/backend/tests/test_seat_api.py
+++ b/products/tasks/backend/tests/test_seat_api.py
@@ -420,10 +420,36 @@ class TestSeatAPIBestPlan(BaseSeatAPITest):
@patch("products.tasks.backend.presentation.views.seat_api.requests.request")
@patch("products.tasks.backend.presentation.views.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)
- def test_all_billing_failures_returns_404(self, _mock_token, mock_request, _mock_license):
+ def test_all_billing_failures_returns_503(self, _mock_token, mock_request, _mock_license):
+ """A failed lookup is not a confirmed absence: the LLM gateway caches a 404
+ as seat_missing and free-caps the user, so a billing outage must surface
+ as an error it fails open on, never as 404."""
mock_request.return_value = _billing_response({"error": "fail"}, status_code=500, ok=False)
self._auth_as_member()
response = self.client.get("/api/seats/me/?product_key=posthog_code&best=true")
+ assert response.status_code == status.HTTP_503_SERVICE_UNAVAILABLE
+
+ @patch("products.tasks.backend.presentation.views.seat_api.requests.request")
+ @patch("products.tasks.backend.presentation.views.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)
+ def test_partial_failure_with_no_seat_returns_503(self, _mock_token, mock_request, _mock_license):
+ mock_request.side_effect = [
+ _billing_response({"error": "fail"}, status_code=500, ok=False),
+ _billing_response({"error": "No seat found for this user"}, status_code=404, ok=False),
+ ]
+ self._auth_as_member()
+ response = self.client.get("/api/seats/me/?product_key=posthog_code&best=true")
+ assert response.status_code == status.HTTP_503_SERVICE_UNAVAILABLE
+
+ @patch("products.tasks.backend.presentation.views.seat_api.requests.request")
+ @patch("products.tasks.backend.presentation.views.seat_api.build_billing_token", return_value=MOCK_BILLING_TOKEN)
+ def test_all_orgs_conclusively_no_seat_returns_404(self, _mock_token, mock_request, _mock_license):
+ """404 stays 404 when every org's lookup succeeded and found nothing —
+ the gateway's seat_missing free-cap depends on this conclusive signal."""
+ mock_request.return_value = _billing_response(
+ {"error": "No seat found for this user"}, status_code=404, ok=False
+ )
+ self._auth_as_member()
+ response = self.client.get("/api/seats/me/?product_key=posthog_code&best=true")
assert response.status_code == status.HTTP_404_NOT_FOUND
@patch("products.tasks.backend.presentation.views.seat_api.requests.request")
diff --git a/services/llm-gateway/src/llm_gateway/api/usage.py b/services/llm-gateway/src/llm_gateway/api/usage.py
index 3797552fa6a6..71ea7311c1e3 100644
--- a/services/llm-gateway/src/llm_gateway/api/usage.py
+++ b/services/llm-gateway/src/llm_gateway/api/usage.py
@@ -92,6 +92,7 @@ async def get_usage(
end_user_id=str(user.user_id),
plan_key=plan_info.plan_key,
seat_created_at=plan_info.seat_created_at,
+ seat_missing=plan_info.seat_missing,
billing_period_start=plan_info.billing_period.current_period_start if plan_info.billing_period else None,
credits_exhausted=quota_status.limited,
)
diff --git a/services/llm-gateway/src/llm_gateway/dependencies.py b/services/llm-gateway/src/llm_gateway/dependencies.py
index b672737e1a59..4aeda4fb1bf2 100644
--- a/services/llm-gateway/src/llm_gateway/dependencies.py
+++ b/services/llm-gateway/src/llm_gateway/dependencies.py
@@ -209,6 +209,7 @@ async def enforce_throttles(
end_user_id=end_user_id,
plan_key=plan_info.plan_key,
seat_created_at=plan_info.seat_created_at,
+ seat_missing=plan_info.seat_missing,
billing_period_start=plan_info.billing_period.current_period_start if plan_info.billing_period else None,
credits_exhausted=quota_status.limited,
)
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.py
index 3a8913f8c48c..7c526c440d85 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
@@ -41,7 +41,7 @@ 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
+ and (context.seat_created_at is not None or context.seat_missing)
)
diff --git a/services/llm-gateway/src/llm_gateway/rate_limiting/throttles.py b/services/llm-gateway/src/llm_gateway/rate_limiting/throttles.py
index 2f0a123d594e..78d145abc2e8 100644
--- a/services/llm-gateway/src/llm_gateway/rate_limiting/throttles.py
+++ b/services/llm-gateway/src/llm_gateway/rate_limiting/throttles.py
@@ -47,6 +47,7 @@ class ThrottleContext:
end_user_id: str | None = None
plan_key: str | None = None
seat_created_at: str | None = None
+ seat_missing: bool = False
billing_period_start: str | None = None
credits_exhausted: bool = False
diff --git a/services/llm-gateway/src/llm_gateway/services/plan_resolver.py b/services/llm-gateway/src/llm_gateway/services/plan_resolver.py
index 0fb4f487f630..9ee5585d3f38 100644
--- a/services/llm-gateway/src/llm_gateway/services/plan_resolver.py
+++ b/services/llm-gateway/src/llm_gateway/services/plan_resolver.py
@@ -44,6 +44,7 @@ class PlanInfo:
plan_key: str | None
seat_created_at: str | None
billing_period: BillingPeriod | None = None
+ seat_missing: bool = False
def _redis_key(user_id: int) -> str:
@@ -156,16 +157,17 @@ class PlanResolver:
return cached
try:
- plan_key, seat_created_at, billing_period = await self._fetch_plan(auth_header)
+ plan_key, seat_created_at, billing_period, seat_missing = await self._fetch_plan(auth_header)
except Exception:
logger.warning("seat_fetch_failed", user_id=user_id, exc_info=True)
return PlanInfo(plan_key=None, seat_created_at=None)
- await self._set_cached(user_id, plan_key, seat_created_at, billing_period)
+ await self._set_cached(user_id, plan_key, seat_created_at, billing_period, seat_missing)
return PlanInfo(
plan_key=plan_key,
seat_created_at=seat_created_at,
billing_period=billing_period,
+ seat_missing=seat_missing,
)
async def _get_cached(self, user_id: int) -> PlanInfo | None:
@@ -182,6 +184,7 @@ class PlanResolver:
plan_key=plan_key,
seat_created_at=seat_created_at,
billing_period=billing_period,
+ seat_missing=bool(data.get("seat_missing", False)),
)
except Exception:
logger.debug("plan_cache_read_failed", user_id=user_id)
@@ -193,12 +196,17 @@ class PlanResolver:
plan_key: str | None,
seat_created_at: str | None,
billing_period: BillingPeriod | None = None,
+ seat_missing: bool = False,
) -> None:
if not self._redis:
return
ttl = get_settings().plan_cache_ttl
try:
- payload: dict[str, object] = {"plan_key": plan_key, "created_at": seat_created_at}
+ payload: dict[str, object] = {
+ "plan_key": plan_key,
+ "created_at": seat_created_at,
+ "seat_missing": seat_missing,
+ }
if billing_period:
payload["billing_period"] = {
"current_period_start": billing_period.current_period_start,
@@ -210,15 +218,17 @@ class PlanResolver:
except Exception:
logger.debug("plan_cache_write_failed", user_id=user_id)
- async def _fetch_plan(self, auth_header: str) -> tuple[str | None, str | None, BillingPeriod | None]:
+ async def _fetch_plan(self, auth_header: str) -> tuple[str | None, str | None, BillingPeriod | None, bool]:
"""Call the PostHog API seats endpoint to get the user's plan.
Raises on transient HTTP failures so the caller can skip caching.
- Returns (None, None, None) for legitimate "no plan" states (404, no API URL).
+ Returns (None, None, None, seat_missing) for legitimate "no plan"
+ states — seat_missing is True only for a definitive 404 (the user has
+ no seat), not for a missing API URL.
"""
settings = get_settings()
if not settings.posthog_api_base_url:
- return None, None, None
+ return None, None, None, False
url = f"{settings.posthog_api_base_url.rstrip('/')}/api/seats/me/"
resp = await self._http.get(
@@ -228,8 +238,8 @@ class PlanResolver:
timeout=2.0,
)
if resp.status_code == 404:
- return None, None, None
+ return None, None, None, True
resp.raise_for_status()
data = resp.json()
billing_period = _parse_billing_period(data.get("billing_period"))
- return data.get("plan_key"), data.get("created_at"), billing_period
+ return data.get("plan_key"), data.get("created_at"), billing_period, False
diff --git a/services/llm-gateway/tests/test_cost_throttles.py b/services/llm-gateway/tests/test_cost_throttles.py
index 430223da9e44..8c5dc6d1a398 100644
--- a/services/llm-gateway/tests/test_cost_throttles.py
+++ b/services/llm-gateway/tests/test_cost_throttles.py
@@ -25,6 +25,7 @@ def make_context(
end_user_id: str | None = None,
plan_key: str | None = "posthog-code-200-20260301",
seat_created_at: str | None = None,
+ seat_missing: bool = False,
billing_period_start: str | None = None,
) -> ThrottleContext:
user = user or make_user()
@@ -36,6 +37,7 @@ def make_context(
end_user_id=end_user_id,
plan_key=plan_key,
seat_created_at=seat_created_at,
+ seat_missing=seat_missing,
billing_period_start=billing_period_start,
)
@@ -1377,6 +1379,34 @@ class TestPlanAwareThrottling:
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 $75 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
async def test_non_code_product_ignores_plan(self) -> None:
from llm_gateway.rate_limiting.cost_throttles import UserCostBurstThrottle
diff --git a/services/llm-gateway/tests/test_plan_resolver.py b/services/llm-gateway/tests/test_plan_resolver.py
index 7c275c6c0a11..ca7b8fc6a77f 100644
--- a/services/llm-gateway/tests/test_plan_resolver.py
+++ b/services/llm-gateway/tests/test_plan_resolver.py
@@ -108,13 +108,14 @@ class TestPlanResolver:
mock_settings.return_value.plan_cache_ttl = 300
result = await resolver.get_plan(user_id=1, auth_header="Bearer phx_test")
assert result.plan_key is None
+ assert result.seat_missing is False
async def test_returns_cached_plan(self, resolver_with_redis: PlanResolver) -> None:
import json
cached = json.dumps({"plan_key": "posthog-code-200-20260301", "created_at": None})
assert resolver_with_redis._redis is not None
- resolver_with_redis._redis.get = AsyncMock(return_value=cached.encode()) # type: ignore[method-assign]
+ resolver_with_redis._redis.get = AsyncMock(return_value=cached.encode()) # type: ignore[method-assign] # ty: ignore[invalid-assignment]
result = await resolver_with_redis.get_plan(user_id=1, auth_header="Bearer phx_test")
assert result.plan_key == "posthog-code-200-20260301"
@@ -123,9 +124,11 @@ class TestPlanResolver:
cached = json.dumps({"plan_key": None, "created_at": None})
assert resolver_with_redis._redis is not None
- resolver_with_redis._redis.get = AsyncMock(return_value=cached.encode()) # type: ignore[method-assign]
+ resolver_with_redis._redis.get = AsyncMock(return_value=cached.encode()) # type: ignore[method-assign] # ty: ignore[invalid-assignment]
result = await resolver_with_redis.get_plan(user_id=1, auth_header="Bearer phx_test")
assert result.plan_key is None
+ # Entries cached before seat_missing existed must fail loose.
+ assert result.seat_missing is False
async def test_cached_old_seat_returns_plan(self, resolver_with_redis: PlanResolver) -> None:
import json
@@ -133,7 +136,7 @@ class TestPlanResolver:
old_date = (datetime.now(tz=UTC) - timedelta(days=60)).isoformat()
cached = json.dumps({"plan_key": "posthog-code-free-20260301", "created_at": old_date})
assert resolver_with_redis._redis is not None
- resolver_with_redis._redis.get = AsyncMock(return_value=cached.encode()) # type: ignore[method-assign]
+ resolver_with_redis._redis.get = AsyncMock(return_value=cached.encode()) # type: ignore[method-assign] # ty: ignore[invalid-assignment]
result = await resolver_with_redis.get_plan(user_id=1, auth_header="Bearer phx_test")
assert result.plan_key == "posthog-code-free-20260301"
assert result.seat_created_at == old_date
@@ -152,7 +155,7 @@ class TestPlanResolver:
},
}
mock_resp.raise_for_status = MagicMock()
- resolver_with_redis._http.get = AsyncMock(return_value=mock_resp) # type: ignore[method-assign]
+ resolver_with_redis._http.get = AsyncMock(return_value=mock_resp) # type: ignore[method-assign] # ty: ignore[invalid-assignment]
with patch("llm_gateway.services.plan_resolver.get_settings") as mock_settings:
mock_settings.return_value.posthog_api_base_url = "https://app.posthog.com"
@@ -178,7 +181,7 @@ class TestPlanResolver:
mock_resp.status_code = 200
mock_resp.json.return_value = {"plan_key": "posthog-code-200-20260301", "created_at": None}
mock_resp.raise_for_status = MagicMock()
- resolver_with_redis._http.get = AsyncMock(return_value=mock_resp) # type: ignore[method-assign]
+ resolver_with_redis._http.get = AsyncMock(return_value=mock_resp) # type: ignore[method-assign] # ty: ignore[invalid-assignment]
with patch("llm_gateway.services.plan_resolver.get_settings") as mock_settings:
mock_settings.return_value.posthog_api_base_url = "https://app.posthog.com"
@@ -193,7 +196,7 @@ class TestPlanResolver:
mock_resp.status_code = 200
mock_resp.json.return_value = {"plan_key": None, "created_at": None}
mock_resp.raise_for_status = MagicMock()
- resolver._http.get = AsyncMock(return_value=mock_resp) # type: ignore[method-assign]
+ resolver._http.get = AsyncMock(return_value=mock_resp) # type: ignore[method-assign] # ty: ignore[invalid-assignment]
with patch("llm_gateway.services.plan_resolver.get_settings") as mock_settings:
mock_settings.return_value.posthog_api_base_url = "https://app.posthog.com"
@@ -207,7 +210,7 @@ class TestPlanResolver:
async def test_404_returns_none_plan(self, resolver: PlanResolver) -> None:
mock_resp = MagicMock()
mock_resp.status_code = 404
- resolver._http.get = AsyncMock(return_value=mock_resp) # type: ignore[method-assign]
+ resolver._http.get = AsyncMock(return_value=mock_resp) # type: ignore[method-assign] # ty: ignore[invalid-assignment]
with patch("llm_gateway.services.plan_resolver.get_settings") as mock_settings:
mock_settings.return_value.posthog_api_base_url = "https://app.posthog.com"
@@ -215,9 +218,29 @@ class TestPlanResolver:
result = await resolver.get_plan(user_id=1, auth_header="Bearer phx_test")
assert result.plan_key is None
+ assert result.seat_missing is True
+
+ async def test_404_seat_missing_round_trips_through_cache(self, resolver_with_redis: PlanResolver) -> None:
+ import json
+
+ mock_resp = MagicMock()
+ mock_resp.status_code = 404
+ resolver_with_redis._http.get = AsyncMock(return_value=mock_resp) # type: ignore[method-assign] # ty: ignore[invalid-assignment]
+
+ with patch("llm_gateway.services.plan_resolver.get_settings") as mock_settings:
+ mock_settings.return_value.posthog_api_base_url = "https://app.posthog.com"
+ mock_settings.return_value.plan_cache_ttl = 300
+ await resolver_with_redis.get_plan(user_id=1, auth_header="Bearer phx_test")
+
+ assert resolver_with_redis._redis is not None
+ cached_payload = resolver_with_redis._redis.set.call_args.args[1] # type: ignore[attr-defined]
+ resolver_with_redis._redis.get = AsyncMock(return_value=cached_payload.encode()) # type: ignore[method-assign] # ty: ignore[invalid-assignment]
+ cached_result = await resolver_with_redis.get_plan(user_id=1, auth_header="Bearer phx_test")
+ assert json.loads(cached_payload)["seat_missing"] is True
+ assert cached_result.seat_missing is True
async def test_api_error_returns_none_plan(self, resolver: PlanResolver) -> None:
- resolver._http.get = AsyncMock(side_effect=Exception("connection refused")) # type: ignore[method-assign]
+ resolver._http.get = AsyncMock(side_effect=Exception("connection refused")) # type: ignore[method-assign] # ty: ignore[invalid-assignment]
with patch("llm_gateway.services.plan_resolver.get_settings") as mock_settings:
mock_settings.return_value.posthog_api_base_url = "https://app.posthog.com"
@@ -225,6 +248,7 @@ class TestPlanResolver:
result = await resolver.get_plan(user_id=1, auth_header="Bearer phx_test")
assert result.plan_key is None
+ assert result.seat_missing is False
async def test_empty_auth_header_skips_fetch(self, resolver: PlanResolver) -> None:
result = await resolver.get_plan(user_id=1, auth_header="")
@@ -246,7 +270,7 @@ class TestPlanResolver:
}
)
assert resolver_with_redis._redis is not None
- resolver_with_redis._redis.get = AsyncMock(return_value=cached.encode()) # type: ignore[method-assign]
+ resolver_with_redis._redis.get = AsyncMock(return_value=cached.encode()) # type: ignore[method-assign] # ty: ignore[invalid-assignment]
result = await resolver_with_redis.get_plan(user_id=1, auth_header="Bearer phx_test")
assert result.billing_period is not None
assert result.billing_period.current_period_start == "2026-04-01T00:00:00+00:00"
@@ -257,12 +281,12 @@ class TestPlanResolver:
cached = json.dumps({"plan_key": "posthog-code-200-20260301", "created_at": None})
assert resolver_with_redis._redis is not None
- resolver_with_redis._redis.get = AsyncMock(return_value=cached.encode()) # type: ignore[method-assign]
+ resolver_with_redis._redis.get = AsyncMock(return_value=cached.encode()) # type: ignore[method-assign] # ty: ignore[invalid-assignment]
result = await resolver_with_redis.get_plan(user_id=1, auth_header="Bearer phx_test")
assert result.billing_period is None
async def test_api_error_not_cached(self, resolver_with_redis: PlanResolver) -> None:
- resolver_with_redis._http.get = AsyncMock(side_effect=Exception("connection refused")) # type: ignore[method-assign]
+ resolver_with_redis._http.get = AsyncMock(side_effect=Exception("connection refused")) # type: ignore[method-assign] # ty: ignore[invalid-assignment]
with patch("llm_gateway.services.plan_resolver.get_settings") as mock_settings:
mock_settings.return_value.posthog_api_base_url = "https://app.posthog.com"