: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
feat(billing): project billing routes over the organization reads (#110197)
Alex Mays1222d7b4a278
diff --git a/ee/api/organization_billing.py b/ee/api/organization_billing.pyindex bdbbe5b436ae..b9c2d18d41b5 100644--- a/ee/api/organization_billing.py+++ b/ee/api/organization_billing.py@@ -580,39 +580,14 @@ BETA_NOTICE = ()-@extend_schema(extensions={"x-product": "billing"})-class OrganizationBillingViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):- """Read billing state for an organization: subscription, products, features and usage.-- The schema attributes every operation here to the billing product. Without that the route- puts them under organizations, and the MCP tool scaffold, which matches by product, drops- the billing tools that name them.- """+class BillingReadViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):+ """What the organization and project billing routes share. That is the flag, the throttles, the+ grants in billing's token, the project scoping, and the series and export reads."""scope_object = "billing"- scope_object_read_actions = [- "subscription",- "features",- "products",- "product",- "summary",- "usage",- "usage_status",- "spend",- "forecast",- "usage_timeseries",- "spend_timeseries",- "usage_export",- "spend_export",- "invoices",- "invoice_content",- "limits",- "projects",- ]scope_object_write_actions: list[str] = []# Nothing here answers until the flag is on for the caller's organization.posthog_feature_flag = ORGANIZATION_BILLING_API_FLAG- permission_classes = [permissions.IsAuthenticated, OrganizationMemberPermissions, PostHogFeatureFlagPermission]throttle_classes = [BillingReadBurstRateThrottle, BillingReadSustainedRateThrottle]# Opt into the generated schema. The MCP scaffolding and generated clients read it from there.force_include_in_api_docs = True@@ -722,17 +697,24 @@ class OrganizationBillingViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSetparams["teams_map"] = {str(team_id): name for team_id, name in teams_map.items()}return teams_map- def _timeseries(self, request: Request, kind: str) -> Response:+ def _timeseries(+ self,+ request: Request,+ kind: str,+ serializer_class: type[serializers.Serializer],+ *,+ pinned_team_ids: list[int] | None = None,+ ) -> Response:+ """The usage or spend series. A route that names a project passes its teams as+ `pinned_team_ids`, and the scoping treats the read as a request for those teams."""organization = self.organizationgrants = self._grants(request, organization)self._require(grants, BillingEntitlement.USAGE_READ)- # Spend serves a project-only breakdown and usage does not, so each read checks its own.- serializer_class = (- OrganizationUsageTimeseriesRequestSerializer if kind == "usage" else OrganizationTimeseriesRequestSerializer- )serializer = serializer_class(data=request.GET)serializer.is_valid(raise_exception=True)params = {key: value for key, value in serializer.validated_data.items() if value is not None}+ if pinned_team_ids is not None:+ params["team_ids"] = json.dumps(pinned_team_ids)# Billing pages with page_size and after. The API calls the same two limit and cursor.if "limit" in params:params["page_size"] = params.pop("limit")@@ -756,6 +738,103 @@ class OrganizationBillingViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet})+ def _export(+ self,+ request: Request,+ kind: str,+ serializer_class: type[serializers.Serializer],+ *,+ pinned_team_ids: list[int] | None = None,+ ) -> StreamingHttpResponse:+ """The usage or spend rows as a CSV, streamed from billing's organization export route+ under the same scoping as the series, with project names written in as it passes."""+ organization = self.organization+ grants = self._grants(request, organization)+ self._require(grants, BillingEntitlement.USAGE_READ)+ serializer = serializer_class(data=request.GET)+ serializer.is_valid(raise_exception=True)+ params = {key: value for key, value in serializer.validated_data.items() if value is not None}+ if pinned_team_ids is not None:+ params["team_ids"] = json.dumps(pinned_team_ids)+ teams_map = self._scope_projects(request, grants, organization, params, for_export=True)+ # The names go into the file here, not into the request.+ params.pop("teams_map", None)+ # Taken before billing is asked and given back when the download ends, as the root exports do.+ slot = _take_export_stream_slot(request.user)+ try:+ try:+ upstream = self._manager().get_organization_export(organization, grants, kind, params)+ except requests.Timeout:+ raise BillingExportTimeout()+ except BaseException:+ _release_export_stream_slot(slot)+ raise+ lines = _rewrite_csv_labels(upstream.iter_content(chunk_size=8192), teams_map)+ accepts_gzip = "gzip" in request.META.get("HTTP_ACCEPT_ENCODING", "").lower()+ response = streaming_response(+ _released_after(_stream_chunks(upstream, _gzip_stream(lines) if accepts_gzip else lines), slot),+ content_type=upstream.headers.get("Content-Type", "text/csv"),+ )+ if accepts_gzip:+ response["Content-Encoding"] = "gzip"+ patch_vary_headers(response, ("Accept-Encoding",))+ response["Content-Disposition"] = upstream.headers.get(+ "Content-Disposition", f'attachment; filename="posthog_{kind}_export.csv"'+ )+ return response++ def _cursor_url(self, request: Request, cursor: Optional[str]) -> Optional[str]:+ """The same request with the cursor swapped, so limit and any filter carry across pages."""+ if not cursor:+ return None+ params = request.query_params.copy()+ params["cursor"] = cursor+ return request.build_absolute_uri(f"{request.path}?{params.urlencode()}")++ def _previous_url(self, request: Request, cursor: Optional[str]) -> Optional[str]:+ """The page before this one. Billing names the first page with an empty cursor, and the+ link to it is the same request without one."""+ if cursor is None:+ return None+ if cursor == "":+ params = request.query_params.copy()+ params.pop("cursor", None)+ return request.build_absolute_uri(f"{request.path}?{params.urlencode()}")+ return self._cursor_url(request, cursor)+++@extend_schema(extensions={"x-product": "billing"})+class OrganizationBillingViewSet(BillingReadViewSet):+ """Read billing state for an organization: subscription, products, features and usage.++ The schema attributes every operation here to the billing product. Without that the route+ puts them under organizations, and the MCP tool scaffold, which matches by product, drops+ the billing tools that name them.+ """++ scope_object_read_actions = [+ "subscription",+ "features",+ "products",+ "product",+ "summary",+ "usage",+ "usage_status",+ "spend",+ "forecast",+ "usage_timeseries",+ "spend_timeseries",+ "usage_export",+ "spend_export",+ "invoices",+ "invoice_content",+ "limits",+ "projects",+ ]+ permission_classes = [permissions.IsAuthenticated, OrganizationMemberPermissions, PostHogFeatureFlagPermission]+ # The project billing routes share these paths' suffixes, but they read one project, not the organization.+ schema_org_paths_are_not_duplicates = True+@extend_schema(operation_id="billing_subscription_retrieve",summary="Get the organization's subscription",@@ -913,7 +992,7 @@ class OrganizationBillingViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet)@action(methods=["GET"], detail=False, url_path="usage/timeseries")def usage_timeseries(self, request: Request, *args: Any, **kwargs: Any) -> Response:- return self._timeseries(request, "usage")+ return self._timeseries(request, "usage", OrganizationUsageTimeseriesRequestSerializer)@extend_schema(operation_id="billing_spend_timeseries_retrieve",@@ -924,46 +1003,7 @@ class OrganizationBillingViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet)@action(methods=["GET"], detail=False, url_path="spend/timeseries")def spend_timeseries(self, request: Request, *args: Any, **kwargs: Any) -> Response:- return self._timeseries(request, "spend")-- def _export(self, request: Request, kind: str) -> StreamingHttpResponse:- """The usage or spend rows as a CSV, streamed from billing's organization export route- under the same scoping as the series, with project names written in as it passes."""- organization = self.organization- grants = self._grants(request, organization)- self._require(grants, BillingEntitlement.USAGE_READ)- serializer_class = (- OrganizationUsageExportRequestSerializer if kind == "usage" else OrganizationExportRequestSerializer- )- serializer = serializer_class(data=request.GET)- serializer.is_valid(raise_exception=True)- params = {key: value for key, value in serializer.validated_data.items() if value is not None}- teams_map = self._scope_projects(request, grants, organization, params, for_export=True)- # The names go into the file here, not into the request.- params.pop("teams_map", None)- # Taken before billing is asked and given back when the download ends, as the root exports do.- slot = _take_export_stream_slot(request.user)- try:- try:- upstream = self._manager().get_organization_export(organization, grants, kind, params)- except requests.Timeout:- raise BillingExportTimeout()- except BaseException:- _release_export_stream_slot(slot)- raise- lines = _rewrite_csv_labels(upstream.iter_content(chunk_size=8192), teams_map)- accepts_gzip = "gzip" in request.META.get("HTTP_ACCEPT_ENCODING", "").lower()- response = streaming_response(- _released_after(_stream_chunks(upstream, _gzip_stream(lines) if accepts_gzip else lines), slot),- content_type=upstream.headers.get("Content-Type", "text/csv"),- )- if accepts_gzip:- response["Content-Encoding"] = "gzip"- patch_vary_headers(response, ("Accept-Encoding",))- response["Content-Disposition"] = upstream.headers.get(- "Content-Disposition", f'attachment; filename="posthog_{kind}_export.csv"'- )- return response+ return self._timeseries(request, "spend", OrganizationTimeseriesRequestSerializer)@extend_schema(operation_id="billing_usage_export_download",@@ -980,7 +1020,7 @@ class OrganizationBillingViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSetthrottle_classes=[BillingReadBurstRateThrottle, BillingReadSustainedRateThrottle, BillingExportThrottle],)def usage_export(self, request: Request, *args: Any, **kwargs: Any) -> StreamingHttpResponse:- return self._export(request, "usage")+ return self._export(request, "usage", OrganizationUsageExportRequestSerializer)@extend_schema(operation_id="billing_spend_export_download",@@ -997,26 +1037,7 @@ class OrganizationBillingViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSetthrottle_classes=[BillingReadBurstRateThrottle, BillingReadSustainedRateThrottle, BillingExportThrottle],)def spend_export(self, request: Request, *args: Any, **kwargs: Any) -> StreamingHttpResponse:- return self._export(request, "spend")-- def _cursor_url(self, request: Request, cursor: Optional[str]) -> Optional[str]:- """The same request with the cursor swapped, so limit and any filter carry across pages."""- if not cursor:- return None- params = request.query_params.copy()- params["cursor"] = cursor- return request.build_absolute_uri(f"{request.path}?{params.urlencode()}")-- def _previous_url(self, request: Request, cursor: Optional[str]) -> Optional[str]:- """The page before this one. Billing names the first page with an empty cursor, and the- link to it is the same request without one."""- if cursor is None:- return None- if cursor == "":- params = request.query_params.copy()- params.pop("cursor", None)- return request.build_absolute_uri(f"{request.path}?{params.urlencode()}")- return self._cursor_url(request, cursor)+ return self._export(request, "spend", OrganizationExportRequestSerializer)@extend_schema(operation_id="billing_invoices_list",diff --git a/ee/api/project_billing.py b/ee/api/project_billing.pynew file mode 100644index 000000000000..02ebc5d368c6--- /dev/null+++ b/ee/api/project_billing.py@@ -0,0 +1,209 @@+"""Billing reads for one project: its usage and its share of the organization's spend.++Every read is the organization read pinned to the project's teams. A project's numbers match what+the organization routes report for it, and billing serves no new query.+"""++from __future__ import annotations++import json+from datetime import UTC, datetime+from typing import Any, Optional++from django.http import StreamingHttpResponse++import requests+from drf_spectacular.utils import OpenApiResponse, extend_schema+from rest_framework import permissions, serializers+from rest_framework.decorators import action+from rest_framework.request import Request+from rest_framework.response import Response++from posthog.auth import ProjectSecretAPIKeyAuthentication+from posthog.models import Team+from posthog.permissions import PostHogFeatureFlagPermission+from posthog.rate_limit import BillingReadBurstRateThrottle, BillingReadSustainedRateThrottle++from ee.api.billing import BillingExportThrottle, BillingQueryTimeout, BillingUsageRequestSerializer+from ee.api.organization_billing import (+ BETA_NOTICE,+ BillingPeriodSerializer,+ BillingReadViewSet,+ PaginatedBillingTimeSeriesPointListSerializer,+ _billing_period,+)+from ee.billing.grants import BillingEntitlement++PROJECT_BREAKDOWNS_MESSAGE = 'Pass `["type"]` for a series per product, or omit breakdowns for one series.'+++class ProjectTimeseriesRequestSerializer(BillingUsageRequestSerializer):+ """One project's series: the organization series' parameters without the project filter, the+ project fold and paging, because the route already names the project."""++ team_ids = None # type: ignore[assignment]+ top_projects = None # type: ignore[assignment]+ page_size = None # type: ignore[assignment]+ after = None # type: ignore[assignment]+ breakdowns = serializers.CharField(+ required=False,+ allow_blank=True,+ allow_null=True,+ help_text=(+ 'JSON-encoded array of breakdown dimensions. Omit it for one series across the project. Pass `["type"]` '+ "for a series per product."+ ),+ )++ def validate_breakdowns(self, value: Optional[str]) -> Optional[str]:+ value = super().validate_breakdowns(value)+ if value and json.loads(value) not in ([], ["type"]):+ raise serializers.ValidationError(PROJECT_BREAKDOWNS_MESSAGE)+ return value+++class ProjectUsageItemSerializer(serializers.Serializer):+ usage_key = serializers.CharField(help_text="The usage counter, as the usage series names it.")+ name = serializers.CharField(help_text="The counter's display name.")+ usage = serializers.FloatField(help_text="The project's usage of the counter so far this billing period.")+++class ProjectUsageSummarySerializer(serializers.Serializer):+ billing_period = BillingPeriodSerializer(+ allow_null=True,+ help_text=(+ "The period the usage covers. Null when the organization has no billing period yet, and the usage then "+ "covers the current calendar month in UTC."+ ),+ )+ results = ProjectUsageItemSerializer(many=True, help_text="One entry per usage counter the project reported.")+++PROJECT_BILLING_READ_ACTIONS = ["usage", "usage_timeseries", "spend_timeseries", "usage_export", "spend_export"]+EXPORT_THROTTLES = [BillingReadBurstRateThrottle, BillingReadSustainedRateThrottle, BillingExportThrottle]+++@extend_schema(extensions={"x-product": "billing"})+class ProjectBillingViewSet(BillingReadViewSet):+ """Read one project's usage and its share of the organization's spend.++ A credential reaches a project when it covers the project. An organization-wide session, personal+ key or OAuth token covers every project. A project-scoped key covers its projects, and a project+ secret key with `billing:read` covers its own project.+ """++ authentication_classes = [ProjectSecretAPIKeyAuthentication]+ psak_allowed_actions = PROJECT_BILLING_READ_ACTIONS+ scope_object_read_actions = PROJECT_BILLING_READ_ACTIONS+ # The routing mixin adds the project membership check for project routes.+ permission_classes = [permissions.IsAuthenticated, PostHogFeatureFlagPermission]++ def _project_team_ids(self) -> list[int]:+ """Every team in the project. Billing reports usage per team, and a project's environments are+ its teams."""+ return sorted(+ Team.objects.filter(project_id=self.team.project_id, organization_id=self.organization.id).values_list(+ "id", flat=True+ )+ )++ @extend_schema(+ operation_id="billing_project_usage_retrieve",+ summary="Get a project's usage so far this billing period",+ description=BETA_NOTICE,+ responses={200: OpenApiResponse(response=ProjectUsageSummarySerializer)},+ )+ @action(methods=["GET"], detail=False, url_path="usage")+ def usage(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ organization = self.organization+ grants = self._grants(request, organization)+ self._require(grants, BillingEntitlement.USAGE_READ)+ manager = self._manager()+ try:+ subscription = manager.get_organization_subscription(organization, grants)+ except requests.Timeout:+ raise BillingQueryTimeout()+ period = _billing_period(subscription.get("billing_period"))+ today = datetime.now(UTC).date()+ period_start = (period or {}).get("current_period_start")+ start_date = period_start[:10] if period_start else today.replace(day=1).isoformat()+ params: dict[str, Any] = {+ "start_date": start_date,+ "end_date": today.isoformat(),+ "breakdowns": json.dumps(["type"]),+ "team_ids": json.dumps(self._project_team_ids()),+ }+ self._scope_projects(request, grants, organization, params)+ try:+ data = manager.get_organization_timeseries(organization, grants, "usage", params)+ except requests.Timeout:+ raise BillingQueryTimeout()+ results = [+ {+ "usage_key": _usage_key(series.get("breakdown_value")),+ "name": series.get("label") or "",+ "usage": float(sum(value or 0 for value in series.get("data") or [])),+ }+ for series in data.get("results", [])+ ]+ return Response({"billing_period": period, "results": results})++ @extend_schema(+ operation_id="billing_project_usage_timeseries_retrieve",+ summary="A project's usage over time",+ description=BETA_NOTICE,+ parameters=[ProjectTimeseriesRequestSerializer],+ responses={200: OpenApiResponse(response=PaginatedBillingTimeSeriesPointListSerializer)},+ )+ @action(methods=["GET"], detail=False, url_path="usage/timeseries")+ def usage_timeseries(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ return self._timeseries(+ request, "usage", ProjectTimeseriesRequestSerializer, pinned_team_ids=self._project_team_ids()+ )++ @extend_schema(+ operation_id="billing_project_spend_timeseries_retrieve",+ summary="A project's share of spend over time",+ description=BETA_NOTICE,+ parameters=[ProjectTimeseriesRequestSerializer],+ responses={200: OpenApiResponse(response=PaginatedBillingTimeSeriesPointListSerializer)},+ )+ @action(methods=["GET"], detail=False, url_path="spend/timeseries")+ def spend_timeseries(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ return self._timeseries(+ request, "spend", ProjectTimeseriesRequestSerializer, pinned_team_ids=self._project_team_ids()+ )++ @extend_schema(+ operation_id="billing_project_usage_export_download",+ summary="Export a project's usage as CSV",+ description=BETA_NOTICE,+ parameters=[ProjectTimeseriesRequestSerializer],+ responses={(200, "text/csv"): OpenApiResponse(response=bytes)},+ )+ @action(methods=["GET"], detail=False, url_path="usage/export", throttle_classes=EXPORT_THROTTLES)+ def usage_export(self, request: Request, *args: Any, **kwargs: Any) -> StreamingHttpResponse:+ return self._export(+ request, "usage", ProjectTimeseriesRequestSerializer, pinned_team_ids=self._project_team_ids()+ )++ @extend_schema(+ operation_id="billing_project_spend_export_download",+ summary="Export a project's share of spend as CSV",+ description=BETA_NOTICE,+ parameters=[ProjectTimeseriesRequestSerializer],+ responses={(200, "text/csv"): OpenApiResponse(response=bytes)},+ )+ @action(methods=["GET"], detail=False, url_path="spend/export", throttle_classes=EXPORT_THROTTLES)+ def spend_export(self, request: Request, *args: Any, **kwargs: Any) -> StreamingHttpResponse:+ return self._export(+ request, "spend", ProjectTimeseriesRequestSerializer, pinned_team_ids=self._project_team_ids()+ )+++def _usage_key(breakdown_value: Any) -> str:+ """The product dimension of a series broken down by type. Billing sends it alone or as the first+ of the breakdown's values."""+ if isinstance(breakdown_value, list):+ return str(breakdown_value[0]) if breakdown_value else ""+ return str(breakdown_value or "")diff --git a/ee/api/test/test_billing.py b/ee/api/test/test_billing.pyindex c40e8b811a03..4313d7fd0fa5 100644--- a/ee/api/test/test_billing.py+++ b/ee/api/test/test_billing.py@@ -23,12 +23,14 @@ from requests import Response, getfrom rest_framework import statusfrom rest_framework.exceptions import ValidationError+from posthog.auth import ProjectSecretAPIKeyUserfrom posthog.cloud_utils import TEST_clear_instance_license_cache, get_cached_instance_licensefrom posthog.constants import AvailableFeaturefrom posthog.models.oauth import OAuthAccessToken, OAuthApplicationfrom posthog.models.organization import Organization, OrganizationMembershipfrom posthog.models.organization_provisioning import OrganizationProvisioningfrom posthog.models.personal_api_key import PersonalAPIKey+from posthog.models.project_secret_api_key import ProjectSecretAPIKeyfrom posthog.models.team import Teamfrom posthog.models.user import Userfrom posthog.models.utils import generate_random_token_personal, hash_key_value@@ -55,6 +57,7 @@ from ee.api.billing import (from ee.api.test.base import APILicensedTestfrom ee.billing.billing_manager import BillingManagerfrom ee.billing.billing_types import USAGE_TYPE_OPTIONS, BillingPeriod, CustomerInfo, CustomerProduct, UsageType+from ee.billing.exports import _release_export_stream_slot, _take_export_stream_slotfrom ee.billing.grants import (BILLING_LIMIT_TODAYS_USAGE_FLAG,MEMBER_BILLING_USAGE_SPEND_READ_ACCESS_FLAG,@@ -2972,6 +2975,18 @@ class TestExportLimits(APILicensedTest):self.assertEqual(b"".join(first), b"Product\nEvents\n")self.assertEqual(self._export([b"Product\n"]).status_code, status.HTTP_200_OK)+ @patch.object(_EXPORT_STREAMS, "max_concurrency", 1)+ def test_each_project_secret_key_has_its_own_export_slots(self):+ first, second = (+ ProjectSecretAPIKey.objects.create(team=self.team, label=label, secure_value=f"sha256${label}")+ for label in ("first", "second")+ )+ held = _take_export_stream_slot(ProjectSecretAPIKeyUser(first))+ try:+ _release_export_stream_slot(_take_export_stream_slot(ProjectSecretAPIKeyUser(second)))+ finally:+ _release_export_stream_slot(held)+@patch("posthog.rate_limit.is_rate_limit_enabled", return_value=True)@patch.object(BillingExportThrottle, "rate", "1/minute")def test_export_starts_are_rate_limited_per_person(self, _rate_limit_enabled):diff --git a/ee/api/test/test_organization_billing.py b/ee/api/test/test_organization_billing.pyindex 4a650890a77a..b43f919b2c18 100644--- a/ee/api/test/test_organization_billing.py+++ b/ee/api/test/test_organization_billing.py@@ -15,6 +15,7 @@ from rest_framework import statusfrom posthog.models import OrganizationMembership, PersonalAPIKey, Teamfrom posthog.models.oauth import OAuthAccessToken, OAuthApplicationfrom posthog.models.organization_provisioning import OrganizationProvisioning+from posthog.models.project_secret_api_key import ProjectSecretAPIKeyfrom posthog.models.utils import generate_random_token_personal, hash_key_valuefrom posthog.rate_limit import BillingReadBurstRateThrottle@@ -852,3 +853,131 @@ class TestOrganizationBillingInvoicesAndLimits(OrganizationBillingTestMixin, APIresponse = self.client.get(self._url(path))self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN, path)mock_get.assert_not_called()+++class TestProjectBillingAPI(OrganizationBillingTestMixin, APILicensedTest):+ def setUp(self):+ super().setUp()+ self.other_team = Team.objects.create(organization=self.organization, name="Other project")++ def _project_url(self, path: str) -> str:+ return f"/api/projects/{self.team.id}/billing/{path}"++ def _personal_key(self, scoped_teams: list[int] | None) -> dict[str, Any]:+ raw = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ user=self.user,+ label="billing",+ secure_value=hash_key_value(raw),+ scopes=["billing:read"],+ scoped_teams=scoped_teams,+ )+ self.client.logout()+ return {"HTTP_AUTHORIZATION": f"Bearer {raw}"}++ def _project_secret_key(self, team: Team) -> dict[str, Any]:+ token = "phs_" + "a" * 35 + str(team.id)+ ProjectSecretAPIKey.objects.create(+ team=team,+ label="billing",+ mask_value="phs_...",+ secure_value=hash_key_value(token),+ scopes=["billing:read"],+ )+ self.client.logout()+ return {"HTTP_AUTHORIZATION": f"Bearer {token}"}++ def _credential(self, name: str) -> dict[str, Any]:+ if name == "session":+ return {}+ if name == "organization_oauth_token":+ return {"HTTP_AUTHORIZATION": f"Bearer {self._oauth_token('billing:read')}"}+ if name == "personal_key_for_this_project":+ return self._personal_key([self.team.id])+ if name == "personal_key_for_another_project":+ return self._personal_key([self.other_team.id])+ if name == "project_secret_key_for_this_project":+ return self._project_secret_key(self.team)+ return self._project_secret_key(self.other_team)++ @parameterized.expand(+ [+ ("session", True),+ ("organization_oauth_token", True),+ ("personal_key_for_this_project", True),+ ("personal_key_for_another_project", False),+ ("project_secret_key_for_this_project", True),+ ("project_secret_key_for_another_project", False),+ ]+ )+ @patch("ee.billing.billing_manager.http_session.get")+ def test_project_series_read_only_the_project_a_credential_covers(self, credential, allowed, mock_get):+ mock_get.return_value = _response(SERIES)+ headers = self._credential(credential)+ # A request naming another project still reads only the project in the path.+ response = self.client.get(+ self._project_url(+ f"spend/timeseries/?start_date=2026-09-01&end_date=2026-09-14&team_ids=%5B{self.other_team.id}%5D"+ ),+ **headers,+ )+ if not allowed:+ self.assertIn(response.status_code, (status.HTTP_403_FORBIDDEN, status.HTTP_404_NOT_FOUND))+ mock_get.assert_not_called()+ return+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)+ self.assertEqual(json.loads(mock_get.call_args.kwargs["params"]["team_ids"]), [self.team.id])++ @parameterized.expand([("usage",), ("spend",)])+ @patch("ee.billing.billing_manager.http_session.get")+ async def test_project_export_sends_billing_only_the_project_in_the_path(self, kind, mock_get):+ upstream = MagicMock()+ upstream.status_code = 200+ upstream.headers = {"Content-Type": "text/csv"}+ upstream.iter_content.return_value = iter([b"Product,Total\n"])+ mock_get.return_value = upstream+ await self.async_client.aforce_login(self.user)+ # A request naming another project still exports only the project in the path.+ response = await self.async_client.get(+ self._project_url(+ f"{kind}/export/?start_date=2026-09-01&end_date=2026-09-14&team_ids=%5B{self.other_team.id}%5D"+ )+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK, getattr(response, "content", b"")[:200])+ sent = mock_get.call_args+ self.assertTrue(sent.args[0].endswith(f"/api/v2/billing/{kind}/export/"), sent.args[0])+ self.assertEqual(json.loads(sent.kwargs["params"]["team_ids"]), [self.team.id])++ @parameterized.expand([("billing_period_read", 0), ("usage_read", 1)])+ @patch("ee.billing.billing_manager.http_session.get")+ def test_project_usage_timeout_tells_the_person_to_ask_for_less(self, _name, timed_out_call, mock_get):+ answers: list[Any] = [_response(SUBSCRIPTION), _response(SERIES)]+ answers[timed_out_call] = requests.Timeout()+ mock_get.side_effect = answers+ response = self.client.get(self._project_url("usage/"))+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.content)+ self.assertEqual(response.json()["code"], "usage_query_timeout")++ @patch("ee.billing.billing_manager.http_session.get")+ def test_project_usage_sums_the_series_since_the_billing_period_began(self, mock_get):+ series = {+ **SERIES,+ "results": [+ {+ "id": 0,+ "label": "Events",+ "data": [1.0, 2.0],+ "dates": ["2026-09-01", "2026-09-02"],+ "breakdown_type": "type",+ "breakdown_value": "event_count_in_period",+ }+ ],+ }+ mock_get.side_effect = [_response(SUBSCRIPTION), _response(series)]+ response = self.client.get(self._project_url("usage/"))+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)+ self.assertEqual(+ response.json()["results"], [{"usage_key": "event_count_in_period", "name": "Events", "usage": 3.0}]+ )+ sent = mock_get.call_args.kwargs["params"]+ self.assertEqual((sent["start_date"], json.loads(sent["team_ids"])), ("2026-09-01", [self.team.id]))diff --git a/ee/billing/exports.py b/ee/billing/exports.pyindex a30dbf578267..bc0634ca336a 100644--- a/ee/billing/exports.py+++ b/ee/billing/exports.py@@ -54,9 +54,16 @@ _EXPORT_STREAMS = RateLimit()+def _export_stream_owner(user: Any) -> str | int:+ """Whose slots an export takes. A project secret key authenticates as a synthetic user that+ every key shares, so its exports count against the key, not that user."""+ key = getattr(user, "project_secret_api_key", None)+ return f"project_secret_api_key_{key.id}" if key is not None else user.pk++def _take_export_stream_slot(user: Any) -> Optional[ConcurrencySlot]:try:- return _EXPORT_STREAMS.use(user.pk)+ return _EXPORT_STREAMS.use(_export_stream_owner(user))except ConcurrencyLimitExceeded:raise Throttled(detail=(diff --git a/ee/urls.py b/ee/urls.pyindex 49237e48e9df..d289f111a343 100644--- a/ee/urls.py+++ b/ee/urls.py@@ -25,7 +25,7 @@ from ee.api.vercel import vercel_connect, vercel_ssofrom ee.middleware import admin_oauth2_callbackfrom ee.support_sidebar_max.views import MaxChatViewSet-from .api import authentication, billing, conversation, core_memory, organization_billing, subscription+from .api import authentication, billing, conversation, core_memory, organization_billing, project_billing, subscriptionfrom .api.scim import views as scim_views@@ -42,6 +42,7 @@ def extend_api_router() -> None:organizations_router.register(r"billing", organization_billing.OrganizationBillingViewSet, "organization_billing", ["organization_id"])+ projects_router.register(r"billing", project_billing.ProjectBillingViewSet, "project_billing", ["team_id"])root_router.register(r"integrations", integration.PublicIntegrationViewSet)projects_router.register(r"hooks", hooks.HookViewSet, "project_hooks", ["team_id"])diff --git a/frontend/src/lib/scopes.tsx b/frontend/src/lib/scopes.tsxindex 268ec41065ba..18432712a74a 100644--- a/frontend/src/lib/scopes.tsx+++ b/frontend/src/lib/scopes.tsx@@ -376,6 +376,7 @@ export const PROJECT_SECRET_API_KEY_ALLOWED_API_SCOPE_ACTION = ['loop:write','experiment:read','offline_evaluation_ingestion:write',+ 'billing:read','replay_scanner:write','session_recording:read',] as constdiff --git a/posthog/api/documentation.py b/posthog/api/documentation.pyindex 7928d02eb979..5a12cd13f51c 100644--- a/posthog/api/documentation.py+++ b/posthog/api/documentation.py@@ -854,7 +854,13 @@ def preprocess_exclude_path_format(endpoints, **kwargs):is_env_duplicate = env_suffix is not None and (env_suffix, method) in projects_suffixesorg_suffix = _extract_root_suffix(_ORG_PREFIX_RE, path)- is_org_duplicate = org_suffix is not None and (org_suffix, method) in projects_suffixes+ # Sharing a suffix usually means one resource served at both levels. A viewset whose organization+ # paths are a different resource opts out with `schema_org_paths_are_not_duplicates = True`.+ is_org_duplicate = (+ org_suffix is not None+ and (org_suffix, method) in projects_suffixes+ and not getattr(callback.cls, "schema_org_paths_are_not_duplicates", False)+ )if is_env_duplicate:path = _ENVIRONMENTS_PREFIX_RE.sub("/api/environments/{environment_id}/", path, count=1)diff --git a/posthog/api/project_secret_api_key.py b/posthog/api/project_secret_api_key.pyindex 6d9f757739b9..cc7af3d79af4 100644--- a/posthog/api/project_secret_api_key.py+++ b/posthog/api/project_secret_api_key.py@@ -16,7 +16,7 @@ from posthog.api.shared import UserBasicSerializerfrom posthog.api.utils import actionfrom posthog.auth import PersonalAPIKeyAuthentication, SessionAuthenticationfrom posthog.llm.wizard_blocklist import WIZARD_BLOCKED_DETAIL, wizard_identity_blocked-from posthog.models import User+from posthog.models import Organization, Userfrom posthog.models.project_secret_api_key import ProjectSecretAPIKey, RevokedTeamSecretTokenfrom posthog.models.utils import generate_random_token_secret, hash_key_value, mask_key_valuefrom posthog.permissions import (@@ -31,6 +31,7 @@ from posthog.scopes import (PROJECT_SECRET_API_KEY_ALLOWED_API_SCOPE_ACTION,scopes_not_covered,)+from posthog.settings import EE_AVAILABLEfrom posthog.tasks.email import send_feature_flags_secure_api_key_exposed, send_project_secret_api_key_exposedfrom posthog.utils import get_trusted_client_ip@@ -38,6 +39,9 @@ from products.security.backend.facade.api import access_refused as security_accefrom products.security.backend.facade.contracts import SubjectInput as SecuritySubjectfrom products.security.backend.facade.enums import Surface as SecuritySurface+if EE_AVAILABLE:+ from ee.billing.grants import BillingEntitlement, effective_billing_grants+logger = structlog.get_logger(__name__)MAX_PROJECT_SECRET_API_KEYS_PER_TEAM = 50@@ -57,6 +61,24 @@ def _enforce_caller_holds_scopes(request: Request, scopes: Iterable[str]) -> Non)+def _enforce_caller_may_grant_billing_read(request: Request, organization: Organization, scopes: Iterable[str]) -> None:+ """A key with billing:read reads its project's usage and share of the organization's spend. Only+ someone with full access to the organization's billing may grant it."""+ if "billing:read" not in scopes:+ return+ if not EE_AVAILABLE:+ raise PermissionDenied("The billing:read scope needs PostHog's enterprise billing, which this instance lacks.")+ user = request.user if isinstance(request.user, User) else None+ grants = effective_billing_grants(+ organization=organization, user=user, authenticator=getattr(request, "successful_authenticator", None)+ )+ if BillingEntitlement.FULL_ACCESS.value not in grants.entitlements:+ raise PermissionDenied(+ "Only someone with full access to the organization's billing can give a project secret API key "+ "the billing:read scope."+ )++def _enforce_gateway_bans(request: Request, team) -> None:"""A phs_ key reaches the gateway with no user attached, so the user bans thatother gateway credential paths enforce run here, when the scope is granted."""@@ -155,6 +177,7 @@ class ProjectSecretAPIKeySerializer(serializers.ModelSerializer):existing = set(self.instance.scopes or []) if self.instance is not None else set()added = [scope for scope in scopes if scope not in existing]_enforce_caller_holds_scopes(self.context["request"], added)+ _enforce_caller_may_grant_billing_read(self.context["request"], self.context["view"].team.organization, added)if "llm_gateway:read" in added:_enforce_gateway_bans(self.context["request"], self.context["view"].team)return scopes@@ -266,6 +289,8 @@ class ProjectSecretAPIKeyViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):def roll(self, request, *args, **kwargs):instance = self.get_object()_enforce_caller_holds_scopes(request, instance.scopes or [])+ # Rolling hands back a usable secret, so it needs what granting the scopes needs.+ _enforce_caller_may_grant_billing_read(request, self.team.organization, instance.scopes or [])serializer = cast(ProjectSecretAPIKeySerializer, self.get_serializer(instance))serializer.roll(instance)return response.Response(serializer.data, status=status.HTTP_200_OK)diff --git a/posthog/api/test/test_api_docs.py b/posthog/api/test/test_api_docs.pyindex 6076667f68ae..bf719b66d9d0 100644--- a/posthog/api/test/test_api_docs.py+++ b/posthog/api/test/test_api_docs.py@@ -28,6 +28,18 @@ class _XInternalMarkerViewSet(viewsets.ViewSet):return Response({"ok": True})+def _thing_viewset(operation_id: str, *, org_paths_are_not_duplicates: bool) -> type[viewsets.ViewSet]:+ class ThingViewSet(viewsets.ViewSet):+ scope_object = "project"+ schema_org_paths_are_not_duplicates = org_paths_are_not_duplicates++ @extend_schema(operation_id=operation_id, responses={200: _XInternalMarkerSerializer})+ def list(self, request: Request) -> Response:+ return Response({"ok": True})++ return ThingViewSet++@extend_schema(responses={200: _XInternalMarkerSerializer}, extensions={"x-internal": True})class _XInternalClassMarkerViewSet(viewsets.ViewSet):scope_object = "project"@@ -55,6 +67,21 @@ class _RequestDependentScopesViewSet(viewsets.ViewSet):class TestAPIDocsSchema(APIBaseTest):+ @parameterized.expand([("duplicate", False, True), ("not_a_duplicate", True, False)])+ def test_org_path_sharing_a_project_suffix(self, _name: str, opted_out: bool, deprecated: bool) -> None:+ org_view = _thing_viewset("thing_list", org_paths_are_not_duplicates=opted_out)+ project_view = _thing_viewset("project_thing_list", org_paths_are_not_duplicates=False)+ patterns = [+ path("api/organizations/<str:parent_lookup_organization_id>/thing/", org_view.as_view({"get": "list"})),+ path("api/projects/<str:parent_lookup_team_id>/thing/", project_view.as_view({"get": "list"})),+ ]++ schema = SchemaGenerator(patterns=patterns).get_schema(request=None, public=True)++ operation = schema["paths"]["/api/organizations/{organization_id}/thing/"]["get"]+ assert operation.get("deprecated", False) is deprecated+ assert operation["operationId"] == ("org_thing_list" if deprecated else "thing_list")+def test_retired_project_environments_route_is_not_in_schema(self) -> None:self.client.logout()diff --git a/posthog/api/test/test_project_secret_api_keys.py b/posthog/api/test/test_project_secret_api_keys.pyindex 9683310e7a2c..004ec70b5567 100644--- a/posthog/api/test/test_project_secret_api_keys.py+++ b/posthog/api/test/test_project_secret_api_keys.py@@ -157,6 +157,50 @@ class TestProjectSecretAPIKeysAPI(APIBaseTest):assert response.status_code == 201, response.json()assert response.json()["scopes"] == ["llm_gateway:read"]+ @parameterized.expand(+ [+ ("granted_with_full_billing_access", False, True, 201),+ ("refused_without_full_billing_access", True, True, 403),+ ("refused_without_enterprise_billing", False, False, 403),+ ]+ )+ @patch("ee.billing.grants._owner_only_billing_enabled")+ def test_create_billing_read_scope_needs_full_billing_access(+ self, _name, owner_only_billing, ee_available, expected_status, mock_owner_only+ ):+ # An admin has full billing access unless owner-only billing is on.+ mock_owner_only.return_value = owner_only_billing++ with patch("posthog.api.project_secret_api_key.EE_AVAILABLE", ee_available):+ response = self.client.post(+ f"/api/projects/{self.team.id}/project_secret_api_keys",+ {"label": "billing key", "scopes": ["billing:read"]},+ )++ assert response.status_code == expected_status, response.json()++ @parameterized.expand(+ [+ ("rolled_with_full_billing_access", False, 200),+ ("refused_without_full_billing_access", True, 403),+ ]+ )+ @patch("ee.billing.grants._owner_only_billing_enabled")+ def test_roll_billing_read_key_needs_full_billing_access(+ self, _name, owner_only_billing, expected_status, mock_owner_only+ ):+ key = ProjectSecretAPIKey.objects.create(+ team=self.team, label="owner's billing key", secure_value="sha256$owner", scopes=["billing:read"]+ )+ # An admin has full billing access unless owner-only billing is on.+ mock_owner_only.return_value = owner_only_billing++ response = self.client.post(f"/api/projects/{self.team.id}/project_secret_api_keys/{key.id}/roll")++ assert response.status_code == expected_status, response.json()+ key.refresh_from_db()+ assert (key.secure_value != "sha256$owner") == (expected_status == 200)+@parameterized.expand([("other_scope", ["endpoint:read"]), ("null_scopes", None)])def test_staff_update_adding_llm_gateway_scope(self, _name, existing_scopes):self._make_staff()diff --git a/posthog/scopes.py b/posthog/scopes.pyindex 1bc155c0d70d..80b4bc9625dc 100644--- a/posthog/scopes.py+++ b/posthog/scopes.py@@ -269,6 +269,9 @@ PROJECT_SECRET_API_KEY_ALLOWED_API_SCOPE_ACTION: list[tuple[APIScopeObject, APIS# experiments into a warehouse don't need a credential tied to one person's account.("experiment", "read"),("offline_evaluation_ingestion", "write"),+ # A project's own usage and share of spend, for a service that watches one project's billing.+ # Only someone with full billing access may grant it (see the key serializer).+ ("billing", "read"),# Lets a service start Replay Vision scans and read their results back through `vision/requests/`.# Both are needed together; every other replay_scanner and session_recording route stays PSAK-denied.("replay_scanner", "write"),diff --git a/products/billing/frontend/generated/api.schemas.ts b/products/billing/frontend/generated/api.schemas.tsindex 090b7079a7eb..f1a5ce49eb65 100644--- a/products/billing/frontend/generated/api.schemas.ts+++ b/products/billing/frontend/generated/api.schemas.ts@@ -1249,6 +1249,22 @@ export interface BillingUsageStatusApi {products: ProductUsageStatusApi[]}+export interface ProjectUsageItemApi {+ /** The usage counter, as the usage series names it. */+ usage_key: string+ /** The counter's display name. */+ name: string+ /** The project's usage of the counter so far this billing period. */+ usage: number+}++export interface ProjectUsageSummaryApi {+ /** The period the usage covers. Null when the organization has no billing period yet, and the usage then covers the current calendar month in UTC. */+ billing_period: BillingPeriodApi | null+ /** One entry per usage counter the project reported. */+ results: ProjectUsageItemApi[]+}+export type BillingSpendRetrieveParams = {/*** The `next` cursor from the previous page. Opaque. Ignored without page_size.@@ -1707,3 +1723,111 @@ export type BillingUsageTimeseriesRetrieveParams = {*/usage_types?: string | null}++export type BillingProjectSpendExportDownloadParams = {+ /**+ * JSON-encoded array of breakdown dimensions. Omit it for one series across the project. Pass `["type"]` for a series per product.+ * @nullable+ */+ breakdowns?: string | null+ /**+ * End date (YYYY-MM-DD, UTC), inclusive. Defaults to yesterday if both dates are omitted, or today if only start_date is provided.+ * @nullable+ */+ end_date?: string | null+ /**+ * @nullable+ */+ interval?: string | null+ /**+ * Start date (YYYY-MM-DD, UTC), or "all" for 2020-01-01. If both dates are omitted, defaults to 30 days ago.+ * @nullable+ */+ start_date?: string | null+ /**+ * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.+ * @nullable+ */+ usage_types?: string | null+}++export type BillingProjectSpendTimeseriesRetrieveParams = {+ /**+ * JSON-encoded array of breakdown dimensions. Omit it for one series across the project. Pass `["type"]` for a series per product.+ * @nullable+ */+ breakdowns?: string | null+ /**+ * End date (YYYY-MM-DD, UTC), inclusive. Defaults to yesterday if both dates are omitted, or today if only start_date is provided.+ * @nullable+ */+ end_date?: string | null+ /**+ * @nullable+ */+ interval?: string | null+ /**+ * Start date (YYYY-MM-DD, UTC), or "all" for 2020-01-01. If both dates are omitted, defaults to 30 days ago.+ * @nullable+ */+ start_date?: string | null+ /**+ * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.+ * @nullable+ */+ usage_types?: string | null+}++export type BillingProjectUsageExportDownloadParams = {+ /**+ * JSON-encoded array of breakdown dimensions. Omit it for one series across the project. Pass `["type"]` for a series per product.+ * @nullable+ */+ breakdowns?: string | null+ /**+ * End date (YYYY-MM-DD, UTC), inclusive. Defaults to yesterday if both dates are omitted, or today if only start_date is provided.+ * @nullable+ */+ end_date?: string | null+ /**+ * @nullable+ */+ interval?: string | null+ /**+ * Start date (YYYY-MM-DD, UTC), or "all" for 2020-01-01. If both dates are omitted, defaults to 30 days ago.+ * @nullable+ */+ start_date?: string | null+ /**+ * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.+ * @nullable+ */+ usage_types?: string | null+}++export type BillingProjectUsageTimeseriesRetrieveParams = {+ /**+ * JSON-encoded array of breakdown dimensions. Omit it for one series across the project. Pass `["type"]` for a series per product.+ * @nullable+ */+ breakdowns?: string | null+ /**+ * End date (YYYY-MM-DD, UTC), inclusive. Defaults to yesterday if both dates are omitted, or today if only start_date is provided.+ * @nullable+ */+ end_date?: string | null+ /**+ * @nullable+ */+ interval?: string | null+ /**+ * Start date (YYYY-MM-DD, UTC), or "all" for 2020-01-01. If both dates are omitted, defaults to 30 days ago.+ * @nullable+ */+ start_date?: string | null+ /**+ * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.+ * @nullable+ */+ usage_types?: string | null+}diff --git a/products/billing/frontend/generated/api.ts b/products/billing/frontend/generated/api.tsindex 16876a9d3104..b2aa0aa3a10b 100644--- a/products/billing/frontend/generated/api.ts+++ b/products/billing/frontend/generated/api.ts@@ -29,6 +29,10 @@ import type {BillingProductsListParams,BillingProductsRetrieveParams,BillingProductsSummaryApi,+ BillingProjectSpendExportDownloadParams,+ BillingProjectSpendTimeseriesRetrieveParams,+ BillingProjectUsageExportDownloadParams,+ BillingProjectUsageTimeseriesRetrieveParams,BillingProjectsApi,BillingSpendExportDownloadParams,BillingSpendExportRetrieveParams,@@ -49,6 +53,7 @@ import type {PaginatedBillingTimeSeriesPointListApi,PatchedBillingAlertConfigurationApi,PatchedBillingApi,+ ProjectUsageSummaryApi,} from './api.schemas'// https://stackoverflow.com/questions/49579094/typescript-conditional-types-filter-out-readonly-properties-pick-only-requir/49579497#49579497@@ -1036,3 +1041,163 @@ export const billingUsageTimeseriesRetrieve = async (})}++export const getBillingProjectSpendExportDownloadUrl = (+ projectId: string,+ params?: BillingProjectSpendExportDownloadParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/billing/spend/export/?${stringifiedParams}`+ : `/api/projects/${projectId}/billing/spend/export/`+}++/**+ * In beta: the organization billing API is behind the organization-billing-api feature flag and answers 403 without it, so ask support for access. Its shapes may change while it is in beta.+ * @summary Export a project's share of spend as CSV+ */+export const billingProjectSpendExportDownload = async (+ projectId: string,+ params?: BillingProjectSpendExportDownloadParams,+ options?: RequestInit+): Promise<Blob> => {+ return apiMutator<Blob>(getBillingProjectSpendExportDownloadUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}++export const getBillingProjectSpendTimeseriesRetrieveUrl = (+ projectId: string,+ params?: BillingProjectSpendTimeseriesRetrieveParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/billing/spend/timeseries/?${stringifiedParams}`+ : `/api/projects/${projectId}/billing/spend/timeseries/`+}++/**+ * In beta: the organization billing API is behind the organization-billing-api feature flag and answers 403 without it, so ask support for access. Its shapes may change while it is in beta.+ * @summary A project's share of spend over time+ */+export const billingProjectSpendTimeseriesRetrieve = async (+ projectId: string,+ params?: BillingProjectSpendTimeseriesRetrieveParams,+ options?: RequestInit+): Promise<PaginatedBillingTimeSeriesPointListApi> => {+ return apiMutator<PaginatedBillingTimeSeriesPointListApi>(+ getBillingProjectSpendTimeseriesRetrieveUrl(projectId, params),+ {+ ...options,+ method: 'GET',+ }+ )+}++export const getBillingProjectUsageRetrieveUrl = (projectId: string) => {+ return `/api/projects/${projectId}/billing/usage/`+}++/**+ * In beta: the organization billing API is behind the organization-billing-api feature flag and answers 403 without it, so ask support for access. Its shapes may change while it is in beta.+ * @summary Get a project's usage so far this billing period+ */+export const billingProjectUsageRetrieve = async (+ projectId: string,+ options?: RequestInit+): Promise<ProjectUsageSummaryApi> => {+ return apiMutator<ProjectUsageSummaryApi>(getBillingProjectUsageRetrieveUrl(projectId), {+ ...options,+ method: 'GET',+ })+}++export const getBillingProjectUsageExportDownloadUrl = (+ projectId: string,+ params?: BillingProjectUsageExportDownloadParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/billing/usage/export/?${stringifiedParams}`+ : `/api/projects/${projectId}/billing/usage/export/`+}++/**+ * In beta: the organization billing API is behind the organization-billing-api feature flag and answers 403 without it, so ask support for access. Its shapes may change while it is in beta.+ * @summary Export a project's usage as CSV+ */+export const billingProjectUsageExportDownload = async (+ projectId: string,+ params?: BillingProjectUsageExportDownloadParams,+ options?: RequestInit+): Promise<Blob> => {+ return apiMutator<Blob>(getBillingProjectUsageExportDownloadUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}++export const getBillingProjectUsageTimeseriesRetrieveUrl = (+ projectId: string,+ params?: BillingProjectUsageTimeseriesRetrieveParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/billing/usage/timeseries/?${stringifiedParams}`+ : `/api/projects/${projectId}/billing/usage/timeseries/`+}++/**+ * In beta: the organization billing API is behind the organization-billing-api feature flag and answers 403 without it, so ask support for access. Its shapes may change while it is in beta.+ * @summary A project's usage over time+ */+export const billingProjectUsageTimeseriesRetrieve = async (+ projectId: string,+ params?: BillingProjectUsageTimeseriesRetrieveParams,+ options?: RequestInit+): Promise<PaginatedBillingTimeSeriesPointListApi> => {+ return apiMutator<PaginatedBillingTimeSeriesPointListApi>(+ getBillingProjectUsageTimeseriesRetrieveUrl(projectId, params),+ {+ ...options,+ method: 'GET',+ }+ )+}diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex ee9acb2f8691..dd6fb1af6060 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -90162,6 +90162,22 @@ export namespace Schemas {payload?: ProjectProfilePayload;}+ export interface ProjectUsageItem {+ /** The usage counter, as the usage series names it. */+ usage_key: string;+ /** The counter's display name. */+ name: string;+ /** The project's usage of the counter so far this billing period. */+ usage: number;+ }++ export interface ProjectUsageSummary {+ /** The period the usage covers. Null when the organization has no billing period yet, and the usage then covers the current calendar month in UTC. */+ billing_period: BillingPeriod | null;+ /** One entry per usage counter the project reported. */+ results: ProjectUsageItem[];+ }+export interface Property {/*** You can use a simplified version:@@ -119357,6 +119373,114 @@ export namespace Schemas {search?: string;};+ export type BillingProjectSpendExportDownloadParams = {+ /**+ * JSON-encoded array of breakdown dimensions. Omit it for one series across the project. Pass `["type"]` for a series per product.+ * @nullable+ */+ breakdowns?: string | null;+ /**+ * End date (YYYY-MM-DD, UTC), inclusive. Defaults to yesterday if both dates are omitted, or today if only start_date is provided.+ * @nullable+ */+ end_date?: string | null;+ /**+ * @nullable+ */+ interval?: string | null;+ /**+ * Start date (YYYY-MM-DD, UTC), or "all" for 2020-01-01. If both dates are omitted, defaults to 30 days ago.+ * @nullable+ */+ start_date?: string | null;+ /**+ * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.+ * @nullable+ */+ usage_types?: string | null;+ };++ export type BillingProjectSpendTimeseriesRetrieveParams = {+ /**+ * JSON-encoded array of breakdown dimensions. Omit it for one series across the project. Pass `["type"]` for a series per product.+ * @nullable+ */+ breakdowns?: string | null;+ /**+ * End date (YYYY-MM-DD, UTC), inclusive. Defaults to yesterday if both dates are omitted, or today if only start_date is provided.+ * @nullable+ */+ end_date?: string | null;+ /**+ * @nullable+ */+ interval?: string | null;+ /**+ * Start date (YYYY-MM-DD, UTC), or "all" for 2020-01-01. If both dates are omitted, defaults to 30 days ago.+ * @nullable+ */+ start_date?: string | null;+ /**+ * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.+ * @nullable+ */+ usage_types?: string | null;+ };++ export type BillingProjectUsageExportDownloadParams = {+ /**+ * JSON-encoded array of breakdown dimensions. Omit it for one series across the project. Pass `["type"]` for a series per product.+ * @nullable+ */+ breakdowns?: string | null;+ /**+ * End date (YYYY-MM-DD, UTC), inclusive. Defaults to yesterday if both dates are omitted, or today if only start_date is provided.+ * @nullable+ */+ end_date?: string | null;+ /**+ * @nullable+ */+ interval?: string | null;+ /**+ * Start date (YYYY-MM-DD, UTC), or "all" for 2020-01-01. If both dates are omitted, defaults to 30 days ago.+ * @nullable+ */+ start_date?: string | null;+ /**+ * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.+ * @nullable+ */+ usage_types?: string | null;+ };++ export type BillingProjectUsageTimeseriesRetrieveParams = {+ /**+ * JSON-encoded array of breakdown dimensions. Omit it for one series across the project. Pass `["type"]` for a series per product.+ * @nullable+ */+ breakdowns?: string | null;+ /**+ * End date (YYYY-MM-DD, UTC), inclusive. Defaults to yesterday if both dates are omitted, or today if only start_date is provided.+ * @nullable+ */+ end_date?: string | null;+ /**+ * @nullable+ */+ interval?: string | null;+ /**+ * Start date (YYYY-MM-DD, UTC), or "all" for 2020-01-01. If both dates are omitted, defaults to 30 days ago.+ * @nullable+ */+ start_date?: string | null;+ /**+ * JSON-encoded array of usage type identifiers to filter on. Valid values: event_count_in_period, exceptions_captured_in_period, recording_count_in_period, rows_synced_in_period, free_historical_rows_synced_in_period, survey_responses_count_in_period, mobile_recording_count_in_period, mobile_billable_recording_count_in_period, billable_feature_flag_requests_count_in_period, enhanced_persons_event_count_in_period, ai_event_count_in_period, cdp_billable_invocations_in_period, rows_exported_in_period, ai_credits_used_in_period, signals_credits_used_in_period, posthog_code_credits_used_in_period, posthog_code_token_credits_used_in_period, sandbox_compute_credits_used_in_period, sandbox_compute_cpu_millicore_seconds_in_period, sandbox_compute_memory_mib_seconds_in_period, workflow_emails_sent_in_period, workflow_billable_invocations_in_period, logs_mb_in_period, logs_retention_30d_mb_in_period, logs_retention_mb_days_in_period, replay_vision_credits_used_in_period, data_pipelines, group_analytics. E.g. ["event_count_in_period","recording_count_in_period"]. Omit for all types.+ * @nullable+ */+ usage_types?: string | null;+ };+export type BusinessKnowledgeDocumentsWindowListParams = {/*** Zero-based chunk ordinal to center the window on (from a search result).