: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(llma): add posthog code token spend analysis endpoint (#59017)
Paul D'Ambra089111fcba0e
diff --git a/posthog/api/__init__.py b/posthog/api/__init__.pyindex 24d68642dc6a..0aa39c5a8730 100644--- a/posthog/api/__init__.py+++ b/posthog/api/__init__.py@@ -22,7 +22,7 @@ from posthog.api.sdk_doctor import SdkDoctorViewSetfrom posthog.api.wizard import http as wizardfrom posthog.approvals import api as approval_apifrom posthog.batch_exports import http as batch_exports-from posthog.settings import EE_AVAILABLE+from posthog.settings import CLOUD_DEPLOYMENT, DEBUG, EE_AVAILABLE, TESTimport products.logs.backend.api as logsimport products.links.backend.api as link@@ -97,6 +97,7 @@ from products.llm_analytics.backend.api import (LLMProviderKeyValidationViewSet,LLMProviderKeyViewSet,LLMProxyViewSet,+ PersonalSpendViewSet,ReviewQueueItemViewSet,ReviewQueueViewSet,ScoreDefinitionViewSet,@@ -218,6 +219,12 @@ router.register(r"plugin_config", plugin.LegacyPluginConfigViewSet, "legacy_plugrouter.register(r"feature_flag", feature_flag.LegacyFeatureFlagViewSet) # Used for library side feature flag evaluationrouter.register(r"llm_proxy", LLMProxyViewSet, "llm_proxy")+# Personal LLM spend data lives only in PostHog Cloud US's internal team — register+# the endpoint there plus dev/test envs so it stays reachable in development. EU+# adds a redirect (declared in posthog/urls.py) so callers get a discoverable+# pointer instead of a silent 404.+if CLOUD_DEPLOYMENT == "US" or DEBUG or TEST:+ router.register(r"llm_analytics/@me/spend", PersonalSpendViewSet, "personal_spend")router.register(r"mcp_store/oauth_redirect", mcp_store.MCPOAuthRedirectViewSet, "mcp_oauth_redirect")# Nested endpoints sharedprojects_router = router.register(r"projects", project.RootProjectViewSet, "projects")diff --git a/posthog/rate_limit.py b/posthog/rate_limit.pyindex c3cba51c66e9..f7cc8741a699 100644--- a/posthog/rate_limit.py+++ b/posthog/rate_limit.py@@ -560,6 +560,26 @@ class LLMAnalyticsSummarizationDailyThrottle(PersonalApiKeyRateThrottle):rate = "500/day"+class PersonalSpendBurstThrottle(PersonalApiKeyOrUserRateThrottle):+ # Burst limit for the personal LLM spend analysis endpoint.+ # ClickHouse-bound; protects against impatient refresh-spamming.+ # Applies to session-auth users too — they are the primary callers.+ scope = "personal_spend_burst"+ rate = "10/minute"+++class PersonalSpendSustainedThrottle(PersonalApiKeyOrUserRateThrottle):+ # Sustained limit for the personal LLM spend analysis endpoint.+ scope = "personal_spend_sustained"+ rate = "60/hour"+++class PersonalSpendDailyThrottle(PersonalApiKeyOrUserRateThrottle):+ # Daily cap for the personal LLM spend analysis endpoint.+ scope = "personal_spend_daily"+ rate = "200/day"++class LLMPromptPublishBurstRateThrottle(PersonalApiKeyOrUserRateThrottle):# Stricter burst limit for publishing prompt versions.# This protects against accidental loops or scripted abuse while allowing normal usage.diff --git a/posthog/settings/base_variables.py b/posthog/settings/base_variables.pyindex e34f420c632f..36de9f02c95c 100644--- a/posthog/settings/base_variables.py+++ b/posthog/settings/base_variables.py@@ -50,6 +50,12 @@ SERVER_GATEWAY_INTERFACE = get_from_env("SERVER_GATEWAY_INTERFACE", "WSGI", type# GitHub secret alert relay URL - set in US deployment to forward alerts to EUGITHUB_SECRET_ALERT_RELAY_URL: str | None = get_from_env("GITHUB_SECRET_ALERT_RELAY_URL", optional=True)+# Internal team on PostHog Cloud US that receives `$ai_generation` /+# `$ai_embedding` events emitted by PostHog products (PostHog Code,+# background agents, etc). Used by /api/llm_analytics/personal_spend/.+# Override in tests via @override_settings to point at a per-test team.+LLM_ANALYTICS_INTERNAL_TEAM_ID: int = 2+# Duckgres - URL, internal secret, and PG endpoint for the managed warehouse serviceDUCKGRES_API_URL: str | None = get_from_env("DUCKGRES_API_URL", optional=True)DUCKGRES_INTERNAL_SECRET: str | None = get_from_env("DUCKGRES_INTERNAL_SECRET", optional=True)diff --git a/posthog/urls.py b/posthog/urls.pyindex 1d0558a5749e..84f3d2f52f84 100644--- a/posthog/urls.py+++ b/posthog/urls.py@@ -51,6 +51,7 @@ from products.data_warehouse.backend.api.public_source_configs import PublicSourfrom products.deployments.backend.api.internal import InternalDeploymentTransitionsViewSetfrom products.early_access_features.backend.api import early_access_featuresfrom products.legal_documents.backend.presentation.webhook import legal_document_pandadoc_webhook+from products.llm_analytics.backend.api.personal_spend import personal_spend_eu_redirectfrom products.messaging.backend.api.customerio_webhook import CustomerIOWebhookViewfrom products.product_tours.backend.api import product_toursfrom products.signals.backend import views as signals_views@@ -411,6 +412,18 @@ urlpatterns = [opt_slash_path("messaging-preferences/update", update_preferences, name="message_preferences_update"),]+# Personal LLM spend data only lives in PostHog Cloud US — EU forwards its product+# LLM telemetry over, so EU callers get a 302 to the US-hosted endpoint instead of+# a silent 404.+if settings.CLOUD_DEPLOYMENT == "EU":+ urlpatterns += [+ path(+ "api/llm_analytics/@me/spend/",+ personal_spend_eu_redirect,+ name="personal_spend_eu_redirect",+ ),+ ]+if settings.DEBUG:# If we have DEBUG=1 set, then let's expose the metrics for debugging. Note# that in production we expose these metrics on a separate port (8001), to ensurediff --git a/products/llm_analytics/backend/api/__init__.py b/products/llm_analytics/backend/api/__init__.pyindex 9ebe72699008..506bf1ef1019 100644--- a/products/llm_analytics/backend/api/__init__.py+++ b/products/llm_analytics/backend/api/__init__.py@@ -9,6 +9,7 @@ from .evaluation_summary import LLMEvaluationSummaryViewSetfrom .evaluations import EvaluationViewSetfrom .models import LLMModelsViewSetfrom .offline_evaluations import LLMAnalyticsOfflineEvaluationsViewSet+from .personal_spend import PersonalSpendViewSetfrom .provider_keys import LLMProviderKeyValidationViewSet, LLMProviderKeyViewSetfrom .proxy import SUPPORTED_MODELS_WITH_THINKING, LLMProxyViewSetfrom .review_queues import ReviewQueueItemViewSet, ReviewQueueViewSet@@ -44,6 +45,7 @@ __all__ = ["ScoreDefinitionViewSet","LLMAnalyticsSentimentViewSet","LLMAnalyticsOfflineEvaluationsViewSet",+ "PersonalSpendViewSet","TaggerViewSet","TraceReviewViewSet",]diff --git a/products/llm_analytics/backend/api/personal_spend.py b/products/llm_analytics/backend/api/personal_spend.pynew file mode 100644index 000000000000..3890a58323ca--- /dev/null+++ b/products/llm_analytics/backend/api/personal_spend.py@@ -0,0 +1,690 @@+"""+Personal LLM spend analysis endpoint.++Surfaces the requesting user's own LLM spend across PostHog products (last N+days) by running a fixed set of HogQL queries against PostHog's internal cloud+analytics team. Optionally filter to a single `ai_product` (e.g. `posthog_code`,+`background_agents`) — when omitted, results aggregate across every product+captured by LLM analytics for that user.++Endpoint:+- GET /api/llm_analytics/@me/spend/?date_from=-30d&date_to=&product=<key>&limit=50&refresh=false+"""++from __future__ import annotations++import re+import datetime+from typing import Any, cast+from urllib.parse import urlencode+from zoneinfo import ZoneInfo++from django.conf import settings+from django.core.cache import cache+from django.http import HttpRequest, HttpResponseRedirect++import structlog+from drf_spectacular.utils import extend_schema+from rest_framework import exceptions, permissions, serializers, status, viewsets+from rest_framework.request import Request+from rest_framework.response import Response++from posthog.hogql import ast+from posthog.hogql.parser import parse_select++from posthog.hogql_queries.ai.ai_table_resolver import execute_with_ai_events_fallback+from posthog.models import Team, User+from posthog.rate_limit import PersonalSpendBurstThrottle, PersonalSpendDailyThrottle, PersonalSpendSustainedThrottle+from posthog.utils import relative_date_parse++logger = structlog.get_logger(__name__)++MAX_PRODUCT_KEY_LENGTH = 64+MAX_DATE_STRING_LENGTH = 32++DEFAULT_DATE_FROM = "-30d"+MAX_WINDOW_DAYS = 90+_RELATIVE_DATE_RE = re.compile(r"^-?\d+[hdwmqyHDWMQY](Start|End)?$")++MIN_LIMIT = 1+MAX_LIMIT = 200+DEFAULT_LIMIT = 50++CACHE_TIMEOUT_SECONDS = 300++UTC = ZoneInfo("UTC")+++def _internal_team_id() -> int:+ return settings.LLM_ANALYTICS_INTERNAL_TEAM_ID+++def _cache_key(email: str, date_from: str, date_to: str | None, product: str | None, limit: int) -> str:+ product_slot = product or "_all"+ to_slot = date_to or "_now"+ return f"personal_spend:{email}:{date_from}:{to_slot}:{product_slot}:{limit}"+++def _parse_date_param(value: str, field: str, now: datetime.datetime) -> datetime.datetime:+ """Accepts either an ISO date / datetime or a relative shorthand like `-7d`. Rejects garbage."""+ looks_relative = _RELATIVE_DATE_RE.match(value) is not None+ looks_iso = value[:1].isdigit()+ if not (looks_relative or looks_iso):+ raise exceptions.ValidationError(+ {+ field: f"Could not parse `{value}`. Use an ISO date (e.g. `2026-04-23`) or relative shorthand (e.g. `-7d`)."+ }+ )+ try:+ return relative_date_parse(value, UTC, now=now)+ except Exception as exc:+ raise exceptions.ValidationError({field: f"Could not parse `{value}`: {exc}"})+++def _resolve_window(date_from: str, date_to: str | None) -> tuple[datetime.datetime, datetime.datetime]:+ """Resolve relative or absolute date strings to UTC datetimes, capped at MAX_WINDOW_DAYS."""+ now = datetime.datetime.now(UTC)+ from_dt = _parse_date_param(date_from, "date_from", now)+ to_dt = _parse_date_param(date_to, "date_to", now) if date_to else now++ if to_dt <= from_dt:+ raise exceptions.ValidationError({"date_to": "Must be later than `date_from`."})+ if (to_dt - from_dt).total_seconds() > MAX_WINDOW_DAYS * 86400:+ raise exceptions.ValidationError(+ {"date_from": f"Window between `date_from` and `date_to` cannot exceed {MAX_WINDOW_DAYS} days."}+ )+ return from_dt, to_dt+++class _SpendQueryParamsSerializer(serializers.Serializer):+ date_from = serializers.CharField(+ required=False,+ default=DEFAULT_DATE_FROM,+ max_length=MAX_DATE_STRING_LENGTH,+ help_text=(+ "Start of the spend window. Accepts absolute dates (`2026-04-23`) or relative strings "+ "(`-7d`, `-1m`, etc.) — same parser used elsewhere in PostHog. Defaults to `-30d`. The "+ "window between `date_from` and `date_to` cannot exceed 90 days."+ ),+ )+ date_to = serializers.CharField(+ required=False,+ default=None,+ allow_null=True,+ max_length=MAX_DATE_STRING_LENGTH,+ help_text=("End of the spend window. Accepts the same formats as `date_from`. Defaults to `now` when omitted."),+ )+ product = serializers.CharField(+ required=False,+ allow_null=True,+ allow_blank=False,+ max_length=MAX_PRODUCT_KEY_LENGTH,+ default=None,+ help_text=(+ "Optional `ai_product` key to scope the tool / model / trace breakdowns to a single product "+ "(e.g. `posthog_code`, `background_agents`). When omitted, those breakdowns aggregate across "+ "every product captured for the user."+ ),+ )+ limit = serializers.IntegerField(+ required=False,+ min_value=MIN_LIMIT,+ max_value=MAX_LIMIT,+ default=DEFAULT_LIMIT,+ help_text=(+ f"Maximum number of rows to return per breakdown ({MIN_LIMIT}-{MAX_LIMIT}, defaults to {DEFAULT_LIMIT}). "+ "Each breakdown returns up to this many rows ordered by cost descending. "+ "Per-breakdown `truncated: true` indicates more rows exist beyond the limit."+ ),+ )+ refresh = serializers.BooleanField(+ required=False,+ default=False,+ help_text="If true, bypass the result cache and re-run the underlying queries against ClickHouse.",+ )+++class _ProductBreakdownRowSerializer(serializers.Serializer):+ product = serializers.CharField(+ allow_null=True,+ help_text="Value of the `ai_product` property on the event (e.g. `posthog_code`, `background_agents`). Null when unset.",+ )+ event_count = serializers.IntegerField(+ help_text="Number of $ai_generation + $ai_embedding events for this product."+ )+ cost_usd = serializers.FloatField(help_text="Total cost in USD for this product over the lookback window.")+++class _ToolBreakdownRowSerializer(serializers.Serializer):+ tool = serializers.CharField(+ allow_null=True,+ help_text=(+ "Individual tool name from `$ai_tools_called` (split on `,` since multi-tool generations "+ "store a comma-separated list). Null = pure text response with no tool call."+ ),+ )+ generation_count = serializers.IntegerField(+ help_text="Number of $ai_generation events whose tool list includes this tool."+ )+ cost_usd = serializers.FloatField(+ help_text=(+ "Sum of `$ai_total_cost_usd` for generations whose tool list includes this tool. Multi-tool "+ "generations contribute their full cost to every tool they invoked, so this sum can exceed "+ "`summary.scoped_cost_usd`. Prefer `share_of_scoped` for headline percentages — it's computed "+ "per row and doesn't require the totals to reconcile."+ ),+ )+ share_of_scoped = serializers.FloatField(+ help_text=(+ "This tool's share of `summary.scoped_cost_usd`, expressed as a float in `[0, 1]`. Independent "+ "per row, so co-occurring tools can each show a substantial share — the headline number to "+ "present (e.g. `'Bash drove 47% of your spend'`)."+ ),+ )+ avg_input_tokens = serializers.FloatField(+ help_text="Average `$ai_input_tokens` across these generations — high values signal context bloat per call.",+ )+++class _ModelBreakdownRowSerializer(serializers.Serializer):+ model = serializers.CharField(allow_null=True, help_text="Value of the `$ai_model` property.")+ generation_count = serializers.IntegerField(help_text="Number of $ai_generation + $ai_embedding events.")+ cost_usd = serializers.FloatField(help_text="Total cost in USD for this model.")+ input_tokens = serializers.IntegerField(help_text="Sum of `$ai_input_tokens` for this model.")+ output_tokens = serializers.IntegerField(help_text="Sum of `$ai_output_tokens` for this model.")+++class _TopTraceRowSerializer(serializers.Serializer):+ trace_id = serializers.CharField(+ allow_null=True,+ help_text=(+ "`$ai_trace_id` of the session — opaque string scoped to the originating product. Format is "+ "not stable: most are UUIDs but some SDK wrappers emit JSON-shaped strings like "+ '`{"device_id":"...","session_id":"..."}`. Callers should treat this as an opaque '+ "identifier (URL-encode before linking to a trace view)."+ ),+ )+ generation_count = serializers.IntegerField(help_text="Number of $ai_generation events in this trace.")+ cost_usd = serializers.FloatField(help_text="Total cost in USD for this trace.")+ started_at = serializers.DateTimeField(allow_null=True, help_text="Timestamp of the earliest event in this trace.")+++class _SummarySerializer(serializers.Serializer):+ date_from = serializers.DateTimeField(+ help_text="Inclusive UTC start of the spend window resolved from the request."+ )+ date_to = serializers.DateTimeField(help_text="Exclusive UTC end of the spend window resolved from the request.")+ product = serializers.CharField(+ allow_null=True,+ help_text="The `ai_product` filter applied to tool / model / trace breakdowns. Null when unfiltered.",+ )+ total_cost_usd = serializers.FloatField(+ help_text="Total LLM cost in USD across every `ai_product` for the user — independent of the `product` filter."+ )+ event_count = serializers.IntegerField(+ help_text="Total $ai_generation + $ai_embedding events captured across every product."+ )+ scoped_cost_usd = serializers.FloatField(+ help_text=(+ "Total cost in USD for the product filter (or all products when unfiltered). Matches the cost summed "+ "across `by_tool` / `by_model` for the scoped slice."+ ),+ )+ scoped_event_count = serializers.IntegerField(+ help_text="Total $ai_generation + $ai_embedding events for the scoped slice."+ )+++class _ErrorResponseSerializer(serializers.Serializer):+ """DRF's default error envelope — `{ "detail": str }` — typed for the OpenAPI schema."""++ detail = serializers.CharField(help_text="Human-readable error description from DRF.")+++class _ProductBreakdownSerializer(serializers.Serializer):+ items = _ProductBreakdownRowSerializer(many=True, help_text="Rows of spend by product, ordered by cost descending.")+ truncated = serializers.BooleanField(+ help_text="True when more rows exist beyond the requested `limit`. Re-request with a larger `limit` to retrieve them."+ )+++class _ToolBreakdownSerializer(serializers.Serializer):+ items = _ToolBreakdownRowSerializer(many=True, help_text="Rows of spend by tool, ordered by cost descending.")+ truncated = serializers.BooleanField(+ help_text="True when more rows exist beyond the requested `limit`. Re-request with a larger `limit` to retrieve them."+ )+++class _ModelBreakdownSerializer(serializers.Serializer):+ items = _ModelBreakdownRowSerializer(many=True, help_text="Rows of spend by model, ordered by cost descending.")+ truncated = serializers.BooleanField(+ help_text="True when more rows exist beyond the requested `limit`. Re-request with a larger `limit` to retrieve them."+ )+++class _TopTracesSerializer(serializers.Serializer):+ items = _TopTraceRowSerializer(many=True, help_text="Rows of top traces by cost, ordered by cost descending.")+ truncated = serializers.BooleanField(+ help_text="True when more rows exist beyond the requested `limit`. Re-request with a larger `limit` to retrieve them."+ )+++class PersonalSpendAnalysisResponseSerializer(serializers.Serializer):+ """Structured personal LLM spend analysis for the requesting user."""++ summary = _SummarySerializer(help_text="High-level totals for the lookback window.")+ by_product = _ProductBreakdownSerializer(+ help_text="Spend grouped by the `ai_product` property — always across all products, never filtered."+ )+ by_tool = _ToolBreakdownSerializer(help_text="Spend grouped by tool. Scoped to `product` when set.")+ by_model = _ModelBreakdownSerializer(help_text="Spend grouped by `$ai_model`. Scoped to `product` when set.")+ top_traces = _TopTracesSerializer(+ help_text="Most expensive trace IDs (sessions) in the window. Scoped to `product` when set."+ )+++def _email_filter(email: str) -> ast.Expr:+ # With person-on-events mode `person.properties.email` is a denormalized column on+ # the events row, so this is a single column read rather than a join — it also catches+ # every event the user identified with, including historical distinct_ids merged into+ # the same person.+ return ast.CompareOperation(+ op=ast.CompareOperationOp.Eq,+ left=ast.Field(chain=["person", "properties", "email"]),+ right=ast.Constant(value=email),+ )+++def _timestamp_filter(from_dt: datetime.datetime, to_dt: datetime.datetime) -> ast.Expr:+ return ast.And(+ exprs=[+ ast.CompareOperation(+ op=ast.CompareOperationOp.GtEq,+ left=ast.Field(chain=["timestamp"]),+ right=ast.Constant(value=from_dt),+ ),+ ast.CompareOperation(+ op=ast.CompareOperationOp.Lt,+ left=ast.Field(chain=["timestamp"]),+ right=ast.Constant(value=to_dt),+ ),+ ]+ )+++def _event_in(events: list[str]) -> ast.Expr:+ return ast.CompareOperation(+ op=ast.CompareOperationOp.In,+ left=ast.Field(chain=["event"]),+ right=ast.Tuple(exprs=[ast.Constant(value=e) for e in events]),+ )+++def _ai_product_eq(value: str) -> ast.Expr:+ return ast.CompareOperation(+ op=ast.CompareOperationOp.Eq,+ left=ast.Field(chain=["properties", "ai_product"]),+ right=ast.Constant(value=value),+ )+++def _true() -> ast.Expr:+ """Identity filter used when no product scoping is requested."""+ return ast.Constant(value=True)+++def _product_filter(product: str | None) -> ast.Expr:+ return _ai_product_eq(product) if product else _true()+++def _truncate(rows: list[dict[str, Any]], limit: int) -> dict[str, Any]:+ """Trim a `limit + 1` row fetch back down to `limit` rows and set the `truncated` flag."""+ return {"items": rows[:limit], "truncated": len(rows) > limit}+++def _fetch_summary(+ team: Team, email: str, from_dt: datetime.datetime, to_dt: datetime.datetime, product: str | None+) -> dict[str, Any]:+ query = parse_select(+ """+ SELECT+ countIf({product_filter}) AS scoped_event_count,+ round(sumIf(toFloat(properties.$ai_total_cost_usd), {product_filter}), 6) AS scoped_cost_usd,+ count() AS event_count,+ round(sum(toFloat(properties.$ai_total_cost_usd)), 6) AS total_cost_usd+ FROM posthog.ai_events+ WHERE {event_in} AND {email_filter} AND {timestamp_filter}+ """+ )+ result = execute_with_ai_events_fallback(+ query=query,+ placeholders={+ "product_filter": _product_filter(product),+ "event_in": _event_in(["$ai_generation", "$ai_embedding"]),+ "email_filter": _email_filter(email),+ "timestamp_filter": _timestamp_filter(from_dt, to_dt),+ },+ team=team,+ query_type="PersonalSpendSummary",+ )+ row = (result.results or [(0, 0.0, 0, 0.0)])[0]+ return {+ "date_from": from_dt,+ "date_to": to_dt,+ "product": product,+ "scoped_event_count": int(row[0] or 0),+ "scoped_cost_usd": float(row[1] or 0.0),+ "event_count": int(row[2] or 0),+ "total_cost_usd": float(row[3] or 0.0),+ }+++def _fetch_by_product(+ team: Team, email: str, from_dt: datetime.datetime, to_dt: datetime.datetime, limit: int+) -> dict[str, Any]:+ query = parse_select(+ """+ SELECT+ properties.ai_product AS product,+ count() AS event_count,+ round(sum(toFloat(properties.$ai_total_cost_usd)), 6) AS cost_usd+ FROM posthog.ai_events+ WHERE {event_in} AND {email_filter} AND {timestamp_filter}+ GROUP BY product+ ORDER BY cost_usd DESC+ LIMIT {limit}+ """+ )+ result = execute_with_ai_events_fallback(+ query=query,+ placeholders={+ "event_in": _event_in(["$ai_generation", "$ai_embedding"]),+ "email_filter": _email_filter(email),+ "timestamp_filter": _timestamp_filter(from_dt, to_dt),+ "limit": ast.Constant(value=limit + 1),+ },+ team=team,+ query_type="PersonalSpendByProduct",+ )+ rows = [+ {+ "product": row[0] if row[0] is not None else None,+ "event_count": int(row[1] or 0),+ "cost_usd": float(row[2] or 0.0),+ }+ for row in (result.results or [])+ ]+ return _truncate(rows, limit)+++def _fetch_by_tool(+ team: Team,+ email: str,+ from_dt: datetime.datetime,+ to_dt: datetime.datetime,+ product: str | None,+ limit: int,+) -> dict[str, Any]:+ # `$ai_tools_called` stores a comma-separated list of all tools called within a+ # generation (e.g. "Bash,Read"). Split it so multi-tool generations contribute to+ # each individual tool row. nullIf restores the no-tool case (where the property+ # is NULL and coalesce produces an empty string) to a NULL bucket.+ query = parse_select(+ """+ SELECT+ nullIf(arrayJoin(splitByChar(',', coalesce(properties.$ai_tools_called, ''))), '') AS tool,+ count() AS generation_count,+ round(sum(toFloat(properties.$ai_total_cost_usd)), 6) AS cost_usd,+ round(avg(toFloat(properties.$ai_input_tokens)), 0) AS avg_input_tokens+ FROM posthog.ai_events+ WHERE equals(event, '$ai_generation')+ AND {product_filter}+ AND {email_filter}+ AND {timestamp_filter}+ GROUP BY tool+ ORDER BY cost_usd DESC+ LIMIT {limit}+ """+ )+ result = execute_with_ai_events_fallback(+ query=query,+ placeholders={+ "product_filter": _product_filter(product),+ "email_filter": _email_filter(email),+ "timestamp_filter": _timestamp_filter(from_dt, to_dt),+ "limit": ast.Constant(value=limit + 1),+ },+ team=team,+ query_type="PersonalSpendByTool",+ )+ rows = [+ {+ "tool": row[0] if row[0] is not None else None,+ "generation_count": int(row[1] or 0),+ "cost_usd": float(row[2] or 0.0),+ "avg_input_tokens": float(row[3] or 0.0),+ }+ for row in (result.results or [])+ ]+ return _truncate(rows, limit)+++def _fetch_by_model(+ team: Team,+ email: str,+ from_dt: datetime.datetime,+ to_dt: datetime.datetime,+ product: str | None,+ limit: int,+) -> dict[str, Any]:+ query = parse_select(+ """+ SELECT+ properties.$ai_model AS model,+ count() AS generation_count,+ round(sum(toFloat(properties.$ai_total_cost_usd)), 6) AS cost_usd,+ sum(toFloat(properties.$ai_input_tokens)) AS input_tokens,+ sum(toFloat(properties.$ai_output_tokens)) AS output_tokens+ FROM posthog.ai_events+ WHERE {event_in}+ AND {product_filter}+ AND {email_filter}+ AND {timestamp_filter}+ GROUP BY model+ ORDER BY cost_usd DESC+ LIMIT {limit}+ """+ )+ result = execute_with_ai_events_fallback(+ query=query,+ placeholders={+ "event_in": _event_in(["$ai_generation", "$ai_embedding"]),+ "product_filter": _product_filter(product),+ "email_filter": _email_filter(email),+ "timestamp_filter": _timestamp_filter(from_dt, to_dt),+ "limit": ast.Constant(value=limit + 1),+ },+ team=team,+ query_type="PersonalSpendByModel",+ )+ rows = [+ {+ "model": row[0] if row[0] is not None else None,+ "generation_count": int(row[1] or 0),+ "cost_usd": float(row[2] or 0.0),+ "input_tokens": int(row[3] or 0),+ "output_tokens": int(row[4] or 0),+ }+ for row in (result.results or [])+ ]+ return _truncate(rows, limit)+++def _fetch_top_traces(+ team: Team,+ email: str,+ from_dt: datetime.datetime,+ to_dt: datetime.datetime,+ product: str | None,+ limit: int,+) -> dict[str, Any]:+ query = parse_select(+ """+ SELECT+ properties.$ai_trace_id AS trace_id,+ count() AS generation_count,+ round(sum(toFloat(properties.$ai_total_cost_usd)), 6) AS cost_usd,+ min(timestamp) AS started_at+ FROM posthog.ai_events+ WHERE equals(event, '$ai_generation')+ AND {product_filter}+ AND {email_filter}+ AND {timestamp_filter}+ GROUP BY trace_id+ ORDER BY cost_usd DESC+ LIMIT {limit}+ """+ )+ result = execute_with_ai_events_fallback(+ query=query,+ placeholders={+ "product_filter": _product_filter(product),+ "email_filter": _email_filter(email),+ "timestamp_filter": _timestamp_filter(from_dt, to_dt),+ "limit": ast.Constant(value=limit + 1),+ },+ team=team,+ query_type="PersonalSpendTopTraces",+ )+ rows = [+ {+ "trace_id": row[0] if row[0] is not None else None,+ "generation_count": int(row[1] or 0),+ "cost_usd": float(row[2] or 0.0),+ "started_at": row[3],+ }+ for row in (result.results or [])+ ]+ return _truncate(rows, limit)+++class PersonalSpendViewSet(viewsets.ViewSet):+ """+ Returns the requesting user's personal LLM spend analysis across PostHog products.++ Queries are run server-side against PostHog's internal analytics team+ (settings.LLM_ANALYTICS_INTERNAL_TEAM_ID) and are strictly scoped to the+ authenticated user's email (read off the events row via person-on-events) —+ callers cannot pivot to other users' data. Authorization model is "any+ authenticated PostHog user may read their own spend"; the `llm_analytics:read`+ scope on the MCP tool is decorative since no project-level scope check+ applies. Routes through `execute_with_ai_events_fallback` so reads hit the+ dedicated `ai_events` table when enabled, with the shared `events` table as+ a fallback. Optionally filter tool / model / trace breakdowns to a single+ `ai_product` via the `product` query param; `by_product` always returns+ the full cross-product breakdown. The endpoint is only registered on US+ Cloud + dev/test envs; hobby / self-hosted deploys never see this URL;+ EU deploys receive a 302 to the US URL.+ """++ permission_classes = [permissions.IsAuthenticated]++ def get_throttles(self):+ return [+ PersonalSpendBurstThrottle(),+ PersonalSpendSustainedThrottle(),+ PersonalSpendDailyThrottle(),+ ]++ @extend_schema(+ parameters=[_SpendQueryParamsSerializer],+ responses={+ 200: PersonalSpendAnalysisResponseSerializer,+ 400: _ErrorResponseSerializer,+ 401: _ErrorResponseSerializer,+ 403: _ErrorResponseSerializer,+ 404: _ErrorResponseSerializer,+ 429: _ErrorResponseSerializer,+ },+ description=(+ "Return a structured personal LLM spend analysis for the requesting user. Pass "+ "`date_from` / `date_to` (absolute like `2026-04-23` or relative like `-7d`) to bound "+ "the window — defaults to the last 30 days, max 90 days. Pass `product=<ai_product>` "+ "to scope the tool / model / trace breakdowns to a single product (e.g. `posthog_code`); "+ "omit it for an aggregate view. `by_product` is always returned for cross-product "+ "visibility. Use `refresh=true` to bypass the 5-minute response cache."+ ),+ tags=["LLM Analytics"],+ )+ def list(self, request: Request) -> Response:+ user = cast(User, request.user)+ email = user.email+ if not email:+ raise exceptions.PermissionDenied("User has no email on record; cannot scope spend analysis.")++ params = _SpendQueryParamsSerializer(data=request.query_params)+ params.is_valid(raise_exception=True)+ date_from = params.validated_data["date_from"]+ date_to = params.validated_data["date_to"]+ product = params.validated_data["product"]+ limit = params.validated_data["limit"]+ refresh = params.validated_data["refresh"]++ from_dt, to_dt = _resolve_window(date_from, date_to)++ cache_key = _cache_key(email, date_from, date_to, product, limit)++ if not refresh:+ cached = cache.get(cache_key)+ if cached is not None:+ return Response(cached, status=status.HTTP_200_OK)++ team_id = _internal_team_id()+ try:+ team = Team.objects.get(pk=team_id)+ except Team.DoesNotExist:+ logger.exception("personal_spend.team_missing", team_id=team_id)+ raise exceptions.NotFound("Internal analytics team is not provisioned on this deployment.")++ summary = _fetch_summary(team, email, from_dt, to_dt, product)+ by_tool = _fetch_by_tool(team, email, from_dt, to_dt, product, limit)+ scoped = summary["scoped_cost_usd"] or 0.0+ # `cost_usd` in by_tool can exceed scoped_cost_usd because multi-tool generations+ # contribute to every tool. `share_of_scoped` is independent per row, so agents can+ # present headline percentages directly without reconciling sums.+ for row in by_tool["items"]:+ row["share_of_scoped"] = (row["cost_usd"] / scoped) if scoped > 0 else 0.0++ payload = {+ "summary": summary,+ "by_product": _fetch_by_product(team, email, from_dt, to_dt, limit),+ "by_tool": by_tool,+ "by_model": _fetch_by_model(team, email, from_dt, to_dt, product, limit),+ "top_traces": _fetch_top_traces(team, email, from_dt, to_dt, product, limit),+ }++ response_data = PersonalSpendAnalysisResponseSerializer(payload).data+ cache.set(cache_key, response_data, timeout=CACHE_TIMEOUT_SECONDS)+ return Response(response_data, status=status.HTTP_200_OK)+++_EU_REDIRECT_TARGET = "https://us.posthog.com/api/llm_analytics/@me/spend/"+_EU_REDIRECT_FORWARDED_PARAMS = frozenset({"date_from", "date_to", "product", "limit", "refresh"})+++def personal_spend_eu_redirect(request: HttpRequest) -> HttpResponseRedirect:+ """Redirect EU callers to the US-hosted endpoint where the data actually lives.++ EU PostHog Cloud forwards its product LLM telemetry to PostHog Cloud US, so the+ spend analysis only runs there. Returning a 302 makes the new home discoverable+ instead of serving a silent 404. Callers still need a US-valid auth token.++ The target host is hardcoded — only an allowlist of known params is forwarded+ (re-encoded via `urlencode`) so a malicious caller cannot smuggle extra path or+ fragment characters into the redirect target.+ """+ safe_params = {k: v for k, v in request.GET.items() if k in _EU_REDIRECT_FORWARDED_PARAMS}+ target = _EU_REDIRECT_TARGET+ if safe_params:+ target = f"{target}?{urlencode(safe_params)}"+ return HttpResponseRedirect(target)diff --git a/products/llm_analytics/backend/api/test/__snapshots__/test_personal_spend.ambr b/products/llm_analytics/backend/api/test/__snapshots__/test_personal_spend.ambrnew file mode 100644index 000000000000..bc1cdb18c520--- /dev/null+++ b/products/llm_analytics/backend/api/test/__snapshots__/test_personal_spend.ambr@@ -0,0 +1,199 @@+# serializer version: 1+# name: TestPersonalSpendQueries.test_empty_result_when_no_events+ '''+ /* user_id:0 request:_snapshot_@me_spend_ */+ SELECT countIf(1) AS scoped_event_count,+ round(sumIf(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_total_cost_usd'), ''), 'null'), '^"|"$', ''), 'Float64'), 1), 6) AS scoped_cost_usd,+ count() AS event_count,+ round(sum(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_total_cost_usd'), ''), 'null'), '^"|"$', ''), 'Float64')), 6) AS total_cost_usd+ FROM events+ LEFT OUTER JOIN+ (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id,+ person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 99999)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)+ LEFT JOIN+ (SELECT person.id AS id,+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'email'), ''), 'null'), '^"|"$', '') AS properties___email+ FROM person+ WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),+ (SELECT person.id AS id, max(person.version) AS version+ FROM person+ WHERE equals(person.team_id, 99999)+ GROUP BY person.id+ HAVING and(ifNull(equals(argMax(person.is_deleted, person.version), 0), 0), ifNull(less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))), 0))))) SETTINGS optimize_aggregation_in_order=1) AS events__person ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), events__person.id)+ WHERE and(equals(events.team_id, 99999), in(events.event, tuple('$ai_generation', '$ai_embedding')), ifNull(equals(events__person.properties___email, '[email protected]'), 0), and(greaterOrEquals(events.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), less(events.timestamp, toDateTime64('today', 6, 'UTC'))))+ LIMIT 100 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---+# name: TestPersonalSpendQueries.test_empty_result_when_no_events.1+ '''+ /* user_id:0 request:_snapshot_@me_spend_ */+ SELECT nullIf(arrayJoin(splitByChar(',', coalesce(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_tools_called'), ''), 'null'), '^"|"$', ''), ''))), '') AS tool,+ count() AS generation_count,+ round(sum(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_total_cost_usd'), ''), 'null'), '^"|"$', ''), 'Float64')), 6) AS cost_usd,+ round(avg(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_input_tokens'), ''), 'null'), '^"|"$', ''), 'Float64')), 0) AS avg_input_tokens+ FROM events+ LEFT OUTER JOIN+ (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id,+ person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 99999)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)+ LEFT JOIN+ (SELECT person.id AS id,+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'email'), ''), 'null'), '^"|"$', '') AS properties___email+ FROM person+ WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),+ (SELECT person.id AS id, max(person.version) AS version+ FROM person+ WHERE equals(person.team_id, 99999)+ GROUP BY person.id+ HAVING and(ifNull(equals(argMax(person.is_deleted, person.version), 0), 0), ifNull(less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))), 0))))) SETTINGS optimize_aggregation_in_order=1) AS events__person ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), events__person.id)+ WHERE and(equals(events.team_id, 99999), equals(events.event, '$ai_generation'), ifNull(equals(events__person.properties___email, '[email protected]'), 0), and(greaterOrEquals(events.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), less(events.timestamp, toDateTime64('today', 6, 'UTC'))))+ GROUP BY tool+ ORDER BY cost_usd DESC+ LIMIT 51 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---+# name: TestPersonalSpendQueries.test_empty_result_when_no_events.2+ '''+ /* user_id:0 request:_snapshot_@me_spend_ */+ SELECT replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'ai_product'), ''), 'null'), '^"|"$', '') AS product,+ count() AS event_count,+ round(sum(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_total_cost_usd'), ''), 'null'), '^"|"$', ''), 'Float64')), 6) AS cost_usd+ FROM events+ LEFT OUTER JOIN+ (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id,+ person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 99999)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)+ LEFT JOIN+ (SELECT person.id AS id,+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'email'), ''), 'null'), '^"|"$', '') AS properties___email+ FROM person+ WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),+ (SELECT person.id AS id, max(person.version) AS version+ FROM person+ WHERE equals(person.team_id, 99999)+ GROUP BY person.id+ HAVING and(ifNull(equals(argMax(person.is_deleted, person.version), 0), 0), ifNull(less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))), 0))))) SETTINGS optimize_aggregation_in_order=1) AS events__person ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), events__person.id)+ WHERE and(equals(events.team_id, 99999), in(events.event, tuple('$ai_generation', '$ai_embedding')), ifNull(equals(events__person.properties___email, '[email protected]'), 0), and(greaterOrEquals(events.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), less(events.timestamp, toDateTime64('today', 6, 'UTC'))))+ GROUP BY product+ ORDER BY cost_usd DESC+ LIMIT 51 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---+# name: TestPersonalSpendQueries.test_empty_result_when_no_events.3+ '''+ /* user_id:0 request:_snapshot_@me_spend_ */+ SELECT replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_model'), ''), 'null'), '^"|"$', '') AS model,+ count() AS generation_count,+ round(sum(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_total_cost_usd'), ''), 'null'), '^"|"$', ''), 'Float64')), 6) AS cost_usd,+ sum(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_input_tokens'), ''), 'null'), '^"|"$', ''), 'Float64')) AS input_tokens,+ sum(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_output_tokens'), ''), 'null'), '^"|"$', ''), 'Float64')) AS output_tokens+ FROM events+ LEFT OUTER JOIN+ (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id,+ person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 99999)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)+ LEFT JOIN+ (SELECT person.id AS id,+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'email'), ''), 'null'), '^"|"$', '') AS properties___email+ FROM person+ WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),+ (SELECT person.id AS id, max(person.version) AS version+ FROM person+ WHERE equals(person.team_id, 99999)+ GROUP BY person.id+ HAVING and(ifNull(equals(argMax(person.is_deleted, person.version), 0), 0), ifNull(less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))), 0))))) SETTINGS optimize_aggregation_in_order=1) AS events__person ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), events__person.id)+ WHERE and(equals(events.team_id, 99999), in(events.event, tuple('$ai_generation', '$ai_embedding')), ifNull(equals(events__person.properties___email, '[email protected]'), 0), and(greaterOrEquals(events.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), less(events.timestamp, toDateTime64('today', 6, 'UTC'))))+ GROUP BY replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_model'), ''), 'null'), '^"|"$', '')+ ORDER BY cost_usd DESC+ LIMIT 51 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---+# name: TestPersonalSpendQueries.test_empty_result_when_no_events.4+ '''+ /* user_id:0 request:_snapshot_@me_spend_ */+ SELECT replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_trace_id'), ''), 'null'), '^"|"$', '') AS trace_id,+ count() AS generation_count,+ round(sum(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_total_cost_usd'), ''), 'null'), '^"|"$', ''), 'Float64')), 6) AS cost_usd,+ min(toTimeZone(events.timestamp, 'UTC')) AS started_at+ FROM events+ LEFT OUTER JOIN+ (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id,+ person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 99999)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)+ LEFT JOIN+ (SELECT person.id AS id,+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'email'), ''), 'null'), '^"|"$', '') AS properties___email+ FROM person+ WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),+ (SELECT person.id AS id, max(person.version) AS version+ FROM person+ WHERE equals(person.team_id, 99999)+ GROUP BY person.id+ HAVING and(ifNull(equals(argMax(person.is_deleted, person.version), 0), 0), ifNull(less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))), 0))))) SETTINGS optimize_aggregation_in_order=1) AS events__person ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), events__person.id)+ WHERE and(equals(events.team_id, 99999), equals(events.event, '$ai_generation'), ifNull(equals(events__person.properties___email, '[email protected]'), 0), and(greaterOrEquals(events.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), less(events.timestamp, toDateTime64('today', 6, 'UTC'))))+ GROUP BY replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_trace_id'), ''), 'null'), '^"|"$', '')+ ORDER BY cost_usd DESC+ LIMIT 51 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---diff --git a/products/llm_analytics/backend/api/test/__snapshots__/test_posthog_code_spend.ambr b/products/llm_analytics/backend/api/test/__snapshots__/test_posthog_code_spend.ambrnew file mode 100644index 000000000000..b1663eb4d605--- /dev/null+++ b/products/llm_analytics/backend/api/test/__snapshots__/test_posthog_code_spend.ambr@@ -0,0 +1,199 @@+# serializer version: 1+# name: TestPostHogCodeSpendQueries.test_empty_result_when_no_events+ '''+ /* user_id:0 request:_snapshot_ */+ SELECT countIf(ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'ai_product'), ''), 'null'), '^"|"$', ''), 'posthog_code'), 0)) AS posthog_code_event_count,+ round(sumIf(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_total_cost_usd'), ''), 'null'), '^"|"$', ''), 'Float64'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'ai_product'), ''), 'null'), '^"|"$', ''), 'posthog_code'), 0)), 6) AS posthog_code_cost_usd,+ count() AS event_count,+ round(sum(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_total_cost_usd'), ''), 'null'), '^"|"$', ''), 'Float64')), 6) AS total_cost_usd+ FROM events+ LEFT OUTER JOIN+ (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id,+ person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 99999)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)+ LEFT JOIN+ (SELECT person.id AS id,+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'email'), ''), 'null'), '^"|"$', '') AS properties___email+ FROM person+ WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),+ (SELECT person.id AS id, max(person.version) AS version+ FROM person+ WHERE equals(person.team_id, 99999)+ GROUP BY person.id+ HAVING and(ifNull(equals(argMax(person.is_deleted, person.version), 0), 0), ifNull(less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))), 0))))) SETTINGS optimize_aggregation_in_order=1) AS events__person ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), events__person.id)+ WHERE and(equals(events.team_id, 99999), in(events.event, tuple('$ai_generation', '$ai_embedding')), ifNull(equals(events__person.properties___email, '[email protected]'), 0), greaterOrEquals(events.timestamp, minus(now64(6, 'UTC'), toIntervalDay(30))))+ LIMIT 100 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---+# name: TestPostHogCodeSpendQueries.test_empty_result_when_no_events.1+ '''+ /* user_id:0 request:_snapshot_ */+ SELECT replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'ai_product'), ''), 'null'), '^"|"$', '') AS product,+ count() AS event_count,+ round(sum(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_total_cost_usd'), ''), 'null'), '^"|"$', ''), 'Float64')), 6) AS cost_usd+ FROM events+ LEFT OUTER JOIN+ (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id,+ person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 99999)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)+ LEFT JOIN+ (SELECT person.id AS id,+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'email'), ''), 'null'), '^"|"$', '') AS properties___email+ FROM person+ WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),+ (SELECT person.id AS id, max(person.version) AS version+ FROM person+ WHERE equals(person.team_id, 99999)+ GROUP BY person.id+ HAVING and(ifNull(equals(argMax(person.is_deleted, person.version), 0), 0), ifNull(less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))), 0))))) SETTINGS optimize_aggregation_in_order=1) AS events__person ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), events__person.id)+ WHERE and(equals(events.team_id, 99999), in(events.event, tuple('$ai_generation', '$ai_embedding')), ifNull(equals(events__person.properties___email, '[email protected]'), 0), greaterOrEquals(events.timestamp, minus(now64(6, 'UTC'), toIntervalDay(30))))+ GROUP BY product+ ORDER BY cost_usd DESC+ LIMIT 10 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---+# name: TestPostHogCodeSpendQueries.test_empty_result_when_no_events.2+ '''+ /* user_id:0 request:_snapshot_ */+ SELECT replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_tools_called'), ''), 'null'), '^"|"$', '') AS tool,+ count() AS generation_count,+ round(sum(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_total_cost_usd'), ''), 'null'), '^"|"$', ''), 'Float64')), 6) AS cost_usd,+ round(avg(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_input_tokens'), ''), 'null'), '^"|"$', ''), 'Float64')), 0) AS avg_input_tokens+ FROM events+ LEFT OUTER JOIN+ (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id,+ person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 99999)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)+ LEFT JOIN+ (SELECT person.id AS id,+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'email'), ''), 'null'), '^"|"$', '') AS properties___email+ FROM person+ WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),+ (SELECT person.id AS id, max(person.version) AS version+ FROM person+ WHERE equals(person.team_id, 99999)+ GROUP BY person.id+ HAVING and(ifNull(equals(argMax(person.is_deleted, person.version), 0), 0), ifNull(less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))), 0))))) SETTINGS optimize_aggregation_in_order=1) AS events__person ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), events__person.id)+ WHERE and(equals(events.team_id, 99999), equals(events.event, '$ai_generation'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'ai_product'), ''), 'null'), '^"|"$', ''), 'posthog_code'), 0), ifNull(equals(events__person.properties___email, '[email protected]'), 0), greaterOrEquals(events.timestamp, minus(now64(6, 'UTC'), toIntervalDay(30))))+ GROUP BY tool+ ORDER BY cost_usd DESC+ LIMIT 20 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---+# name: TestPostHogCodeSpendQueries.test_empty_result_when_no_events.3+ '''+ /* user_id:0 request:_snapshot_ */+ SELECT replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_model'), ''), 'null'), '^"|"$', '') AS model,+ count() AS generation_count,+ round(sum(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_total_cost_usd'), ''), 'null'), '^"|"$', ''), 'Float64')), 6) AS cost_usd,+ sum(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_input_tokens'), ''), 'null'), '^"|"$', ''), 'Float64')) AS input_tokens,+ sum(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_output_tokens'), ''), 'null'), '^"|"$', ''), 'Float64')) AS output_tokens+ FROM events+ LEFT OUTER JOIN+ (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id,+ person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 99999)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)+ LEFT JOIN+ (SELECT person.id AS id,+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'email'), ''), 'null'), '^"|"$', '') AS properties___email+ FROM person+ WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),+ (SELECT person.id AS id, max(person.version) AS version+ FROM person+ WHERE equals(person.team_id, 99999)+ GROUP BY person.id+ HAVING and(ifNull(equals(argMax(person.is_deleted, person.version), 0), 0), ifNull(less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))), 0))))) SETTINGS optimize_aggregation_in_order=1) AS events__person ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), events__person.id)+ WHERE and(equals(events.team_id, 99999), in(events.event, tuple('$ai_generation', '$ai_embedding')), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'ai_product'), ''), 'null'), '^"|"$', ''), 'posthog_code'), 0), ifNull(equals(events__person.properties___email, '[email protected]'), 0), greaterOrEquals(events.timestamp, minus(now64(6, 'UTC'), toIntervalDay(30))))+ GROUP BY model+ ORDER BY cost_usd DESC+ LIMIT 10 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---+# name: TestPostHogCodeSpendQueries.test_empty_result_when_no_events.4+ '''+ /* user_id:0 request:_snapshot_ */+ SELECT replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_trace_id'), ''), 'null'), '^"|"$', '') AS trace_id,+ count() AS generation_count,+ round(sum(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$ai_total_cost_usd'), ''), 'null'), '^"|"$', ''), 'Float64')), 6) AS cost_usd,+ min(toTimeZone(events.timestamp, 'UTC')) AS started_at+ FROM events+ LEFT OUTER JOIN+ (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id,+ person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 99999)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)+ LEFT JOIN+ (SELECT person.id AS id,+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'email'), ''), 'null'), '^"|"$', '') AS properties___email+ FROM person+ WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),+ (SELECT person.id AS id, max(person.version) AS version+ FROM person+ WHERE equals(person.team_id, 99999)+ GROUP BY person.id+ HAVING and(ifNull(equals(argMax(person.is_deleted, person.version), 0), 0), ifNull(less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))), 0))))) SETTINGS optimize_aggregation_in_order=1) AS events__person ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), events__person.id)+ WHERE and(equals(events.team_id, 99999), equals(events.event, '$ai_generation'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'ai_product'), ''), 'null'), '^"|"$', ''), 'posthog_code'), 0), ifNull(equals(events__person.properties___email, '[email protected]'), 0), greaterOrEquals(events.timestamp, minus(now64(6, 'UTC'), toIntervalDay(30))))+ GROUP BY trace_id+ ORDER BY cost_usd DESC+ LIMIT 10 SETTINGS readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=0,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---diff --git a/products/llm_analytics/backend/api/test/test_personal_spend.py b/products/llm_analytics/backend/api/test/test_personal_spend.pynew file mode 100644index 000000000000..dd17dfe93e6f--- /dev/null+++ b/products/llm_analytics/backend/api/test/test_personal_spend.py@@ -0,0 +1,373 @@+"""Tests for the personal LLM spend analysis API endpoint."""++from __future__ import annotations++from posthog.test.base import (+ APIBaseTest,+ ClickhouseTestMixin,+ _create_event,+ _create_person,+ flush_persons_and_events,+ snapshot_clickhouse_queries,+)+from unittest.mock import patch++from django.test import override_settings++from parameterized import parameterized+from rest_framework import status++ENDPOINT = "/api/llm_analytics/@me/spend/"+++def _by_product(rows: list[dict], product: str | None) -> dict | None:+ return next((r for r in rows if r["product"] == product), None)+++class TestPersonalSpendEuRedirect(APIBaseTest):+ """Pure unit test of the EU redirect view — does not depend on URL conf for EU."""++ def test_eu_redirect_view_preserves_query_string(self) -> None:+ from django.test import RequestFactory++ from products.llm_analytics.backend.api.personal_spend import personal_spend_eu_redirect++ factory = RequestFactory()+ request = factory.get("/api/llm_analytics/@me/spend/", data={"date_from": "-7d", "product": "posthog_code"})+ response = personal_spend_eu_redirect(request)++ assert response.status_code == status.HTTP_302_FOUND+ assert response["Location"].startswith("https://us.posthog.com/api/llm_analytics/@me/spend/")+ assert "date_from=-7d" in response["Location"]+ assert "product=posthog_code" in response["Location"]++ def test_eu_redirect_view_strips_unknown_params(self) -> None:+ from django.test import RequestFactory++ from products.llm_analytics.backend.api.personal_spend import personal_spend_eu_redirect++ factory = RequestFactory()+ request = factory.get(+ "/api/llm_analytics/@me/spend/",+ data={"date_from": "-7d", "evil": "https://attacker.example/", "fragment": "#"},+ )+ response = personal_spend_eu_redirect(request)++ assert response.status_code == status.HTTP_302_FOUND+ # Target host stays hardcoded.+ assert response["Location"].startswith("https://us.posthog.com/")+ # Allowed param preserved.+ assert "date_from=-7d" in response["Location"]+ # Unknown params dropped (allowlist enforced).+ assert "evil" not in response["Location"]+ assert "fragment" not in response["Location"]+ assert "attacker.example" not in response["Location"]+++class TestPersonalSpendAuth(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ self._team_id_override = override_settings(LLM_ANALYTICS_INTERNAL_TEAM_ID=self.team.id)+ self._team_id_override.enable()+ self.addCleanup(self._team_id_override.disable)++ def test_unauthenticated_caller_rejected(self) -> None:+ self.client.logout()+ response = self.client.get(ENDPOINT)+ assert response.status_code == status.HTTP_401_UNAUTHORIZED++ def test_authenticated_caller_without_email_rejected(self) -> None:+ self.user.email = ""+ self.user.save()+ response = self.client.get(ENDPOINT)+ assert response.status_code == status.HTTP_403_FORBIDDEN+++class TestPersonalSpendValidation(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ self._team_id_override = override_settings(LLM_ANALYTICS_INTERNAL_TEAM_ID=self.team.id)+ self._team_id_override.enable()+ self.addCleanup(self._team_id_override.disable)++ @parameterized.expand(+ [+ ("nonsense", "wibble", status.HTTP_400_BAD_REQUEST),+ ("over_max_window", "-365d", status.HTTP_400_BAD_REQUEST),+ ("valid_relative_short", "-1d", status.HTTP_200_OK),+ ("valid_relative_default", "-30d", status.HTTP_200_OK),+ ("valid_relative_max", "-90d", status.HTTP_200_OK),+ ]+ )+ def test_date_from_param_validation(self, _label: str, date_from: str, expected: int) -> None:+ response = self.client.get(f"{ENDPOINT}?date_from={date_from}")+ assert response.status_code == expected++ def test_date_params_optional_default_to_last_30_days(self) -> None:+ response = self.client.get(ENDPOINT)+ assert response.status_code == status.HTTP_200_OK+ summary = response.json()["summary"]+ assert summary["product"] is None+ # date_from / date_to are returned as ISO strings.+ assert summary["date_from"] is not None+ assert summary["date_to"] is not None++ def test_date_to_before_date_from_rejected(self) -> None:+ response = self.client.get(f"{ENDPOINT}?date_from=-7d&date_to=-30d")+ assert response.status_code == status.HTTP_400_BAD_REQUEST++ def test_product_too_long_rejected(self) -> None:+ response = self.client.get(f"{ENDPOINT}?product={'x' * 100}")+ assert response.status_code == status.HTTP_400_BAD_REQUEST++ @parameterized.expand(+ [+ ("zero", "0", status.HTTP_400_BAD_REQUEST),+ ("negative", "-1", status.HTTP_400_BAD_REQUEST),+ ("over_max", "1000", status.HTTP_400_BAD_REQUEST),+ ("valid_min", "1", status.HTTP_200_OK),+ ("valid_default", "50", status.HTTP_200_OK),+ ("valid_max", "200", status.HTTP_200_OK),+ ]+ )+ def test_limit_param_validation(self, _label: str, limit: str, expected: int) -> None:+ response = self.client.get(f"{ENDPOINT}?limit={limit}")+ assert response.status_code == expected+++class TestPersonalSpendQueries(ClickhouseTestMixin, APIBaseTest):+ """End-to-end tests against ClickHouse with real $ai_generation events."""++ def setUp(self) -> None:+ super().setUp()+ self._team_id_override = override_settings(LLM_ANALYTICS_INTERNAL_TEAM_ID=self.team.id)+ self._team_id_override.enable()+ self.addCleanup(self._team_id_override.disable)++ _create_person(+ distinct_ids=[self.user.distinct_id or self.user.email],+ team=self.team,+ properties={"email": self.user.email},+ )+ flush_persons_and_events()++ def _create_generation(+ self,+ *,+ ai_product: str = "posthog_code",+ model: str = "claude-opus-4-7",+ tool: str | None = "Bash",+ trace_id: str = "trace-1",+ cost: float = 1.5,+ input_tokens: int = 100000,+ output_tokens: int = 500,+ event_name: str = "$ai_generation",+ ) -> None:+ props: dict = {+ "$ai_total_cost_usd": cost,+ "$ai_input_tokens": input_tokens,+ "$ai_output_tokens": output_tokens,+ "$ai_model": model,+ "$ai_trace_id": trace_id,+ "ai_product": ai_product,+ }+ if tool is not None:+ props["$ai_tools_called"] = tool+ _create_event(+ event=event_name,+ team=self.team,+ distinct_id=self.user.distinct_id or self.user.email,+ properties=props,+ )++ @snapshot_clickhouse_queries+ def test_empty_result_when_no_events(self) -> None:+ response = self.client.get(ENDPOINT)+ assert response.status_code == status.HTTP_200_OK+ body = response.json()+ assert body["summary"]["total_cost_usd"] == 0+ assert body["summary"]["event_count"] == 0+ assert body["summary"]["scoped_cost_usd"] == 0+ assert body["summary"]["scoped_event_count"] == 0+ assert body["by_product"] == {"items": [], "truncated": False}+ assert body["by_tool"] == {"items": [], "truncated": False}+ assert body["by_model"] == {"items": [], "truncated": False}+ assert body["top_traces"] == {"items": [], "truncated": False}++ def test_unfiltered_summary_aggregates_across_products(self) -> None:+ self._create_generation(ai_product="posthog_code", cost=2.0)+ self._create_generation(ai_product="background_agents", cost=1.0)+ self._create_generation(ai_product="posthog_code", cost=0.5, event_name="$ai_embedding")+ flush_persons_and_events()++ response = self.client.get(ENDPOINT)+ body = response.json()+ summary = body["summary"]+ assert summary["product"] is None+ assert summary["event_count"] == 3+ assert summary["total_cost_usd"] == 3.5+ # Without a product filter, scoped totals match the cross-product totals.+ assert summary["scoped_event_count"] == 3+ assert summary["scoped_cost_usd"] == 3.5+ # by_product carries each slice for the caller to pick out.+ code_row = _by_product(body["by_product"]["items"], "posthog_code")+ assert code_row is not None+ assert code_row["cost_usd"] == 2.5+ assert body["by_product"]["truncated"] is False++ def test_product_filter_scopes_summary_and_breakdowns(self) -> None:+ self._create_generation(ai_product="posthog_code", tool="Bash", cost=2.0)+ self._create_generation(ai_product="background_agents", tool="Bash", cost=10.0)+ flush_persons_and_events()++ response = self.client.get(f"{ENDPOINT}?product=posthog_code")+ body = response.json()++ # Summary still reports cross-product totals; scoped_* is filtered.+ assert body["summary"]["product"] == "posthog_code"+ assert body["summary"]["total_cost_usd"] == 12.0+ assert body["summary"]["scoped_cost_usd"] == 2.0++ # by_tool is scoped to the filter — only the posthog_code Bash row.+ tool_rows = body["by_tool"]["items"]+ assert len(tool_rows) == 1+ assert tool_rows[0]["cost_usd"] == 2.0+ assert tool_rows[0]["share_of_scoped"] == 1.0++ # by_product is always cross-product, regardless of the filter.+ assert {r["product"] for r in body["by_product"]["items"]} == {"posthog_code", "background_agents"}++ def test_by_tool_includes_null_tool_rows(self) -> None:+ self._create_generation(tool="Bash", cost=2.0)+ self._create_generation(tool=None, cost=0.5)+ flush_persons_and_events()++ response = self.client.get(f"{ENDPOINT}?product=posthog_code")+ tools = {r["tool"] for r in response.json()["by_tool"]["items"]}+ assert tools == {"Bash", None}++ def test_by_tool_splits_comma_separated_tools(self) -> None:+ # One generation that calls Bash and Read should contribute to both rows.+ self._create_generation(tool="Bash,Read", cost=2.0, trace_id="multi")+ # One single-tool generation that also touches Bash, plus a single-tool Read.+ self._create_generation(tool="Bash", cost=1.0, trace_id="bash-only")+ self._create_generation(tool="Read", cost=0.5, trace_id="read-only")+ flush_persons_and_events()++ response = self.client.get(f"{ENDPOINT}?product=posthog_code")+ rows = {r["tool"]: r for r in response.json()["by_tool"]["items"]}+ assert set(rows) == {"Bash", "Read"}+ # Bash row picks up both the Bash-only generation and the Bash,Read generation.+ assert rows["Bash"]["generation_count"] == 2+ assert rows["Bash"]["cost_usd"] == 3.0+ # Read row picks up both the Read-only generation and the Bash,Read generation.+ assert rows["Read"]["generation_count"] == 2+ assert rows["Read"]["cost_usd"] == 2.5+ # Scoped total stays $3.50 — the multi-tool generation is only counted once there.+ assert response.json()["summary"]["scoped_cost_usd"] == 3.5++ def test_top_traces_ordered_by_cost(self) -> None:+ self._create_generation(trace_id="cheap", cost=0.5)+ self._create_generation(trace_id="expensive", cost=5.0)+ self._create_generation(trace_id="expensive", cost=3.0)+ flush_persons_and_events()++ response = self.client.get(ENDPOINT)+ traces = response.json()["top_traces"]["items"]+ assert traces[0]["trace_id"] == "expensive"+ assert traces[0]["cost_usd"] == 8.0+ assert traces[0]["generation_count"] == 2+ assert traces[1]["trace_id"] == "cheap"++ def test_other_users_spend_is_not_visible(self) -> None:+ other_email = "[email protected]"+ _create_person(distinct_ids=["other-distinct"], team=self.team, properties={"email": other_email})+ _create_event(+ event="$ai_generation",+ team=self.team,+ distinct_id="other-distinct",+ properties={+ "$ai_total_cost_usd": 999.99,+ "ai_product": "posthog_code",+ "$ai_model": "claude-opus-4-7",+ "$ai_tools_called": "Bash",+ "$ai_trace_id": "their-trace",+ },+ )+ self._create_generation(cost=1.0)+ flush_persons_and_events()++ response = self.client.get(ENDPOINT)+ assert response.json()["summary"]["total_cost_usd"] == 1.0++ def test_date_window_passes_through_to_query_layer(self) -> None:+ with patch("products.llm_analytics.backend.api.personal_spend.execute_with_ai_events_fallback") as mock_exec:+ mock_exec.return_value.results = []+ response = self.client.get(f"{ENDPOINT}?date_from=-7d")++ assert response.status_code == status.HTTP_200_OK+ # All 5 fetchers should run once.+ assert mock_exec.call_count == 5++ def test_second_call_serves_from_cache(self) -> None:+ with patch("products.llm_analytics.backend.api.personal_spend.execute_with_ai_events_fallback") as mock_exec:+ mock_exec.return_value.results = []+ self.client.get(ENDPOINT)+ first = mock_exec.call_count+ self.client.get(ENDPOINT)+ assert mock_exec.call_count == first++ def test_refresh_bypasses_cache(self) -> None:+ with patch("products.llm_analytics.backend.api.personal_spend.execute_with_ai_events_fallback") as mock_exec:+ mock_exec.return_value.results = []+ self.client.get(ENDPOINT)+ first = mock_exec.call_count+ self.client.get(f"{ENDPOINT}?refresh=true")+ assert mock_exec.call_count == first * 2++ def test_cache_key_includes_date_from(self) -> None:+ with patch("products.llm_analytics.backend.api.personal_spend.execute_with_ai_events_fallback") as mock_exec:+ mock_exec.return_value.results = []+ self.client.get(f"{ENDPOINT}?date_from=-7d")+ first = mock_exec.call_count+ self.client.get(f"{ENDPOINT}?date_from=-30d")+ assert mock_exec.call_count == first * 2++ def test_cache_key_includes_product(self) -> None:+ with patch("products.llm_analytics.backend.api.personal_spend.execute_with_ai_events_fallback") as mock_exec:+ mock_exec.return_value.results = []+ self.client.get(ENDPOINT)+ first = mock_exec.call_count+ self.client.get(f"{ENDPOINT}?product=posthog_code")+ assert mock_exec.call_count == first * 2++ def test_cache_key_includes_limit(self) -> None:+ with patch("products.llm_analytics.backend.api.personal_spend.execute_with_ai_events_fallback") as mock_exec:+ mock_exec.return_value.results = []+ self.client.get(f"{ENDPOINT}?limit=10")+ first = mock_exec.call_count+ self.client.get(f"{ENDPOINT}?limit=50")+ assert mock_exec.call_count == first * 2++ def test_by_product_truncated_when_more_than_limit_products(self) -> None:+ # Three products, ask for limit=2 → top 2 returned, truncated=True.+ self._create_generation(ai_product="a", cost=3.0)+ self._create_generation(ai_product="b", cost=2.0)+ self._create_generation(ai_product="c", cost=1.0)+ flush_persons_and_events()++ response = self.client.get(f"{ENDPOINT}?limit=2")+ by_product = response.json()["by_product"]+ assert len(by_product["items"]) == 2+ assert by_product["truncated"] is True++ def test_by_tool_share_of_scoped(self) -> None:+ self._create_generation(tool="Bash", cost=2.0)+ self._create_generation(tool="Read", cost=2.0)+ flush_persons_and_events()++ response = self.client.get(f"{ENDPOINT}?product=posthog_code")+ rows = {r["tool"]: r for r in response.json()["by_tool"]["items"]}+ # Each tool drove half of the scoped spend.+ assert rows["Bash"]["share_of_scoped"] == 0.5+ assert rows["Read"]["share_of_scoped"] == 0.5