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.

chore(llm-gateway): stop resolving retired PostHog Desktop seats (#94055)

Roy Cohen5f1a99718f84
diff --git a/products/tasks/backend/presentation/views/seat_api.py b/products/tasks/backend/presentation/views/seat_api.py
index 7927be946b03..e8fe9a9381f4 100644
--- a/products/tasks/backend/presentation/views/seat_api.py
+++ b/products/tasks/backend/presentation/views/seat_api.py
@@ -24,7 +24,6 @@ from posthog.models.user import User
from ee.billing.billing_manager import build_billing_token
from ee.settings import BILLING_SERVICE_URL
-# Duplicated in services/llm-gateway/src/llm_gateway/services/plan_resolver.py
PRO_PLAN_PREFIXES = ("posthog-code-200", "posthog-code-pro-")
RETIRED_SEAT_PRODUCT_MESSAGE = (
"You can no longer create, upgrade, or reactivate PostHog Desktop seats. "
diff --git a/services/llm-gateway/src/llm_gateway/api/usage.py b/services/llm-gateway/src/llm_gateway/api/usage.py
index 1377ad2fd0cc..161dd3e42bf2 100644
--- a/services/llm-gateway/src/llm_gateway/api/usage.py
+++ b/services/llm-gateway/src/llm_gateway/api/usage.py
@@ -5,22 +5,17 @@ from datetime import UTC, datetime, timedelta
from typing import Annotated
import structlog
-from fastapi import APIRouter, Depends, HTTPException, Request
+from fastapi import APIRouter, Depends, Request
from pydantic import BaseModel
from llm_gateway.auth.models import AuthenticatedUser
-from llm_gateway.dependencies import get_authenticated_user, resolve_plan_and_quota
+from llm_gateway.dependencies import get_authenticated_user, resolve_quota
+from llm_gateway.products.config import POSTHOG_CODE_PRODUCT
from llm_gateway.rate_limiting.billable_credits_throttle import bucket_block_applies
from llm_gateway.rate_limiting.cost_throttles import CostStatus, UserCostBurstThrottle, UserCostSustainedThrottle
from llm_gateway.rate_limiting.runner import ThrottleRunner
from llm_gateway.rate_limiting.throttles import ThrottleContext
-from llm_gateway.services.billing_period_resolver import resolve_billing_period
-from llm_gateway.services.plan_resolver import (
- POSTHOG_CODE_PRODUCT,
- PlanResolver,
- is_pro_plan,
- parse_iso_utc,
-)
+from llm_gateway.services.billing_period_resolver import parse_iso_utc, resolve_billing_period
logger = structlog.get_logger(__name__)
@@ -79,10 +74,9 @@ async def get_usage(
) -> UsageResponse:
runner: ThrottleRunner = request.app.state.throttle_runner
- (plan_info, quota_status), organization_billing_period = await asyncio.gather(
- resolve_plan_and_quota(
+ quota_status, organization_billing_period = await asyncio.gather(
+ resolve_quota(
request,
- user_id=user.user_id,
team_id=user.team_id,
product=product,
),
@@ -94,14 +88,10 @@ async def get_usage(
user=user,
product=product,
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,
code_usage_billed=quota_status.code_usage_billing_active,
- billing_period_start=plan_info.billing_period.current_period_start if plan_info.billing_period else None,
credits_exhausted=quota_status.limited,
)
- # The product's own credit bucket (resolve_plan_and_quota resolves per bucket;
+ # The product's own credit bucket (resolve_quota resolves per bucket;
# always unlimited for unbilled products), reported under the legacy `ai_credits`
# response field — clients read `ai_credits.exhausted` regardless of bucket. Run
# through the same decision as the request-path throttle: clients gate on this
@@ -130,8 +120,6 @@ async def get_usage(
billing_period_end: datetime | None = None
raw_period_end = organization_billing_period.current_period_end if organization_billing_period else None
- if raw_period_end is None and plan_info.billing_period:
- raw_period_end = plan_info.billing_period.current_period_end
if raw_period_end is not None:
try:
billing_period_end = parse_iso_utc(raw_period_end)
@@ -157,20 +145,9 @@ async def get_usage(
breakdown=quota_status.posthog_desktop_usage if product == POSTHOG_CODE_PRODUCT else None,
),
is_rate_limited=burst_status.exceeded or sustained_status.exceeded or credits_exhausted,
- is_pro=is_pro_plan(plan_info.plan_key),
+ # The seat product is retired. No caller holds a Pro seat.
+ # Older PostHog Desktop builds require this field, so it stays.
+ is_pro=False,
code_usage_subscribed=quota_status.code_usage_billing_active,
billing_period_end=billing_period_end,
)
-
-
-@usage_router.post("/{product}/invalidate-plan-cache")
-async def invalidate_plan_cache(
- product: str,
- request: Request,
- user: Annotated[AuthenticatedUser, Depends(get_authenticated_user)],
-) -> dict[str, bool]:
- if product != POSTHOG_CODE_PRODUCT:
- raise HTTPException(status_code=404, detail="Plan cache not available for this product")
- plan_resolver: PlanResolver = request.app.state.plan_resolver
- await plan_resolver.invalidate(user.user_id)
- return {"ok": True}
diff --git a/services/llm-gateway/src/llm_gateway/cli/reset_posthog_code_usage.py b/services/llm-gateway/src/llm_gateway/cli/reset_posthog_code_usage.py
index b55a22e58ec2..5a078ec225cd 100644
--- a/services/llm-gateway/src/llm_gateway/cli/reset_posthog_code_usage.py
+++ b/services/llm-gateway/src/llm_gateway/cli/reset_posthog_code_usage.py
@@ -11,7 +11,7 @@ import structlog
from redis.asyncio import Redis
from llm_gateway.config import get_settings
-from llm_gateway.services.plan_resolver import POSTHOG_CODE_PRODUCT
+from llm_gateway.products.config import POSTHOG_CODE_PRODUCT
logger = structlog.get_logger(__name__)
diff --git a/services/llm-gateway/src/llm_gateway/config.py b/services/llm-gateway/src/llm_gateway/config.py
index 285150a8c368..d2dc47f59eb0 100644
--- a/services/llm-gateway/src/llm_gateway/config.py
+++ b/services/llm-gateway/src/llm_gateway/config.py
@@ -236,7 +236,6 @@ class Settings(BaseSettings):
default_fallback_cost_usd: float = 0.01
posthog_api_base_url: str = "https://us.posthog.com"
- plan_cache_ttl: int = 900 # 15 minutes
desktop_access_gate_enabled: bool = True
desktop_access_cache_ttl: int = 60
diff --git a/services/llm-gateway/src/llm_gateway/dependencies.py b/services/llm-gateway/src/llm_gateway/dependencies.py
index 3b5e5e2532c7..11e2b7a7ea76 100644
--- a/services/llm-gateway/src/llm_gateway/dependencies.py
+++ b/services/llm-gateway/src/llm_gateway/dependencies.py
@@ -1,6 +1,5 @@
from __future__ import annotations
-import asyncio
import json
from typing import Annotated, Any
@@ -22,6 +21,7 @@ from llm_gateway.flags import evaluate_flag
from llm_gateway.products.config import (
ALLOWED_PRODUCTS,
INTERNAL_RUN_SCOPE,
+ POSTHOG_CODE_PRODUCT,
check_free_tier_model_access,
check_product_access,
get_product_config,
@@ -37,7 +37,6 @@ from llm_gateway.request_context import (
set_throttle_context,
)
from llm_gateway.services.desktop_access_resolver import DesktopAccessResolver
-from llm_gateway.services.plan_resolver import POSTHOG_CODE_PRODUCT, PlanInfo, resolve_plan_info
from llm_gateway.services.quota_resolver import QuotaResourceStatus, resolve_quota_status
logger = structlog.get_logger(__name__)
@@ -239,19 +238,17 @@ async def _extract_end_user_id_from_body(request: Request) -> str | None:
return None
-async def resolve_plan_and_quota(
+async def resolve_quota(
request: Request,
*,
- user_id: int,
team_id: int | None,
product: str,
-) -> tuple[PlanInfo, QuotaResourceStatus]:
- """Fetch plan info and (for bucket-billed products) the bucket's quota in parallel.
+) -> QuotaResourceStatus:
+ """Fetch the bucket's quota for bucket-billed products.
- Both calls are independent Django roundtrips on cache miss, so for products
- billing into a credit bucket we overlap them. Unbilled products short-circuit
- the throttle stack regardless of quota state, so we skip the resolver entirely
- rather than paying for the Redis GET (and the HTTP fallback on cache miss).
+ Unbilled products short-circuit the throttle stack regardless of quota state,
+ so we skip the resolver entirely rather than paying for the Redis GET (and the
+ HTTP fallback on cache miss).
Caveat: ``code_usage_billing_active`` rides the quota fetch, so a product
without a credit bucket always reads as unbilled — removing or repointing
@@ -259,13 +256,8 @@ async def resolve_plan_and_quota(
"""
product_config = get_product_config(product)
if product_config and product_config.credit_bucket is not None:
- plan_info, quota_status = await asyncio.gather(
- resolve_plan_info(request, user_id, product),
- resolve_quota_status(request, team_id, product_config.credit_bucket.value),
- )
- return plan_info, quota_status
- plan_info = await resolve_plan_info(request, user_id, product)
- return plan_info, QuotaResourceStatus(limited=False)
+ return await resolve_quota_status(request, team_id, product_config.credit_bucket.value)
+ return QuotaResourceStatus(limited=False)
def _format_retry_delay(seconds: int) -> str:
@@ -292,9 +284,8 @@ async def enforce_throttles(
else:
end_user_id = await _extract_end_user_id_from_body(request)
- plan_info, quota_status = await resolve_plan_and_quota(
+ quota_status = await resolve_quota(
request,
- user_id=user.user_id,
team_id=user.team_id,
product=product,
)
@@ -353,11 +344,7 @@ async def enforce_throttles(
product=product,
request_id=get_request_id() or None,
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,
code_usage_billed=quota_status.code_usage_billing_active,
- billing_period_start=plan_info.billing_period.current_period_start if plan_info.billing_period else None,
credits_exhausted=quota_status.limited,
sandbox_task_id=user.sandbox_task_id,
)
diff --git a/services/llm-gateway/src/llm_gateway/main.py b/services/llm-gateway/src/llm_gateway/main.py
index feb2a5175cfb..f4cde92d1eac 100644
--- a/services/llm-gateway/src/llm_gateway/main.py
+++ b/services/llm-gateway/src/llm_gateway/main.py
@@ -42,7 +42,6 @@ from llm_gateway.rate_limiting.runner import ThrottleRunner
from llm_gateway.request_context import RequestContext, set_request_context
from llm_gateway.services.billing_period_resolver import BillingPeriodResolver
from llm_gateway.services.desktop_access_resolver import DesktopAccessResolver
-from llm_gateway.services.plan_resolver import PlanResolver
from llm_gateway.services.quota_resolver import QuotaResolver
@@ -228,10 +227,6 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None]:
max_keepalive_connections=settings.desktop_access_max_connections,
)
)
- app.state.plan_resolver = PlanResolver(
- redis=app.state.redis,
- http_client=app.state.http_client,
- )
app.state.desktop_access_resolver = DesktopAccessResolver(
redis=app.state.redis,
http_client=app.state.desktop_access_http_client,
diff --git a/services/llm-gateway/src/llm_gateway/products/config.py b/services/llm-gateway/src/llm_gateway/products/config.py
index 5263d2aae6d0..fe44ce706f82 100644
--- a/services/llm-gateway/src/llm_gateway/products/config.py
+++ b/services/llm-gateway/src/llm_gateway/products/config.py
@@ -57,6 +57,7 @@ class ProductConfig:
BEDROCK_MODELS = BEDROCK_MODEL_IDS
# OAuth application IDs per region
+POSTHOG_CODE_PRODUCT = "posthog_code"
POSTHOG_CODE_US_APP_ID = "019a3066-4aa2-0000-ca70-48ecdcc519cf"
POSTHOG_CODE_EU_APP_ID = "019a3067-5be7-0000-33c7-c6743eb59a79"
POSTHOG_CODE_DEV_APP_ID = "019ebb47-c750-0000-e1ea-723a6ff112d3"
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 d1376734bb43..851e19c752cd 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
@@ -8,7 +8,7 @@ import structlog
from redis.asyncio import Redis
from llm_gateway.config import DEFAULT_USER_COST_LIMIT, get_settings
-from llm_gateway.products.config import resolve_cost_key
+from llm_gateway.products.config import POSTHOG_CODE_PRODUCT, resolve_cost_key
if TYPE_CHECKING:
from llm_gateway.config import UserCostLimit
@@ -20,7 +20,6 @@ from llm_gateway.rate_limiting.throttles import (
get_rate_limit_multiplier,
is_usage_unlimited,
)
-from llm_gateway.services.plan_resolver import POSTHOG_CODE_PRODUCT
logger = structlog.get_logger(__name__)
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 62b435fce778..3ce38c58ed9a 100644
--- a/services/llm-gateway/src/llm_gateway/rate_limiting/throttles.py
+++ b/services/llm-gateway/src/llm_gateway/rate_limiting/throttles.py
@@ -45,11 +45,7 @@ class ThrottleContext:
product: str
request_id: str | None = None
end_user_id: str | None = None
- plan_key: str | None = None
- seat_created_at: str | None = None
- seat_missing: bool = False
code_usage_billed: bool = False
- billing_period_start: str | None = None
credits_exhausted: bool = False
# Set only for sandbox-run tokens; see AuthenticatedUser.sandbox_task_id.
sandbox_task_id: str | None = None
diff --git a/services/llm-gateway/src/llm_gateway/services/billing_period_resolver.py b/services/llm-gateway/src/llm_gateway/services/billing_period_resolver.py
index ed078f99b534..38b45f2eb7a0 100644
--- a/services/llm-gateway/src/llm_gateway/services/billing_period_resolver.py
+++ b/services/llm-gateway/src/llm_gateway/services/billing_period_resolver.py
@@ -2,6 +2,7 @@ from __future__ import annotations
import json
from dataclasses import dataclass
+from datetime import UTC, datetime
from typing import TYPE_CHECKING
import httpx
@@ -23,6 +24,11 @@ class OrganizationBillingPeriod:
current_period_end: str
+def parse_iso_utc(value: str) -> datetime:
+ parsed = datetime.fromisoformat(value)
+ return parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=UTC)
+
+
def _redis_key(team_id: int) -> str:
return f"billing_period:team:{team_id}"
diff --git a/services/llm-gateway/src/llm_gateway/services/plan_resolver.py b/services/llm-gateway/src/llm_gateway/services/plan_resolver.py
deleted file mode 100644
index 03a16edeb3d8..000000000000
--- a/services/llm-gateway/src/llm_gateway/services/plan_resolver.py
+++ /dev/null
@@ -1,231 +0,0 @@
-"""Resolves a user's PostHog Desktop plan via the PostHog API seats endpoint.
-
-Calls ``GET /api/seats/me/?product_key=posthog_code`` on the PostHog API,
-forwarding the user's auth token. The Django SeatViewSet handles billing
-JWT construction and proxies to the billing service.
-
-Results are cached in Redis to avoid hitting the API on every request.
-"""
-
-from __future__ import annotations
-
-import json
-from dataclasses import dataclass
-from datetime import UTC, datetime
-from typing import TYPE_CHECKING
-
-import structlog
-
-from llm_gateway.auth.service import upstream_auth_header
-from llm_gateway.config import get_settings
-
-if TYPE_CHECKING:
- import httpx
- from fastapi import Request
- from redis.asyncio import Redis
-
-logger = structlog.get_logger(__name__)
-
-POSTHOG_CODE_PRODUCT = "posthog_code"
-PLAN_CACHE_PREFIX = f"plan:{POSTHOG_CODE_PRODUCT}"
-# Duplicated in products/tasks/backend/seat_api.py
-PRO_PLAN_PREFIXES = ("posthog-code-200", "posthog-code-pro-")
-
-
-@dataclass
-class BillingPeriod:
- current_period_start: str
- current_period_end: str
- interval: str
-
-
-@dataclass
-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:
- return f"{PLAN_CACHE_PREFIX}:{user_id}"
-
-
-def is_pro_plan(plan_key: str | None) -> bool:
- if not plan_key:
- return False
- return any(plan_key.startswith(p) for p in PRO_PLAN_PREFIXES)
-
-
-def parse_iso_utc(value: str) -> datetime:
- parsed = datetime.fromisoformat(value)
- return parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=UTC)
-
-
-def get_billing_period_number(
- seat_created_at: str | None,
- period_days: int = 30,
- billing_period_start: str | None = None,
-) -> int:
- anchor = billing_period_start or seat_created_at
- if not anchor:
- return 0
- try:
- created = parse_iso_utc(anchor)
- elapsed = datetime.now(tz=UTC) - created
- return max(0, elapsed.days // period_days)
- except (ValueError, TypeError):
- return 0
-
-
-def _parse_billing_period(raw: object) -> BillingPeriod | None:
- if not isinstance(raw, dict):
- return None
- try:
- return BillingPeriod(
- current_period_start=raw["current_period_start"],
- current_period_end=raw["current_period_end"],
- interval=raw["interval"],
- )
- except (KeyError, TypeError):
- return None
-
-
-async def resolve_plan_info(
- request: Request,
- user_id: int,
- product: str,
-) -> PlanInfo:
- """Resolve plan info, returning safe defaults on failure."""
- if product != POSTHOG_CODE_PRODUCT:
- return PlanInfo(plan_key=None, seat_created_at=None)
-
- plan_resolver: PlanResolver = request.app.state.plan_resolver
- # upstream_auth_header mirrors extract_token's precedence (x-api-key wins).
- # Forwarding only Authorization would resolve no plan for x-api-key callers,
- # silently disabling every plan-conditioned control (usage-based cost caps,
- # the plan-scoped credit-bucket exemption) for a token placement auth accepts.
- auth_header = upstream_auth_header(request)
- try:
- return await plan_resolver.get_plan(
- user_id=user_id,
- auth_header=auth_header,
- )
- except Exception:
- logger.warning("plan_resolve_failed", user_id=user_id)
- return PlanInfo(plan_key=None, seat_created_at=None)
-
-
-class PlanResolver:
- def __init__(
- self,
- redis: Redis[bytes] | None,
- http_client: httpx.AsyncClient,
- ):
- self._redis = redis
- self._http = http_client
-
- async def invalidate(self, user_id: int) -> None:
- if not self._redis:
- return
- try:
- await self._redis.delete(_redis_key(user_id))
- except Exception:
- logger.debug("plan_cache_invalidate_failed", user_id=user_id)
-
- async def get_plan(self, user_id: int, auth_header: str) -> PlanInfo:
- """Return the user's plan info, using cache when available."""
- if not auth_header:
- return PlanInfo(plan_key=None, seat_created_at=None)
-
- cached = await self._get_cached(user_id)
- if cached is not None:
- return cached
-
- try:
- 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, 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:
- if not self._redis:
- return None
- try:
- val = await self._redis.get(_redis_key(user_id))
- if val is not None:
- data = json.loads(val.decode())
- plan_key = data.get("plan_key") or None
- seat_created_at = data.get("created_at")
- billing_period = _parse_billing_period(data.get("billing_period"))
- return PlanInfo(
- 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)
- return None
-
- async def _set_cached(
- self,
- user_id: int,
- 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,
- "seat_missing": seat_missing,
- }
- if billing_period:
- payload["billing_period"] = {
- "current_period_start": billing_period.current_period_start,
- "current_period_end": billing_period.current_period_end,
- "interval": billing_period.interval,
- }
- data = json.dumps(payload)
- await self._redis.set(_redis_key(user_id), data, ex=ttl)
- 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, 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, 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, False
-
- url = f"{settings.posthog_api_base_url.rstrip('/')}/api/seats/me/"
- resp = await self._http.get(
- url,
- params={"product_key": POSTHOG_CODE_PRODUCT, "best": "true"},
- headers={"Authorization": auth_header},
- timeout=2.0,
- )
- if resp.status_code == 404:
- 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, False
diff --git a/services/llm-gateway/src/llm_gateway/services/quota_resolver.py b/services/llm-gateway/src/llm_gateway/services/quota_resolver.py
index d146eba5e7c0..c358d7382375 100644
--- a/services/llm-gateway/src/llm_gateway/services/quota_resolver.py
+++ b/services/llm-gateway/src/llm_gateway/services/quota_resolver.py
@@ -1,6 +1,6 @@
"""Resolves a team's quota state via the PostHog API quota_limits endpoint.
-Mirrors :mod:`llm_gateway.services.plan_resolver` — forwards the caller's
+Forwards the caller's
credentials to ``GET /api/projects/{team_id}/quota_limits/`` and
caches the result per team-and-resource in the gateway's own Redis. The
resource key is a Django ``QuotaResource`` value (matches ``CreditBucket``
diff --git a/services/llm-gateway/tests/conftest.py b/services/llm-gateway/tests/conftest.py
index 611a6e34fe9d..ee598e0865e0 100644
--- a/services/llm-gateway/tests/conftest.py
+++ b/services/llm-gateway/tests/conftest.py
@@ -19,7 +19,6 @@ from llm_gateway.rate_limiting.runner import ThrottleRunner
from llm_gateway.rate_limiting.throttles import Throttle
from llm_gateway.request_context import request_context_var
from llm_gateway.services.desktop_access_resolver import DesktopAccessDecision
-from llm_gateway.services.plan_resolver import PlanInfo
from llm_gateway.services.quota_resolver import QuotaResourceStatus
@@ -57,8 +56,6 @@ def create_test_app(
app.state.redis = None
app.state.throttle_runner = ThrottleRunner(throttles=throttles if throttles is not None else default_throttles)
app.state.http_client = MagicMock()
- app.state.plan_resolver = AsyncMock()
- app.state.plan_resolver.get_plan = AsyncMock(return_value=PlanInfo(plan_key=None, seat_created_at=None))
app.state.billing_period_resolver = AsyncMock()
app.state.billing_period_resolver.get_period = AsyncMock(return_value=None)
app.state.desktop_access_resolver = AsyncMock()
diff --git a/services/llm-gateway/tests/test_billable_credits_throttle.py b/services/llm-gateway/tests/test_billable_credits_throttle.py
index 4f839f2760f4..db85173fe3ea 100644
--- a/services/llm-gateway/tests/test_billable_credits_throttle.py
+++ b/services/llm-gateway/tests/test_billable_credits_throttle.py
@@ -23,16 +23,12 @@ def _make_context(
product: str,
*,
credits_exhausted: bool = False,
- plan_key: str | None = None,
- seat_missing: bool = False,
code_usage_billed: bool = False,
) -> ThrottleContext:
return ThrottleContext(
user=_make_user(),
product=product,
credits_exhausted=credits_exhausted,
- plan_key=plan_key,
- seat_missing=seat_missing,
code_usage_billed=code_usage_billed,
)
@@ -63,32 +59,24 @@ class TestBillableCreditThrottle:
@pytest.mark.asyncio
@pytest.mark.parametrize(
- ("seat_missing", "code_usage_billed"),
+ "code_usage_billed",
[
- # Seatless in a paying org: the org's billing limit is the only
- # ceiling (the per-user cap is lifted) - exhaustion must block, or
- # usage runs past the org's configured limit.
- (True, True),
- # Seatless in a non-paying org: the free plan's monthly allocation
- # surfaces the same way and must block the same way.
- (True, False),
- # Every generation is counted into the bucket regardless of seat
- # state, so a seat-based carve-out would let the exempted callers
- # burn past the limit their own spend is filling.
- (False, True),
- (False, False),
+ # Paying org: the org's billing limit is the only ceiling (the
+ # per-user cap is lifted) - exhaustion must block, or usage runs
+ # past the org's configured limit.
+ True,
+ # Non-paying org: the free plan's monthly allocation surfaces the
+ # same way and must block the same way.
+ False,
],
)
- async def test_bucket_blocks_regardless_of_seat_or_billing_state(
- self, seat_missing: bool, code_usage_billed: bool
- ) -> None:
+ async def test_bucket_blocks_regardless_of_billing_state(self, code_usage_billed: bool) -> None:
throttle = BillableCreditThrottle()
result = await throttle.allow_request(
_make_context(
product="posthog_code",
credits_exhausted=True,
- seat_missing=seat_missing,
code_usage_billed=code_usage_billed,
)
)
diff --git a/services/llm-gateway/tests/test_cost_throttles.py b/services/llm-gateway/tests/test_cost_throttles.py
index 89c631f468bd..7eea91ec98c7 100644
--- a/services/llm-gateway/tests/test_cost_throttles.py
+++ b/services/llm-gateway/tests/test_cost_throttles.py
@@ -40,11 +40,7 @@ def make_context(
user: AuthenticatedUser | None = None,
product: str = "posthog_code",
end_user_id: str | None = None,
- plan_key: str | None = "posthog-code-200-20260301",
- seat_created_at: str | None = None,
- seat_missing: bool = False,
code_usage_billed: bool = False,
- billing_period_start: str | None = None,
sandbox_task_id: str | None = None,
) -> ThrottleContext:
user = user or make_user()
@@ -54,11 +50,7 @@ def make_context(
user=user,
product=product,
end_user_id=end_user_id,
- plan_key=plan_key,
- seat_created_at=seat_created_at,
- seat_missing=seat_missing,
code_usage_billed=code_usage_billed,
- billing_period_start=billing_period_start,
sandbox_task_id=sandbox_task_id,
)
@@ -539,27 +531,6 @@ class TestStaffUnlimitedUsage:
assert status.limit_usd == float("inf")
get_settings.cache_clear()
- @pytest.mark.asyncio
- async def test_free_plan_staff_still_unlimited(self) -> None:
- # The case that bit staff before: a staff member on the free plan was
- # pinned to the (multiplied) free-plan cap rather than treated as unlimited.
- from datetime import UTC, datetime, timedelta
-
- get_settings.cache_clear()
- from llm_gateway.rate_limiting.cost_throttles import UserCostSustainedThrottle
-
- throttle = UserCostSustainedThrottle(redis=None)
- context = make_context(
- user=make_user(is_staff=True),
- product="background_agents",
- plan_key="posthog-code-free-20260301",
- seat_created_at=(datetime.now(tz=UTC) - timedelta(days=5)).isoformat(),
- )
-
- await throttle.record_cost(context, 100_000.0)
- assert (await throttle.allow_request(context)).allowed is True
- get_settings.cache_clear()
-
@pytest.mark.asyncio
async def test_non_staff_still_enforced(self) -> None:
get_settings.cache_clear()
@@ -1196,7 +1167,7 @@ class TestPostHogCodeUserThrottling:
@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)
+ context = make_context(product="posthog_code")
await throttle.record_cost(context, 600.0)
@@ -1207,11 +1178,11 @@ class TestPostHogCodeUserThrottling:
assert status.limit_usd == float("inf")
@pytest.mark.asyncio
- async def test_non_code_product_ignores_plan(self) -> None:
+ async def test_non_code_product_allows_normal_spend(self) -> None:
from llm_gateway.rate_limiting.cost_throttles import UserCostBurstThrottle
throttle = UserCostBurstThrottle(redis=None)
- context = make_context(product="wizard", plan_key=None)
+ context = make_context(product="wizard")
await throttle.record_cost(context, 50.0)
result = await throttle.allow_request(context)
diff --git a/services/llm-gateway/tests/test_dependencies.py b/services/llm-gateway/tests/test_dependencies.py
index 73bfaca697d3..c9ebdf63ea97 100644
--- a/services/llm-gateway/tests/test_dependencies.py
+++ b/services/llm-gateway/tests/test_dependencies.py
@@ -25,7 +25,7 @@ from llm_gateway.dependencies import (
get_model_from_request,
get_provider_from_request,
get_request_json,
- resolve_plan_and_quota,
+ resolve_quota,
)
from llm_gateway.products.config import POSTHOG_CODE_US_APP_ID, SIGNALS_DEV_APP_ID
from llm_gateway.rate_limiting.cost_throttles import SandboxTaskCostThrottle
@@ -35,7 +35,6 @@ from llm_gateway.services.desktop_access_resolver import (
DesktopAccessReason,
DesktopAccessStatus,
)
-from llm_gateway.services.plan_resolver import PlanInfo
from llm_gateway.services.quota_resolver import QuotaResourceStatus
@@ -287,19 +286,14 @@ class TestEnforceThrottles:
assert context.end_user_id is None
-class TestResolvePlanAndQuota:
+class TestResolveQuota:
"""The quota resolver roundtrip runs for bucket-billed products (against the
product's own bucket) and is skipped entirely for unbilled ones."""
async def _run(self, product: str) -> tuple:
- plan_info = PlanInfo(plan_key="pro", seat_created_at=None)
- plan_mock = AsyncMock(return_value=plan_info)
quota_mock = AsyncMock(return_value=QuotaResourceStatus(limited=True))
- with (
- patch("llm_gateway.dependencies.resolve_plan_info", plan_mock),
- patch("llm_gateway.dependencies.resolve_quota_status", quota_mock),
- ):
- result = await resolve_plan_and_quota(_make_request(), user_id=1, team_id=42, product=product)
+ with patch("llm_gateway.dependencies.resolve_quota_status", quota_mock):
+ result = await resolve_quota(_make_request(), team_id=42, product=product)
return result, quota_mock
@pytest.mark.asyncio
@@ -308,7 +302,7 @@ class TestResolvePlanAndQuota:
[("slack_app", "ai_credits"), ("posthog_code", "posthog_code_credits")],
)
async def test_bucket_billed_product_resolves_its_own_bucket(self, product: str, expected_resource: str) -> None:
- (_, quota_status), quota_mock = await self._run(product)
+ quota_status, quota_mock = await self._run(product)
quota_mock.assert_awaited_once()
assert quota_mock.call_args.args[2] == expected_resource
@@ -317,7 +311,7 @@ class TestResolvePlanAndQuota:
@pytest.mark.asyncio
async def test_unbilled_product_skips_quota_resolver(self) -> None:
# wizard is unbilled — it shouldn't pay for the quota resolver roundtrip.
- (_, quota_status), quota_mock = await self._run("wizard")
+ quota_status, quota_mock = await self._run("wizard")
quota_mock.assert_not_awaited()
assert quota_status.limited is False
@@ -416,8 +410,8 @@ 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))),
+ "llm_gateway.dependencies.resolve_quota",
+ AsyncMock(return_value=QuotaResourceStatus(limited=False, code_usage_billing_active=True)),
):
yield
@@ -468,8 +462,8 @@ 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))),
+ "llm_gateway.dependencies.resolve_quota",
+ AsyncMock(return_value=QuotaResourceStatus(limited=False, code_usage_billing_active=True)),
):
yield
@@ -533,13 +527,8 @@ class TestBasetenExclusiveModelGateWiring:
with (
patch(
- "llm_gateway.dependencies.resolve_plan_and_quota",
- AsyncMock(
- return_value=(
- MagicMock(),
- QuotaResourceStatus(limited=False, code_usage_billing_active=False),
- )
- ),
+ "llm_gateway.dependencies.resolve_quota",
+ AsyncMock(return_value=QuotaResourceStatus(limited=False, code_usage_billing_active=False)),
),
patch("llm_gateway.dependencies.ensure_costs_fresh"),
patch("llm_gateway.dependencies.evaluate_flag", AsyncMock(return_value=flag_result)),
diff --git a/services/llm-gateway/tests/test_plan_resolver.py b/services/llm-gateway/tests/test_plan_resolver.py
deleted file mode 100644
index dddf40896076..000000000000
--- a/services/llm-gateway/tests/test_plan_resolver.py
+++ /dev/null
@@ -1,322 +0,0 @@
-from datetime import UTC, datetime, timedelta
-from unittest.mock import AsyncMock, MagicMock, patch
-
-import pytest
-
-from llm_gateway.services.plan_resolver import (
- PlanInfo,
- PlanResolver,
- get_billing_period_number,
- is_pro_plan,
- resolve_plan_info,
-)
-
-
-class TestIsProPlan:
- @pytest.mark.parametrize(
- "plan_key,expected",
- [
- ("posthog-code-200-20260301", True),
- ("posthog-code-200-20260501", True),
- ("posthog-code-pro-200-20260301", True),
- ("posthog-code-pro-0-20260422", True),
- ("posthog-code-free-20260301", False),
- ("posthog-code-free-20260501", False),
- ("some-other-plan", False),
- (None, False),
- ("", False),
- ],
- )
- def test_is_pro_plan(self, plan_key: str | None, expected: bool) -> None:
- assert is_pro_plan(plan_key) is expected
-
-
-class TestGetBillingPeriodNumber:
- def test_none_returns_zero(self) -> None:
- assert get_billing_period_number(None) == 0
-
- def test_invalid_date_returns_zero(self) -> None:
- assert get_billing_period_number("not-a-date") == 0
-
- def test_today_returns_zero(self) -> None:
- now = datetime.now(tz=UTC).isoformat()
- assert get_billing_period_number(now) == 0
-
- def test_five_days_ago_returns_zero(self) -> None:
- created = (datetime.now(tz=UTC) - timedelta(days=5)).isoformat()
- assert get_billing_period_number(created) == 0
-
- def test_thirty_days_returns_one(self) -> None:
- created = (datetime.now(tz=UTC) - timedelta(days=30)).isoformat()
- assert get_billing_period_number(created) == 1
-
- def test_sixty_days_returns_two(self) -> None:
- created = (datetime.now(tz=UTC) - timedelta(days=60)).isoformat()
- assert get_billing_period_number(created) == 2
-
- def test_custom_period_days(self) -> None:
- created = (datetime.now(tz=UTC) - timedelta(days=15)).isoformat()
- assert get_billing_period_number(created, period_days=7) == 2
-
- def test_just_under_boundary(self) -> None:
- created = (datetime.now(tz=UTC) - timedelta(days=29, hours=23)).isoformat()
- assert get_billing_period_number(created) == 0
-
- def test_billing_period_start_overrides_seat_created_at(self) -> None:
- old_seat = (datetime.now(tz=UTC) - timedelta(days=35)).isoformat()
- recent_period = (datetime.now(tz=UTC) - timedelta(days=5)).isoformat()
- assert get_billing_period_number(old_seat, billing_period_start=recent_period) == 0
-
- def test_billing_period_start_none_falls_back_to_seat_created_at(self) -> None:
- old_seat = (datetime.now(tz=UTC) - timedelta(days=35)).isoformat()
- assert get_billing_period_number(old_seat, billing_period_start=None) == 1
-
-
-class TestPlanResolver:
- @pytest.fixture
- def resolver(self) -> PlanResolver:
- return PlanResolver(redis=None, http_client=AsyncMock())
-
- @pytest.fixture
- def resolver_with_redis(self) -> PlanResolver:
- redis = AsyncMock()
- redis.get = AsyncMock(return_value=None)
- redis.set = AsyncMock()
- return PlanResolver(redis=redis, http_client=AsyncMock())
-
- async def test_returns_none_plan_when_no_api_url(self, resolver: PlanResolver) -> None:
- with patch("llm_gateway.services.plan_resolver.get_settings") as mock_settings:
- mock_settings.return_value.posthog_api_base_url = ""
- 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]
- result = await resolver_with_redis.get_plan(user_id=1, auth_header="Bearer phx_test")
- assert result.plan_key == "posthog-code-200-20260301"
-
- async def test_cached_null_plan_returns_none_plan_key(self, resolver_with_redis: PlanResolver) -> None:
- import json
-
- 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]
- 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
-
- 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]
- 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
-
- async def test_fetches_from_api_and_caches(self, resolver_with_redis: PlanResolver) -> None:
- created_at = datetime.now(tz=UTC).isoformat()
- mock_resp = MagicMock()
- mock_resp.status_code = 200
- mock_resp.json.return_value = {
- "plan_key": "posthog-code-pro-200-20260301",
- "created_at": created_at,
- "billing_period": {
- "current_period_start": "2026-04-01T00:00:00+00:00",
- "current_period_end": "2026-05-01T00:00:00+00:00",
- "interval": "month",
- },
- }
- mock_resp.raise_for_status = MagicMock()
- resolver_with_redis._http.get = AsyncMock(return_value=mock_resp) # type: ignore[method-assign]
-
- 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
- result = await resolver_with_redis.get_plan(user_id=1, auth_header="Bearer phx_test")
-
- assert result.plan_key == "posthog-code-pro-200-20260301"
- assert result.billing_period is not None
- assert result.billing_period.current_period_start == "2026-04-01T00:00:00+00:00"
- assert result.billing_period.interval == "month"
- assert resolver_with_redis._redis is not None
- resolver_with_redis._redis.set.assert_called_once() # type: ignore[attr-defined]
-
- resolver_with_redis._http.get.assert_called_once_with(
- "https://app.posthog.com/api/seats/me/",
- params={"product_key": "posthog_code", "best": "true"},
- headers={"Authorization": "Bearer phx_test"},
- timeout=2.0,
- )
-
- async def test_fetches_from_api_without_billing_period(self, resolver_with_redis: PlanResolver) -> None:
- mock_resp = MagicMock()
- 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]
-
- 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
- result = await resolver_with_redis.get_plan(user_id=1, auth_header="Bearer phx_test")
-
- assert result.plan_key == "posthog-code-200-20260301"
- assert result.billing_period is None
-
- async def test_forwards_auth_header(self, resolver: PlanResolver) -> None:
- mock_resp = MagicMock()
- 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]
-
- 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.get_plan(user_id=1, auth_header="Bearer phx_mysecretkey")
-
- resolver._http.get.assert_called_once()
- call_kwargs = resolver._http.get.call_args
- assert call_kwargs.kwargs["headers"]["Authorization"] == "Bearer phx_mysecretkey"
-
- 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]
-
- 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
- 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]
-
- 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]
- 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]
-
- 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
- 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="")
- assert result.plan_key is None
- resolver._http.get.assert_not_called() # type: ignore[attr-defined]
-
- async def test_cached_plan_with_billing_period(self, resolver_with_redis: PlanResolver) -> None:
- import json
-
- cached = json.dumps(
- {
- "plan_key": "posthog-code-pro-200-20260301",
- "created_at": None,
- "billing_period": {
- "current_period_start": "2026-04-01T00:00:00+00:00",
- "current_period_end": "2026-05-01T00:00:00+00:00",
- "interval": "month",
- },
- }
- )
- assert resolver_with_redis._redis is not None
- resolver_with_redis._redis.get = AsyncMock(return_value=cached.encode()) # type: ignore[method-assign]
- 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"
- assert result.billing_period.interval == "month"
-
- async def test_cached_plan_without_billing_period(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]
- 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]
-
- 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
- result = await resolver_with_redis.get_plan(user_id=1, auth_header="Bearer phx_test")
-
- assert result.plan_key is None
- assert resolver_with_redis._redis is not None
- resolver_with_redis._redis.set.assert_not_called() # type: ignore[attr-defined]
-
-
-class TestResolvePlanInfoCredentialForwarding:
- """Credential forwarding must mirror extract_token: either header
- authenticates, so either header must reach plan resolution — otherwise
- x-api-key callers resolve no plan, silently disabling every
- plan-conditioned control (free vs pro cost caps, the seat-scoped
- credit-bucket exemption)."""
-
- def _make_request(self, headers: dict[str, str]) -> MagicMock:
- from starlette.datastructures import Headers
-
- request = MagicMock()
- request.headers = Headers(headers)
- resolver = MagicMock()
- resolver.get_plan = AsyncMock(
- return_value=PlanInfo(plan_key="posthog-code-pro-200-20260301", seat_created_at=None)
- )
- request.app.state.plan_resolver = resolver
- return request
-
- @pytest.mark.asyncio
- async def test_forwards_authorization_header(self) -> None:
- request = self._make_request({"Authorization": "Bearer phx_test"})
- result = await resolve_plan_info(request, user_id=1, product="posthog_code")
- assert result.plan_key == "posthog-code-pro-200-20260301"
- assert request.app.state.plan_resolver.get_plan.await_args.kwargs["auth_header"] == "Bearer phx_test"
-
- @pytest.mark.asyncio
- async def test_forwards_x_api_key_as_bearer(self) -> None:
- request = self._make_request({"x-api-key": " phx_test "})
- result = await resolve_plan_info(request, user_id=1, product="posthog_code")
- assert result.plan_key == "posthog-code-pro-200-20260301"
- assert request.app.state.plan_resolver.get_plan.await_args.kwargs["auth_header"] == "Bearer phx_test"
-
- @pytest.mark.asyncio
- async def test_x_api_key_takes_precedence_over_authorization(self) -> None:
- # Matches extract_token — the token that authenticated the request is
- # the one whose plan gets resolved.
- request = self._make_request({"x-api-key": "phx_from_api_key", "Authorization": "Bearer phx_from_auth"})
- await resolve_plan_info(request, user_id=1, product="posthog_code")
- assert request.app.state.plan_resolver.get_plan.await_args.kwargs["auth_header"] == "Bearer phx_from_api_key"
diff --git a/services/llm-gateway/tests/test_usage.py b/services/llm-gateway/tests/test_usage.py
index 47e6e597b7e5..e99a5ee69393 100644
--- a/services/llm-gateway/tests/test_usage.py
+++ b/services/llm-gateway/tests/test_usage.py
@@ -13,7 +13,6 @@ from llm_gateway.rate_limiting.cost_throttles import (
UserCostSustainedThrottle,
)
from llm_gateway.services.billing_period_resolver import OrganizationBillingPeriod
-from llm_gateway.services.plan_resolver import BillingPeriod, PlanInfo
from llm_gateway.services.quota_resolver import QuotaResourceStatus
from tests.conftest import create_test_app
@@ -109,17 +108,12 @@ class TestUsageEndpoint:
for key in bucket:
assert "usd" not in key.lower(), f"Bucket field {key!r} leaks USD"
- def test_includes_billing_period_end_for_pro_plan(self, authenticated_usage_client: TestClient) -> None:
+ def test_includes_billing_period_end_from_org_period(self, authenticated_usage_client: TestClient) -> None:
app = authenticated_usage_client.app
- app.state.plan_resolver.get_plan = AsyncMock(
- return_value=PlanInfo(
- plan_key="posthog-code-200-20260301",
- seat_created_at="2026-01-01T00:00:00+00:00",
- billing_period=BillingPeriod(
- current_period_start="2026-05-01T00:00:00+00:00",
- current_period_end="2026-05-31T00:00:00+00:00",
- interval="month",
- ),
+ app.state.billing_period_resolver.get_period = AsyncMock(
+ return_value=OrganizationBillingPeriod(
+ current_period_start="2026-05-01T00:00:00+00:00",
+ current_period_end="2026-05-31T00:00:00+00:00",
)
)
@@ -132,19 +126,8 @@ class TestUsageEndpoint:
assert data["billing_period_end"] is not None
assert data["billing_period_end"].startswith("2026-05-31")
- def test_org_usage_billing_period_wins_over_seat_period(self, authenticated_usage_client: TestClient) -> None:
+ def test_org_usage_billing_period_reported(self, authenticated_usage_client: TestClient) -> None:
app = authenticated_usage_client.app
- app.state.plan_resolver.get_plan = AsyncMock(
- return_value=PlanInfo(
- plan_key="posthog-code-200-20260301",
- seat_created_at="2026-01-01T00:00:00+00:00",
- billing_period=BillingPeriod(
- current_period_start="2026-07-16T00:00:00Z",
- current_period_end="2026-08-16T00:00:00Z",
- interval="month",
- ),
- )
- )
app.state.billing_period_resolver.get_period = AsyncMock(
return_value=OrganizationBillingPeriod(
current_period_start="2026-07-09T00:00:00Z",
@@ -170,15 +153,10 @@ class TestUsageEndpoint:
def test_billing_period_end_normalises_naive_iso_to_utc(self, authenticated_usage_client: TestClient) -> None:
app = authenticated_usage_client.app
- app.state.plan_resolver.get_plan = AsyncMock(
- return_value=PlanInfo(
- plan_key="posthog-code-200-20260301",
- seat_created_at="2026-01-01T00:00:00+00:00",
- billing_period=BillingPeriod(
- current_period_start="2026-05-01T00:00:00",
- current_period_end="2026-05-31T00:00:00",
- interval="month",
- ),
+ app.state.billing_period_resolver.get_period = AsyncMock(
+ return_value=OrganizationBillingPeriod(
+ current_period_start="2026-05-01T00:00:00",
+ current_period_end="2026-05-31T00:00:00",
)
)
@@ -195,15 +173,10 @@ class TestUsageEndpoint:
def test_billing_period_end_null_when_unparseable(self, authenticated_usage_client: TestClient) -> None:
app = authenticated_usage_client.app
- app.state.plan_resolver.get_plan = AsyncMock(
- return_value=PlanInfo(
- plan_key="posthog-code-200-20260301",
- seat_created_at="2026-01-01T00:00:00+00:00",
- billing_period=BillingPeriod(
- current_period_start="2026-05-01T00:00:00+00:00",
- current_period_end="not-a-real-date",
- interval="month",
- ),
+ app.state.billing_period_resolver.get_period = AsyncMock(
+ return_value=OrganizationBillingPeriod(
+ current_period_start="2026-05-01T00:00:00+00:00",
+ current_period_end="not-a-real-date",
)
)
@@ -216,12 +189,7 @@ class TestUsageEndpoint:
assert response.json()["billing_period_end"] is None
assert any(log.get("event") == "usage.billing_period_end_unparseable" for log in logs)
- def test_billing_period_end_null_for_free_plan(self, authenticated_usage_client: TestClient) -> None:
- app = authenticated_usage_client.app
- app.state.plan_resolver.get_plan = AsyncMock(
- return_value=PlanInfo(plan_key=None, seat_created_at="2026-01-01T00:00:00+00:00")
- )
-
+ def test_billing_period_end_null_without_org_period(self, authenticated_usage_client: TestClient) -> None:
response = authenticated_usage_client.get(
"/v1/usage/posthog_code",
headers={"Authorization": "Bearer phx_test"},
@@ -229,54 +197,17 @@ class TestUsageEndpoint:
assert response.status_code == 200
assert response.json()["billing_period_end"] is None
- @pytest.mark.parametrize(
- "plan_key,expected_is_pro",
- [
- ("posthog-code-200-20260301", True),
- ("posthog-code-free-20260301", False),
- (None, False),
- ],
- )
- def test_is_pro_reflects_plan_key(
- self, authenticated_usage_client: TestClient, plan_key: str | None, expected_is_pro: bool
- ) -> None:
- app = authenticated_usage_client.app
- app.state.plan_resolver.get_plan = AsyncMock(
- return_value=PlanInfo(plan_key=plan_key, seat_created_at="2026-01-01T00:00:00+00:00")
- )
-
- response = authenticated_usage_client.get(
- "/v1/usage/posthog_code",
- headers={"Authorization": "Bearer phx_test"},
- )
- assert response.status_code == 200
- assert response.json()["is_pro"] is expected_is_pro
-
- def test_returns_free_limits_for_free_plan_with_seat(self, authenticated_usage_client: TestClient) -> None:
- app = authenticated_usage_client.app
- app.state.plan_resolver.get_plan = AsyncMock(
- return_value=PlanInfo(plan_key=None, seat_created_at="2026-01-01T00:00:00+00:00")
- )
-
+ def test_is_pro_always_false(self, authenticated_usage_client: TestClient) -> None:
+ # The seat product is retired. No caller holds a Pro seat.
+ # The field stays until older Desktop builds age out.
response = authenticated_usage_client.get(
"/v1/usage/posthog_code",
headers={"Authorization": "Bearer phx_test"},
)
assert response.status_code == 200
- data = response.json()
-
- assert data["burst"]["used_percent"] == 0
- assert data["sustained"]["used_percent"] == 0
-
- def test_old_free_user_still_gets_limits(self, authenticated_usage_client: TestClient) -> None:
- app = authenticated_usage_client.app
- app.state.plan_resolver.get_plan = AsyncMock(
- return_value=PlanInfo(
- plan_key="posthog-code-free-20260301",
- seat_created_at="2025-01-01T00:00:00+00:00",
- )
- )
+ assert response.json()["is_pro"] is False
+ def test_returns_limits_for_every_caller(self, authenticated_usage_client: TestClient) -> None:
response = authenticated_usage_client.get(
"/v1/usage/posthog_code",
headers={"Authorization": "Bearer phx_test"},
@@ -290,23 +221,6 @@ class TestUsageEndpoint:
assert data["sustained"]["exceeded"] is False
assert data["is_rate_limited"] is False
- def test_returns_pro_limits_with_pro_plan(self, authenticated_usage_client: TestClient) -> None:
- app = authenticated_usage_client.app
- app.state.plan_resolver.get_plan = AsyncMock(
- return_value=PlanInfo(plan_key="posthog-code-200-20260301", seat_created_at=None)
- )
-
- response = authenticated_usage_client.get(
- "/v1/usage/posthog_code",
- headers={"Authorization": "Bearer phx_test"},
- )
- assert response.status_code == 200
- data = response.json()
-
- assert data["burst"]["used_percent"] == 0
- assert data["sustained"]["used_percent"] == 0
- assert data["is_rate_limited"] is False
-
def test_returns_401_without_auth(self, client: TestClient) -> None:
response = client.get("/v1/usage/posthog_code")
assert response.status_code == 401
@@ -406,9 +320,6 @@ class TestUsageEndpoint:
app = authenticated_usage_client.app
resolver_mock = AsyncMock(return_value=QuotaResourceStatus(limited=True))
app.state.quota_resolver.get_resource_status = resolver_mock
- app.state.plan_resolver.get_plan = AsyncMock(
- return_value=PlanInfo(plan_key=None, seat_created_at=None, seat_missing=True)
- )
response = authenticated_usage_client.get(
"/v1/usage/posthog_code",
@@ -420,21 +331,15 @@ class TestUsageEndpoint:
assert data["is_rate_limited"] is True
assert resolver_mock.call_args.args[0] == "posthog_code_credits"
- @pytest.mark.parametrize("plan_key", ["posthog-code-200-20260301", "posthog-code-free-20260301", None])
- def test_exhausted_bucket_reported_for_every_caller(
- self, authenticated_usage_client: TestClient, plan_key: str | None
- ) -> None:
+ def test_exhausted_bucket_reported_for_every_caller(self, authenticated_usage_client: TestClient) -> None:
# Mirrors BillableCreditThrottle: every posthog_code generation counts into
# the org's bucket, so exhaustion blocks (and must be reported to) every
- # caller regardless of seat state — clients gate on this response, and a
- # carve-out here would let them keep sending requests enforcement denies.
+ # caller — clients gate on this response, and a carve-out here would let
+ # them keep sending requests enforcement denies.
from llm_gateway.services.quota_resolver import QuotaResourceStatus
app = authenticated_usage_client.app
app.state.quota_resolver.get_resource_status = AsyncMock(return_value=QuotaResourceStatus(limited=True))
- app.state.plan_resolver.get_plan = AsyncMock(
- return_value=PlanInfo(plan_key=plan_key, seat_created_at="2026-01-01T00:00:00+00:00")
- )
response = authenticated_usage_client.get(
"/v1/usage/posthog_code",
@@ -531,26 +436,3 @@ class TestUsageEndpoint:
)
assert response.status_code == 200
assert response.json()["code_usage_subscribed"] is billing_active
-
- def test_invalidate_plan_cache_calls_resolver(self, authenticated_usage_client: TestClient) -> None:
- app = authenticated_usage_client.app
- app.state.plan_resolver.invalidate = AsyncMock()
-
- response = authenticated_usage_client.post(
- "/v1/usage/posthog_code/invalidate-plan-cache",
- headers={"Authorization": "Bearer phx_test"},
- )
- assert response.status_code == 200
- assert response.json() == {"ok": True}
- app.state.plan_resolver.invalidate.assert_called_once_with(42)
-
- def test_invalidate_plan_cache_404_for_other_product(self, authenticated_usage_client: TestClient) -> None:
- response = authenticated_usage_client.post(
- "/v1/usage/wizard/invalidate-plan-cache",
- headers={"Authorization": "Bearer phx_test"},
- )
- assert response.status_code == 404
-
- def test_invalidate_plan_cache_401_without_auth(self, client: TestClient) -> None:
- response = client.post("/v1/usage/posthog_code/invalidate-plan-cache")
- assert response.status_code == 401