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.

feat(llm-gateway): include reset_at in usage response (#60059)

Peter Kirkhameddd4f73a00d
diff --git a/services/llm-gateway/src/llm_gateway/api/usage.py b/services/llm-gateway/src/llm_gateway/api/usage.py
index 5c99d3267482..557a61bdfd1b 100644
--- a/services/llm-gateway/src/llm_gateway/api/usage.py
+++ b/services/llm-gateway/src/llm_gateway/api/usage.py
@@ -1,7 +1,9 @@
from __future__ import annotations
+from datetime import UTC, datetime, timedelta
from typing import Annotated
+import structlog
from fastapi import APIRouter, Depends, HTTPException, Request
from pydantic import BaseModel
@@ -10,14 +12,26 @@ from llm_gateway.dependencies import get_authenticated_user
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.plan_resolver import POSTHOG_CODE_PRODUCT, PlanResolver, resolve_plan_info
+from llm_gateway.services.plan_resolver import (
+ POSTHOG_CODE_PRODUCT,
+ PlanResolver,
+ is_pro_plan,
+ parse_iso_utc,
+ resolve_plan_info,
+)
+
+logger = structlog.get_logger(__name__)
usage_router = APIRouter(prefix="/v1/usage", tags=["Usage"])
class CostLimitStatus(BaseModel):
used_percent: float
+ # Kept on the wire for older PostHog Code clients whose zod schema still
+ # requires it. Newer clients anchor to `reset_at`; drop in a follow-up once
+ # the long tail of pinned clients has rolled forward.
resets_in_seconds: int
+ reset_at: datetime
exceeded: bool
@@ -27,9 +41,11 @@ class UsageResponse(BaseModel):
burst: CostLimitStatus
sustained: CostLimitStatus
is_rate_limited: bool
+ is_pro: bool
+ billing_period_end: datetime | None = None
-def _to_cost_limit_status(status: CostStatus) -> CostLimitStatus:
+def _to_cost_limit_status(status: CostStatus, now: datetime) -> CostLimitStatus:
if status.limit_usd > 0:
used_percent = min(100.0, (status.used_usd / status.limit_usd) * 100)
else:
@@ -37,6 +53,7 @@ def _to_cost_limit_status(status: CostStatus) -> CostLimitStatus:
return CostLimitStatus(
used_percent=round(used_percent, 1),
resets_in_seconds=status.resets_in_seconds,
+ reset_at=now + timedelta(seconds=status.resets_in_seconds),
exceeded=status.exceeded,
)
@@ -49,6 +66,7 @@ async def get_usage(
) -> UsageResponse:
runner: ThrottleRunner = request.app.state.throttle_runner
plan_info = await resolve_plan_info(request, user.user_id, product)
+ now = datetime.now(tz=UTC)
context = ThrottleContext(
user=user,
@@ -64,14 +82,36 @@ async def get_usage(
for throttle in runner.throttles:
if isinstance(throttle, UserCostBurstThrottle):
- burst_status = _to_cost_limit_status(await throttle.get_status(context))
+ burst_status = _to_cost_limit_status(await throttle.get_status(context), now=now)
elif isinstance(throttle, UserCostSustainedThrottle):
- sustained_status = _to_cost_limit_status(await throttle.get_status(context))
-
- if burst_status is None:
- burst_status = CostLimitStatus(used_percent=0, resets_in_seconds=0, exceeded=False)
- if sustained_status is None:
- sustained_status = CostLimitStatus(used_percent=0, resets_in_seconds=0, exceeded=False)
+ sustained_status = _to_cost_limit_status(await throttle.get_status(context), now=now)
+ if burst_status is not None and sustained_status is not None:
+ break
+
+ if burst_status is None or sustained_status is None:
+ # `limit_usd=1` is a sentinel so `_to_cost_limit_status` reports 0% used
+ # rather than tripping its no-throttle branch (which would surface 100%
+ # used + not rate-limited).
+ empty = CostStatus(used_usd=0, limit_usd=1, remaining_usd=1, resets_in_seconds=0, exceeded=False)
+ if burst_status is None:
+ burst_status = _to_cost_limit_status(empty, now=now)
+ if sustained_status is None:
+ sustained_status = _to_cost_limit_status(empty, now=now)
+
+ billing_period_end: datetime | None = None
+ if plan_info.billing_period:
+ raw_period_end = plan_info.billing_period.current_period_end
+ try:
+ billing_period_end = parse_iso_utc(raw_period_end)
+ except (ValueError, TypeError) as exc:
+ logger.warning(
+ "usage.billing_period_end_unparseable",
+ user_id=user.user_id,
+ product=product,
+ raw=raw_period_end,
+ error=str(exc),
+ )
+ billing_period_end = None
return UsageResponse(
product=product,
@@ -79,6 +119,8 @@ async def get_usage(
burst=burst_status,
sustained=sustained_status,
is_rate_limited=burst_status.exceeded or sustained_status.exceeded,
+ is_pro=is_pro_plan(plan_info.plan_key),
+ billing_period_end=billing_period_end,
)
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 8fef8d00287f..73fce616fa40 100644
--- a/services/llm-gateway/src/llm_gateway/services/plan_resolver.py
+++ b/services/llm-gateway/src/llm_gateway/services/plan_resolver.py
@@ -55,6 +55,11 @@ def is_pro_plan(plan_key: str | None) -> bool:
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,
@@ -64,9 +69,7 @@ def get_billing_period_number(
if not anchor:
return 0
try:
- created = datetime.fromisoformat(anchor)
- if created.tzinfo is None:
- created = created.replace(tzinfo=UTC)
+ created = parse_iso_utc(anchor)
elapsed = datetime.now(tz=UTC) - created
return max(0, elapsed.days // period_days)
except (ValueError, TypeError):
diff --git a/services/llm-gateway/tests/test_usage.py b/services/llm-gateway/tests/test_usage.py
index 5b40b8488db6..e9ec3e6999c7 100644
--- a/services/llm-gateway/tests/test_usage.py
+++ b/services/llm-gateway/tests/test_usage.py
@@ -1,6 +1,8 @@
+from datetime import UTC, datetime, timedelta
from unittest.mock import AsyncMock, MagicMock
import pytest
+import structlog
from fastapi.testclient import TestClient
from llm_gateway.api.usage import _to_cost_limit_status
@@ -9,11 +11,13 @@ from llm_gateway.rate_limiting.cost_throttles import (
UserCostBurstThrottle,
UserCostSustainedThrottle,
)
-from llm_gateway.services.plan_resolver import PlanInfo
+from llm_gateway.services.plan_resolver import BillingPeriod, PlanInfo
from tests.conftest import create_test_app
class TestToCostLimitStatus:
+ NOW = datetime(2026, 5, 1, 12, 0, 0, tzinfo=UTC)
+
@pytest.mark.parametrize(
"used_usd,limit_usd,expected_percent",
[
@@ -29,15 +33,27 @@ class TestToCostLimitStatus:
status = CostStatus(
used_usd=used_usd, limit_usd=limit_usd, remaining_usd=0.0, resets_in_seconds=60, exceeded=False
)
- result = _to_cost_limit_status(status)
+ result = _to_cost_limit_status(status, now=self.NOW)
assert result.used_percent == expected_percent
def test_passes_through_exceeded_and_resets(self) -> None:
status = CostStatus(used_usd=100.0, limit_usd=100.0, remaining_usd=0.0, resets_in_seconds=3600, exceeded=True)
- result = _to_cost_limit_status(status)
+ result = _to_cost_limit_status(status, now=self.NOW)
assert result.exceeded is True
assert result.resets_in_seconds == 3600
+ @pytest.mark.parametrize("resets_in_seconds", [0, 60, 3600, 86400])
+ def test_reset_at_matches_resets_in_seconds(self, resets_in_seconds: int) -> None:
+ status = CostStatus(
+ used_usd=10.0,
+ limit_usd=100.0,
+ remaining_usd=90.0,
+ resets_in_seconds=resets_in_seconds,
+ exceeded=False,
+ )
+ result = _to_cost_limit_status(status, now=self.NOW)
+ assert result.reset_at == self.NOW + timedelta(seconds=resets_in_seconds)
+
class TestUsageEndpoint:
@pytest.fixture
@@ -73,6 +89,128 @@ class TestUsageEndpoint:
assert data["burst"]["used_percent"] == 0
assert data["sustained"]["used_percent"] == 0
assert data["is_rate_limited"] is False
+ assert "is_pro" in data
+ assert "reset_at" in data["burst"]
+ assert "reset_at" in data["sustained"]
+ assert "billing_period_end" in data
+
+ def test_response_has_no_usd_fields(self, authenticated_usage_client: TestClient) -> None:
+ response = authenticated_usage_client.get(
+ "/v1/usage/posthog_code",
+ headers={"Authorization": "Bearer phx_test"},
+ )
+ assert response.status_code == 200
+ data = response.json()
+ for bucket in (data["burst"], data["sustained"]):
+ 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:
+ 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",
+ ),
+ )
+ )
+
+ response = authenticated_usage_client.get(
+ "/v1/usage/posthog_code",
+ headers={"Authorization": "Bearer phx_test"},
+ )
+ assert response.status_code == 200
+ data = response.json()
+ assert data["billing_period_end"] is not None
+ assert data["billing_period_end"].startswith("2026-05-31")
+
+ 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",
+ ),
+ )
+ )
+
+ response = authenticated_usage_client.get(
+ "/v1/usage/posthog_code",
+ headers={"Authorization": "Bearer phx_test"},
+ )
+ assert response.status_code == 200
+ billing_period_end = response.json()["billing_period_end"]
+ assert billing_period_end is not None
+ parsed = datetime.fromisoformat(billing_period_end)
+ assert parsed.tzinfo is not None
+ assert parsed.utcoffset() == timedelta(0)
+
+ 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",
+ ),
+ )
+ )
+
+ with structlog.testing.capture_logs() as logs:
+ 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"] 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")
+ )
+
+ 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"] 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