: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(desktop): use organization billing period for usage (#76877)
Adam Bowker9f028823ffe0
diff --git a/ee/api/billing.py b/ee/api/billing.pyindex d68d8deb0d54..8b8ac9c45178 100644--- a/ee/api/billing.py+++ b/ee/api/billing.py@@ -91,6 +91,17 @@ class BillingUsageRequestSerializer(serializers.Serializer):return self._parse_date(value, "end_date")+class BillingPeriodResponseSerializer(serializers.Serializer):+ current_period_start = serializers.DateTimeField(+ allow_null=True,+ help_text="Start of the organization's current billing period, or null when billing has not synced a period.",+ )+ current_period_end = serializers.DateTimeField(+ allow_null=True,+ help_text="End of the organization's current billing period, or null when billing has not synced a period.",+ )++@extend_schema(tags=["billing"])class BillingViewset(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):serializer_class = BillingSerializer@@ -135,6 +146,28 @@ class BillingViewset(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):return Response(response)+ @extend_schema(+ summary="Get the current organization billing period",+ responses={200: BillingPeriodResponseSerializer},+ )+ @action(+ methods=["GET"],+ detail=False,+ url_path="period",+ permission_classes=[permissions.IsAuthenticated],+ required_scopes=["llm_gateway:read"],+ )+ def period(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ billing_period = self._get_org_required().current_billing_period+ return Response(+ BillingPeriodResponseSerializer(+ {+ "current_period_start": billing_period.start if billing_period else None,+ "current_period_end": billing_period.end if billing_period else None,+ }+ ).data+ )+@action(methods=["PATCH"],detail=False,diff --git a/ee/api/test/test_billing.py b/ee/api/test/test_billing.pyindex 72c0b44a73c6..90dee153fedb 100644--- a/ee/api/test/test_billing.py+++ b/ee/api/test/test_billing.py@@ -19,7 +19,9 @@ from rest_framework import statusfrom posthog.cloud_utils import TEST_clear_instance_license_cache, get_cached_instance_licensefrom posthog.models.organization import OrganizationMembership+from posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.team import Team+from posthog.models.utils import generate_random_token_personal, hash_key_valuefrom ee.api.billing import BillingUsageRequestSerializerfrom ee.api.test.base import APILicensedTest@@ -1226,6 +1228,50 @@ class TestBillingUsageAndSpendAPI(APILicensedTest):mock_get_teams_map.assert_called_once()+class TestBillingPeriodAPI(APILicensedTest):+ def test_member_can_read_synced_organization_period(self):+ self.organization_membership.level = OrganizationMembership.Level.MEMBER+ self.organization_membership.save()+ self.organization.usage = {+ "period": ["2026-07-09T00:00:00Z", "2026-08-09T00:00:00Z"],+ }+ self.organization.save()++ response = self.client.get("/api/billing/period/")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(+ response.json(),+ {+ "current_period_start": "2026-07-09T00:00:00Z",+ "current_period_end": "2026-08-09T00:00:00Z",+ },+ )++ def test_gateway_scoped_personal_api_key_can_read_team_period(self):+ self.organization.usage = {+ "period": ["2026-07-09T00:00:00Z", "2026-08-09T00:00:00Z"],+ }+ self.organization.save()+ self.client.logout()+ raw_key = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ label="billing-period-test",+ user=self.user,+ secure_value=hash_key_value(raw_key),+ scopes=["llm_gateway:read"],+ scoped_teams=[self.team.pk],+ )++ response = self.client.get(+ f"/api/billing/period/?team_id={self.team.pk}",+ headers={"authorization": f"Bearer {raw_key}"},+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["current_period_end"], "2026-08-09T00:00:00Z")++class TestBillingPermissionDeniedForMembers(APILicensedTest):"""Verify that billing-modifying actions reject member-level users with 403."""diff --git a/services/llm-gateway/src/llm_gateway/api/usage.py b/services/llm-gateway/src/llm_gateway/api/usage.pyindex 17467e35a3ef..1377ad2fd0cc 100644--- a/services/llm-gateway/src/llm_gateway/api/usage.py+++ b/services/llm-gateway/src/llm_gateway/api/usage.py@@ -1,5 +1,6 @@from __future__ import annotations+import asynciofrom datetime import UTC, datetime, timedeltafrom typing import Annotated@@ -13,6 +14,7 @@ from llm_gateway.rate_limiting.billable_credits_throttle import bucket_block_appfrom llm_gateway.rate_limiting.cost_throttles import CostStatus, UserCostBurstThrottle, UserCostSustainedThrottlefrom llm_gateway.rate_limiting.runner import ThrottleRunnerfrom llm_gateway.rate_limiting.throttles import ThrottleContext+from llm_gateway.services.billing_period_resolver import resolve_billing_periodfrom llm_gateway.services.plan_resolver import (POSTHOG_CODE_PRODUCT,PlanResolver,@@ -77,11 +79,14 @@ async def get_usage() -> UsageResponse:runner: ThrottleRunner = request.app.state.throttle_runner- plan_info, quota_status = await resolve_plan_and_quota(- request,- user_id=user.user_id,- team_id=user.team_id,- product=product,+ (plan_info, quota_status), organization_billing_period = await asyncio.gather(+ resolve_plan_and_quota(+ request,+ user_id=user.user_id,+ team_id=user.team_id,+ product=product,+ ),+ resolve_billing_period(request, user.team_id),)now = datetime.now(tz=UTC)@@ -124,8 +129,10 @@ async def get_usage(sustained_status = _to_cost_limit_status(empty, now=now)billing_period_end: datetime | None = None- if plan_info.billing_period:+ 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)except (ValueError, TypeError) as exc:diff --git a/services/llm-gateway/src/llm_gateway/main.py b/services/llm-gateway/src/llm_gateway/main.pyindex 5c9e1529a417..d4874834e8fd 100644--- a/services/llm-gateway/src/llm_gateway/main.py+++ b/services/llm-gateway/src/llm_gateway/main.py@@ -37,6 +37,7 @@ from llm_gateway.rate_limiting.cost_throttles import (from llm_gateway.rate_limiting.denial_event import PosthogDenialCapturerfrom llm_gateway.rate_limiting.runner import ThrottleRunnerfrom llm_gateway.request_context import RequestContext, set_request_context+from llm_gateway.services.billing_period_resolver import BillingPeriodResolverfrom llm_gateway.services.plan_resolver import PlanResolverfrom llm_gateway.services.quota_resolver import QuotaResolver@@ -198,6 +199,10 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None]:redis=app.state.redis,http_client=app.state.http_client,)+ app.state.billing_period_resolver = BillingPeriodResolver(+ redis=app.state.redis,+ http_client=app.state.http_client,+ )logger.info("Plan resolver initialized", posthog_api_base_url=settings.posthog_api_base_url or "(not configured)")logger.info(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.pynew file mode 100644index 000000000000..ed078f99b534--- /dev/null+++ b/services/llm-gateway/src/llm_gateway/services/billing_period_resolver.py@@ -0,0 +1,120 @@+from __future__ import annotations++import json+from dataclasses import dataclass+from typing import TYPE_CHECKING++import httpx+import structlog++from llm_gateway.auth.service import upstream_auth_header+from llm_gateway.config import get_settings++if TYPE_CHECKING:+ from fastapi import Request+ from redis.asyncio import Redis++logger = structlog.get_logger(__name__)+++@dataclass(frozen=True, kw_only=True)+class OrganizationBillingPeriod:+ current_period_start: str+ current_period_end: str+++def _redis_key(team_id: int) -> str:+ return f"billing_period:team:{team_id}"+++class BillingPeriodResolver:+ def __init__(self, redis: Redis | None, http_client: httpx.AsyncClient):+ self._redis = redis+ self._http = http_client+ self._cache_ttl = get_settings().quota_cache_ttl++ async def get_period(self, team_id: int, auth_header: str) -> OrganizationBillingPeriod | None:+ cache_hit, cached = await self._get_cached(team_id)+ if cache_hit:+ return cached++ settings = get_settings()+ if not settings.posthog_api_base_url:+ return None++ url = f"{settings.posthog_api_base_url.rstrip('/')}/api/billing/period/"+ try:+ response = await self._http.get(+ url,+ headers={"Authorization": auth_header},+ params={"team_id": team_id},+ timeout=2.0,+ )+ response.raise_for_status()+ data = response.json()+ if not isinstance(data, dict):+ raise ValueError("Billing period response must be an object")+ except (httpx.HTTPError, ValueError):+ logger.warning("billing_period_fetch_failed", team_id=team_id, exc_info=True)+ return None++ start = data.get("current_period_start")+ end = data.get("current_period_end")+ if not isinstance(start, str) or not isinstance(end, str):+ await self._set_cached(team_id, None)+ return None++ period = OrganizationBillingPeriod(current_period_start=start, current_period_end=end)+ await self._set_cached(team_id, period)+ return period++ async def _get_cached(self, team_id: int) -> tuple[bool, OrganizationBillingPeriod | None]:+ if not self._redis:+ return False, None+ try:+ value = await self._redis.get(_redis_key(team_id))+ if value is None:+ return False, None+ data = json.loads(value.decode())+ start = data.get("current_period_start")+ end = data.get("current_period_end")+ if isinstance(start, str) and isinstance(end, str):+ return True, OrganizationBillingPeriod(current_period_start=start, current_period_end=end)+ if start is None and end is None:+ return True, None+ except Exception:+ logger.debug("billing_period_cache_read_failed", team_id=team_id)+ return False, None++ async def _set_cached(self, team_id: int, period: OrganizationBillingPeriod | None) -> None:+ if not self._redis:+ return+ try:+ await self._redis.set(+ _redis_key(team_id),+ json.dumps(+ {+ "current_period_start": period.current_period_start if period else None,+ "current_period_end": period.current_period_end if period else None,+ }+ ),+ ex=self._cache_ttl,+ )+ except Exception:+ logger.debug("billing_period_cache_write_failed", team_id=team_id)+++async def resolve_billing_period(request: Request, team_id: int | None) -> OrganizationBillingPeriod | None:+ if team_id is None:+ return None++ auth_header = upstream_auth_header(request)+ if not auth_header:+ return None++ resolver: BillingPeriodResolver = request.app.state.billing_period_resolver+ try:+ return await resolver.get_period(team_id=team_id, auth_header=auth_header)+ except Exception:+ logger.warning("billing_period_resolution_failed", team_id=team_id, exc_info=True)+ return Nonediff --git a/services/llm-gateway/tests/conftest.py b/services/llm-gateway/tests/conftest.pyindex a119df8fd95d..332e566caa7a 100644--- a/services/llm-gateway/tests/conftest.py+++ b/services/llm-gateway/tests/conftest.py@@ -58,6 +58,8 @@ def create_test_app(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.anthropic_circuit_breaker = Noneapp.state.quota_resolver = quota_resolveryielddiff --git a/services/llm-gateway/tests/test_billing_period_resolver.py b/services/llm-gateway/tests/test_billing_period_resolver.pynew file mode 100644index 000000000000..7f8c10c7bf29--- /dev/null+++ b/services/llm-gateway/tests/test_billing_period_resolver.py@@ -0,0 +1,67 @@+from unittest.mock import AsyncMock, MagicMock++import httpx+import pytest++from llm_gateway.services.billing_period_resolver import BillingPeriodResolver, OrganizationBillingPeriod+++async def test_fetches_the_local_billing_period_endpoint() -> None:+ response = httpx.Response(+ 200,+ json={+ "current_period_start": "2026-07-09T00:00:00Z",+ "current_period_end": "2026-08-09T00:00:00Z",+ },+ request=httpx.Request("GET", "https://us.posthog.com/api/billing/period/"),+ )+ http_client = MagicMock()+ http_client.get = AsyncMock(return_value=response)+ resolver = BillingPeriodResolver(redis=None, http_client=http_client)++ period = await resolver.get_period(team_id=42, auth_header="Bearer phx_test")++ assert period == OrganizationBillingPeriod(+ current_period_start="2026-07-09T00:00:00Z",+ current_period_end="2026-08-09T00:00:00Z",+ )+ http_client.get.assert_awaited_once_with(+ "https://us.posthog.com/api/billing/period/",+ headers={"Authorization": "Bearer phx_test"},+ params={"team_id": 42},+ timeout=2.0,+ )+++async def test_malformed_response_falls_open() -> None:+ response = httpx.Response(+ 200,+ content=b"not json",+ request=httpx.Request("GET", "https://us.posthog.com/api/billing/period/"),+ )+ http_client = MagicMock()+ http_client.get = AsyncMock(return_value=response)+ resolver = BillingPeriodResolver(redis=None, http_client=http_client)++ assert await resolver.get_period(team_id=42, auth_header="Bearer phx_test") is None+++async def test_caches_a_successful_missing_period() -> None:+ response = httpx.Response(+ 200,+ json={"current_period_start": None, "current_period_end": None},+ request=httpx.Request("GET", "https://us.posthog.com/api/billing/period/"),+ )+ redis = AsyncMock()+ redis.get.side_effect = [None, b'{"current_period_start": null, "current_period_end": null}']+ http_client = MagicMock()+ http_client.get = AsyncMock(return_value=response)+ resolver = BillingPeriodResolver(redis=redis, http_client=http_client)++ assert await resolver.get_period(team_id=42, auth_header="Bearer phx_test") is None+ assert await resolver.get_period(team_id=42, auth_header="Bearer phx_test") is None+ http_client.get.assert_awaited_once()+ redis.set.assert_awaited_once()diff --git a/services/llm-gateway/tests/test_usage.py b/services/llm-gateway/tests/test_usage.pyindex e1e91617b59c..47e6e597b7e5 100644--- a/services/llm-gateway/tests/test_usage.py+++ b/services/llm-gateway/tests/test_usage.py@@ -12,7 +12,9 @@ from llm_gateway.rate_limiting.cost_throttles import (UserCostBurstThrottle,UserCostSustainedThrottle,)+from llm_gateway.services.billing_period_resolver import OrganizationBillingPeriodfrom llm_gateway.services.plan_resolver import BillingPeriod, PlanInfo+from llm_gateway.services.quota_resolver import QuotaResourceStatusfrom tests.conftest import create_test_app@@ -130,6 +132,42 @@ class TestUsageEndpoint:assert data["billing_period_end"] is not Noneassert data["billing_period_end"].startswith("2026-05-31")+ def test_org_usage_billing_period_wins_over_seat_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-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",+ current_period_end="2026-08-09T00:00:00Z",+ )+ )+ app.state.quota_resolver.get_resource_status = AsyncMock(+ return_value=QuotaResourceStatus(+ limited=False,+ code_usage_billing_active=True,+ used_usd=12.4,+ limit_usd=50.0,+ )+ )++ response = authenticated_usage_client.get(+ "/v1/usage/posthog_code",+ headers={"Authorization": "Bearer phx_test"},+ )++ assert response.status_code == 200+ assert response.json()["billing_period_end"].startswith("2026-08-09")+def test_billing_period_end_normalises_naive_iso_to_utc(self, authenticated_usage_client: TestClient) -> None:app = authenticated_usage_client.appapp.state.plan_resolver.get_plan = AsyncMock(