:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(llma): deprecate top_traces, always return empty (#59796)
Paul D'Ambra4534def31bac
diff --git a/products/llm_analytics/backend/api/personal_spend.py b/products/llm_analytics/backend/api/personal_spend.pyindex 53e5c5f637e4..91eb130a4499 100644--- a/products/llm_analytics/backend/api/personal_spend.py+++ b/products/llm_analytics/backend/api/personal_spend.py@@ -282,7 +282,12 @@ class PersonalSpendAnalysisResponseSerializer(serializers.Serializer):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."+ help_text=(+ "Deprecated — always returns `{items: [], truncated: false}`. Trace IDs are opaque strings "+ "that aren't actionable in the UI. Kept in the response shape so existing consumers don't "+ "crash; remove your rendering of this field and we'll drop it from the response entirely "+ "in a follow-up."+ ))@@ -524,54 +529,6 @@ def _fetch_by_model(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 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_hogql_query(- 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.@@ -690,7 +647,10 @@ class PersonalSpendViewSet(viewsets.ViewSet):"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),+ # Deprecated — trace IDs are opaque and unactionable in the UI. Returned empty so+ # existing consumers don't crash while they remove the rendering. Drop the field+ # entirely once no consumer reads it.+ "top_traces": {"items": [], "truncated": False},}response_data = PersonalSpendAnalysisResponseSerializer(payload).datadiff --git a/products/llm_analytics/backend/api/test/__snapshots__/test_personal_spend.ambr b/products/llm_analytics/backend/api/test/__snapshots__/test_personal_spend.ambrindex c1962a1090ff..4a4b0640938b 100644--- a/products/llm_analytics/backend/api/test/__snapshots__/test_personal_spend.ambr+++ b/products/llm_analytics/backend/api/test/__snapshots__/test_personal_spend.ambr@@ -157,43 +157,3 @@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 trace_id- 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/test_personal_spend.py b/products/llm_analytics/backend/api/test/test_personal_spend.pyindex d27577b3c925..e2f8fd2f2657 100644--- a/products/llm_analytics/backend/api/test/test_personal_spend.py+++ b/products/llm_analytics/backend/api/test/test_personal_spend.py@@ -275,18 +275,16 @@ class TestPersonalSpendQueries(ClickhouseTestMixin, APIBaseTest):# 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:+ def test_top_traces_always_empty(self) -> None:+ # `top_traces` is deprecated — kept in the response shape so existing consumers don't+ # crash, but always returns empty. Trace IDs are opaque strings that aren't actionable+ # in the UI.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"+ assert response.json()["top_traces"] == {"items": [], "truncated": False}def test_other_users_spend_is_not_visible(self) -> None:other_email = "[email protected]"@@ -315,8 +313,9 @@ class TestPersonalSpendQueries(ClickhouseTestMixin, APIBaseTest):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+ # 4 fetchers run once (summary, by_product, by_tool, by_model). top_traces is+ # deprecated and returned empty without a query.+ assert mock_exec.call_count == 4def test_second_call_serves_from_cache(self) -> None:with patch("products.llm_analytics.backend.api.personal_spend.execute_hogql_query") as mock_exec:diff --git a/products/llm_analytics/frontend/generated/api.schemas.ts b/products/llm_analytics/frontend/generated/api.schemas.tsindex deb12732cdb3..b3a768f7359d 100644--- a/products/llm_analytics/frontend/generated/api.schemas.ts+++ b/products/llm_analytics/frontend/generated/api.schemas.ts@@ -2363,7 +2363,7 @@ export interface PersonalSpendAnalysisResponseApi {by_tool: _ToolBreakdownApi/** Spend grouped by `$ai_model`. Scoped to `product` when set. */by_model: _ModelBreakdownApi- /** Most expensive trace IDs (sessions) in the window. Scoped to `product` when set. */+ /** Deprecated — always returns `{items: [], truncated: false}`. Trace IDs are opaque strings that aren't actionable in the UI. Kept in the response shape so existing consumers don't crash; remove your rendering of this field and we'll drop it from the response entirely in a follow-up. */top_traces: _TopTracesApi}diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex f60b617008ca..f71e6f74f712 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -31849,7 +31849,7 @@ export namespace Schemas {by_tool: _ToolBreakdown;/** Spend grouped by `$ai_model`. Scoped to `product` when set. */by_model: _ModelBreakdown;- /** Most expensive trace IDs (sessions) in the window. Scoped to `product` when set. */+ /** Deprecated — always returns `{items: [], truncated: false}`. Trace IDs are opaque strings that aren't actionable in the UI. Kept in the response shape so existing consumers don't crash; remove your rendering of this field and we'll drop it from the response entirely in a follow-up. */top_traces: _TopTraces;}