: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): sentiment generations timeout (#57781)
Carlos Marchalb66967c577a7
diff --git a/products/llm_analytics/backend/api/sentiment.py b/products/llm_analytics/backend/api/sentiment.pyindex 992cc0122882..a308deaf8005 100644--- a/products/llm_analytics/backend/api/sentiment.py+++ b/products/llm_analytics/backend/api/sentiment.py@@ -7,6 +7,7 @@ and returns the result synchronously (blocks until Temporal completes).import timeimport uuidimport asyncio+from collections import namedtuplefrom datetime import timedeltafrom django.conf import settings@@ -24,9 +25,11 @@ from temporalio.common import RetryPolicy, WorkflowIDReusePolicyfrom posthog.schema import HogQLFilters+from posthog.hogql import astfrom posthog.hogql.constants import LimitContextfrom posthog.hogql.filters import replace_filtersfrom posthog.hogql.parser import parse_select+from posthog.hogql.query import execute_hogql_queryfrom posthog.api.monitoring import monitorfrom posthog.api.routing import TeamAndOrgViewSetMixin@@ -113,38 +116,42 @@ class SentimentBatchResponseSerializer(serializers.Serializer):results = serializers.DictField(child=SentimentResultSerializer())-# SQL template for the sentiment-tab generations list. Reads heavy `input` from-# `posthog.ai_events`; the resolver re-runs against `events.properties.$ai_input`-# on the events fallback path. Both branches honour the team's-# `ai-events-table-rollout` flag and emit `ai_query_source` tags for dashboards.-_SENTIMENT_GENERATIONS_SQL = f"""+# Preflight runs against `events` (not `posthog.ai_events`): the events sort+# key starts `(team_id, toDate(timestamp), event)` so date filtering prunes+# granules cheaply, while ai_events is `(team_id, trace_id, timestamp)` —+# unusable for date pruning until trace_id is bounded.+_SENTIMENT_GENERATIONS_PREFLIGHT_SQL = f"""SELECT- argMax(uuid, ts) as uuid,- trace_id,- argMax(ai_input, ts) as ai_input,- argMax(model, ts) as model,- argMax(did, ts) as distinct_id,- max(ts) as timestamp,- min(ts) as created_at-FROM (- SELECT- uuid,- trace_id,- input as ai_input,- model,- distinct_id as did,- timestamp as ts- FROM posthog.ai_events AS ai_events- WHERE event = '$ai_generation'- AND length(coalesce(input, '')) > 0- AND length(coalesce(trace_id, '')) > 0- AND {{filters}}-)+ argMax(uuid, timestamp) as uuid,+ properties.$ai_trace_id as trace_id,+ argMax(properties.$ai_model, timestamp) as model,+ argMax(distinct_id, timestamp) as distinct_id,+ max(timestamp) as timestamp,+ min(timestamp) as created_at+FROM events+WHERE event = '$ai_generation'+ AND length(coalesce(properties.$ai_trace_id, '')) > 0+ AND {{filters}}GROUP BY trace_idORDER BY timestamp DESC, trace_id DESCLIMIT {GENERATIONS_QUERY_LIMIT}"""+_SENTIMENT_GENERATIONS_HEAVY_SQL = """+SELECT+ trace_id,+ argMax(input, timestamp) as ai_input+FROM posthog.ai_events AS ai_events+WHERE event = '$ai_generation'+ AND trace_id IN {trace_ids}+ AND uuid IN {uuids}+ AND timestamp >= {ts_start}+ AND timestamp <= {ts_end}+GROUP BY trace_id+"""++_PreflightRow = namedtuple("_PreflightRow", ["uuid", "trace_id", "model", "distinct_id", "timestamp", "created_at"])+class SentimentGenerationsRequestSerializer(serializers.Serializer):"""Filter shape mirrors the previous frontend `api.query({filters: ...})` payload.@@ -305,14 +312,6 @@ class LLMAnalyticsSentimentViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewS@llma_track_latency("llma_sentiment_generations")@monitor(feature=None, endpoint="llma_sentiment_generations", method="POST")def generations(self, request: Request, **kwargs) -> Response:- """Fetch the recent $ai_generation events for the sentiment tab.-- Backed by `_SENTIMENT_GENERATIONS_SQL` reading `posthog.ai_events` through- `execute_with_ai_events_fallback`, so heavy `input` values survive the- post-cutover strip on `events.properties.$ai_input`. Frontend callers- pass the same `HogQLFilters` payload they previously passed to- `api.query({kind: HogQLQuery, filters: ...})`.- """serializer = SentimentGenerationsRequestSerializer(data=request.data)if not serializer.is_valid():return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)@@ -332,18 +331,48 @@ class LLMAnalyticsSentimentViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewS# the full exception representation (CodeQL flagged it as info exposure).return Response({"filters": e.errors()}, status=status.HTTP_400_BAD_REQUEST)- query = parse_select(_SENTIMENT_GENERATIONS_SQL)- # Apply dateRange / properties / filterTestAccounts via the standard- # `{filters}` placeholder substitution (same machinery the frontend- # HogQL path used pre-migration).- query_with_filters = replace_filters(query, filters, self.team)+ preflight_query = replace_filters(parse_select(_SENTIMENT_GENERATIONS_PREFLIGHT_SQL), filters, self.team)with tags_context(product=Product.LLM_ANALYTICS, feature=Feature.QUERY, team_id=self.team_id):try:- result = execute_with_ai_events_fallback(- query=query_with_filters,+ preflight_result = execute_hogql_query(+ query=preflight_query,placeholders={},team=self.team,+ query_type="LLMSentimentGenerationsTraceIdResolve",+ limit_context=LimitContext.QUERY,+ )+ except Exception as e:+ logger.exception(+ "Failed to resolve sentiment generations trace_ids",+ team_id=self.team_id,+ error=str(e),+ )+ return Response(+ {"error": "Failed to fetch sentiment generations"},+ status=status.HTTP_500_INTERNAL_SERVER_ERROR,+ )++ preflight_rows = [_PreflightRow(*row) for row in (preflight_result.results or [])]+ if not preflight_rows:+ return Response({"results": []}, status=status.HTTP_200_OK)++ trace_ids = [str(row.trace_id) for row in preflight_rows]+ uuids = [str(row.uuid) for row in preflight_rows]+ ts_start = min(row.created_at for row in preflight_rows)+ ts_end = max(row.timestamp for row in preflight_rows)++ heavy_query = parse_select(_SENTIMENT_GENERATIONS_HEAVY_SQL)+ try:+ heavy_result = execute_with_ai_events_fallback(+ query=heavy_query,+ placeholders={+ "trace_ids": ast.Tuple(exprs=[ast.Constant(value=tid) for tid in trace_ids]),+ "uuids": ast.Tuple(exprs=[ast.Constant(value=u) for u in uuids]),+ "ts_start": ast.Constant(value=ts_start),+ "ts_end": ast.Constant(value=ts_end),+ },+ team=self.team,query_type="LLMSentimentGenerations",limit_context=LimitContext.QUERY,)@@ -358,4 +387,17 @@ class LLMAnalyticsSentimentViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSstatus=status.HTTP_500_INTERNAL_SERVER_ERROR,)- return Response({"results": result.results or []}, status=status.HTTP_200_OK)+ ai_input_by_trace = {str(trace_id): ai_input for trace_id, ai_input in (heavy_result.results or [])}+ results = [+ [+ row.uuid,+ row.trace_id,+ ai_input_by_trace.get(str(row.trace_id)),+ row.model,+ row.distinct_id,+ row.timestamp,+ row.created_at,+ ]+ for row in preflight_rows+ ]+ return Response({"results": results}, status=status.HTTP_200_OK)diff --git a/products/llm_analytics/backend/api/test/test_sentiment_generations.py b/products/llm_analytics/backend/api/test/test_sentiment_generations.pyindex c84af63958ed..5fb00c6aaf82 100644--- a/products/llm_analytics/backend/api/test/test_sentiment_generations.py+++ b/products/llm_analytics/backend/api/test/test_sentiment_generations.py@@ -1,27 +1,10 @@-"""Tests for `LLMAnalyticsSentimentViewSet.generations` — the-`sentiment_generations.sql`-equivalent backend endpoint.--The view's responsibility is narrow: parse + validate the filter payload, route-the SQL through `execute_with_ai_events_fallback` so the rollout flag /-events fallback / `ai_query_source` tagging are honored, and return the result-rows tuple-shape unchanged. Tests cover:-- - success on the dedicated path with populated rows- - success on the events fallback when ai_events is empty (post-strip is the- motivating case — the resolver re-runs against `events` automatically)- - kill-switch off (skips ai_events, queries events directly)- - empty filters (omitted dateRange / properties / filterTestAccounts)- - resolver receives the correct query body + tags--The resolver itself is covered by `test_ai_table_resolver.py`; here we mock-it and verify the call shape, then probe the failure paths.-"""--from typing import cast+from datetime import UTC, datetime+from typing import Any, castfrom posthog.test.base import APIBaseTestfrom unittest.mock import MagicMock, patch+from parameterized import parameterizedfrom rest_framework import status@@ -32,29 +15,38 @@ class TestSentimentGenerationsEndpoint(APIBaseTest):super().setUp()self.URL = f"/api/environments/{self.team.id}/llm_analytics/sentiment/generations/"- def _resolver_path(self) -> str:- return "products.llm_analytics.backend.api.sentiment.execute_with_ai_events_fallback"-- def _make_resolver_response(self, rows: list[list]) -> MagicMock:+ def _make_response(self, rows: list[list[Any]]) -> MagicMock:response = MagicMock()response.results = rowsreturn response+ def _preflight_row(+ self,+ uuid: str = "uuid-1",+ trace_id: str = "trace-1",+ model: str = "gpt-4",+ distinct_id: str = "person-1",+ ts_max: Any = "2026-04-27T07:00:00+00:00",+ ts_min: Any = "2026-04-27T06:50:00+00:00",+ ) -> list[Any]:+ return [uuid, trace_id, model, distinct_id, ts_max, ts_min]+@patch("products.llm_analytics.backend.api.sentiment.execute_with_ai_events_fallback")- def test_returns_rows_in_tuple_order(self, mock_resolver: MagicMock) -> None:- # Tuple order: [uuid, trace_id, ai_input, model, distinct_id, timestamp, created_at]- rows = [+ @patch("products.llm_analytics.backend.api.sentiment.execute_hogql_query")+ def test_returns_rows_in_tuple_order(self, mock_preflight: MagicMock, mock_heavy: MagicMock) -> None:+ mock_preflight.return_value = self._make_response([- "uuid-1",- "trace-1",- '[{"role":"user","content":"hi"}]',- "gpt-4",- "person-1",- "2026-04-27T07:00:00+00:00",- "2026-04-27T06:50:00+00:00",- ],- ]- mock_resolver.return_value = self._make_resolver_response(rows)+ self._preflight_row(+ uuid="uuid-1",+ trace_id="trace-1",+ model="gpt-4",+ distinct_id="person-1",+ ts_max="2026-04-27T07:00:00+00:00",+ ts_min="2026-04-27T06:50:00+00:00",+ ),+ ]+ )+ mock_heavy.return_value = self._make_response([["trace-1", '[{"role":"user","content":"hi"}]']])response = self.client.post(self.URL,@@ -64,64 +56,149 @@ class TestSentimentGenerationsEndpoint(APIBaseTest):assert response.status_code == status.HTTP_200_OKbody = response.json()- assert body == {"results": rows}- # Resolver received an LLMSentimentGenerations query_type for tagging dashboards.- assert mock_resolver.call_args.kwargs["query_type"] == "LLMSentimentGenerations"+ assert body == {+ "results": [+ [+ "uuid-1",+ "trace-1",+ '[{"role":"user","content":"hi"}]',+ "gpt-4",+ "person-1",+ "2026-04-27T07:00:00+00:00",+ "2026-04-27T06:50:00+00:00",+ ]+ ]+ }+ assert mock_preflight.call_args.kwargs["query_type"] == "LLMSentimentGenerationsTraceIdResolve"+ assert mock_heavy.call_args.kwargs["query_type"] == "LLMSentimentGenerations"@patch("products.llm_analytics.backend.api.sentiment.execute_with_ai_events_fallback")- def test_empty_filters_payload_is_accepted(self, mock_resolver: MagicMock) -> None:- # Tab loads with no filters set; backend should not reject this.- mock_resolver.return_value = self._make_resolver_response([])-- response = self.client.post(self.URL, {}, content_type="application/json")- assert response.status_code == status.HTTP_200_OK- assert response.json() == {"results": []}-- @patch("products.llm_analytics.backend.api.sentiment.execute_with_ai_events_fallback")- def test_invalid_filters_returns_400(self, mock_resolver: MagicMock) -> None:- # `filterTestAccounts` is meant to be a bool; a non-bool should fail- # `HogQLFilters` validation and surface as a 400 (not 500).+ @patch("products.llm_analytics.backend.api.sentiment.execute_hogql_query")+ def test_invalid_filters_returns_400(self, mock_preflight: MagicMock, mock_heavy: MagicMock) -> None:response = self.client.post(self.URL,{"filters": {"filterTestAccounts": "this should be a bool"}},content_type="application/json",)assert response.status_code == status.HTTP_400_BAD_REQUEST- assert mock_resolver.call_count == 0+ assert mock_preflight.call_count == 0+ assert mock_heavy.call_count == 0+ @parameterized.expand(+ [+ ("missing_filters_key", {}),+ ("empty_filters_dict", {"filters": {}}),+ ]+ )@patch("products.llm_analytics.backend.api.sentiment.execute_with_ai_events_fallback")- def test_resolver_failure_returns_500(self, mock_resolver: MagicMock) -> None:- mock_resolver.side_effect = RuntimeError("clickhouse boom")+ @patch("products.llm_analytics.backend.api.sentiment.execute_hogql_query")+ def test_empty_preflight_skips_heavy_query(+ self,+ _name: str,+ payload: dict[str, Any],+ mock_preflight: MagicMock,+ mock_heavy: MagicMock,+ ) -> None:+ mock_preflight.return_value = self._make_response([])++ response = self.client.post(self.URL, payload, content_type="application/json")+ assert response.status_code == status.HTTP_200_OK+ assert response.json() == {"results": []}+ assert mock_heavy.call_count == 0- response = self.client.post(- self.URL,- {"filters": {}},- content_type="application/json",- )+ @parameterized.expand(+ [+ ("preflight", "preflight"),+ ("heavy", "heavy"),+ ]+ )+ @patch("products.llm_analytics.backend.api.sentiment.execute_with_ai_events_fallback")+ @patch("products.llm_analytics.backend.api.sentiment.execute_hogql_query")+ def test_clickhouse_failure_returns_500(+ self,+ _name: str,+ failing_stage: str,+ mock_preflight: MagicMock,+ mock_heavy: MagicMock,+ ) -> None:+ if failing_stage == "preflight":+ mock_preflight.side_effect = RuntimeError("clickhouse boom")+ else:+ mock_preflight.return_value = self._make_response([self._preflight_row()])+ mock_heavy.side_effect = RuntimeError("clickhouse boom")++ response = self.client.post(self.URL, {"filters": {}}, content_type="application/json")assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR+ if failing_stage == "preflight":+ assert mock_heavy.call_count == 0@patch("products.llm_analytics.backend.api.sentiment.execute_with_ai_events_fallback")- def test_query_targets_ai_events_with_heavy_input_column(self, mock_resolver: MagicMock) -> None:- """The migrated SQL must reach the resolver with the heavy `input`- column referenced via the dedicated `ai_events` table — not as- `properties.$ai_input`. That's the whole point of the migration; if- someone reverts the SQL, this test catches it."""+ @patch("products.llm_analytics.backend.api.sentiment.execute_hogql_query")+ def test_preflight_targets_events_and_heavy_targets_ai_events(+ self, mock_preflight: MagicMock, mock_heavy: MagicMock+ ) -> None:from posthog.hogql import ast- mock_resolver.return_value = self._make_resolver_response([])+ mock_preflight.return_value = self._make_response(+ [+ self._preflight_row(+ uuid="uuid-1",+ trace_id="trace-1",+ ts_max=datetime(2026, 4, 27, 7, 0, tzinfo=UTC),+ ts_min=datetime(2026, 4, 27, 6, 50, tzinfo=UTC),+ ),+ self._preflight_row(+ uuid="uuid-2",+ trace_id="trace-2",+ ts_max=datetime(2026, 4, 27, 6, 30, tzinfo=UTC),+ ts_min=datetime(2026, 4, 27, 6, 0, tzinfo=UTC),+ ),+ ]+ )+ mock_heavy.return_value = self._make_response(+ [+ ["trace-1", '[{"role":"user","content":"hi"}]'],+ ["trace-2", '[{"role":"user","content":"hello"}]'],+ ]+ )response = self.client.post(self.URL, {"filters": {}}, content_type="application/json")assert response.status_code == status.HTTP_200_OK- query_arg = mock_resolver.call_args.kwargs["query"]- # SelectQuery → outer query reads `argMax(ai_input, ts)` over a subquery- # whose FROM is `posthog.ai_events`.- # Easier to verify by walking down to the FROM clause.- select = cast(ast.SelectQuery, query_arg)- # Outer: argMax(ai_input, ts) … FROM (subquery)- # Subquery's FROM is what we care about.- inner = select.select_from.table # type: ignore[union-attr]- if isinstance(inner, ast.SelectQuery):- from_chain = inner.select_from.table.chain # type: ignore[union-attr]- # nosemgrep: hogql-no-string-table-chain- assert from_chain == ["posthog", "ai_events"], f"expected FROM posthog.ai_events, got {from_chain}"+ preflight_query = mock_preflight.call_args.kwargs["query"]+ preflight_select = cast(ast.SelectQuery, preflight_query)+ # nosemgrep: hogql-no-string-table-chain+ assert preflight_select.select_from.table.chain == ["events"] # type: ignore[union-attr]++ heavy_query = mock_heavy.call_args.kwargs["query"]+ heavy_select = cast(ast.SelectQuery, heavy_query)+ # nosemgrep: hogql-no-string-table-chain+ assert heavy_select.select_from.table.chain == ["posthog", "ai_events"] # type: ignore[union-attr]++ heavy_placeholders = mock_heavy.call_args.kwargs["placeholders"]+ trace_id_values = [c.value for c in heavy_placeholders["trace_ids"].exprs]+ uuid_values = [c.value for c in heavy_placeholders["uuids"].exprs]+ assert trace_id_values == ["trace-1", "trace-2"]+ assert uuid_values == ["uuid-1", "uuid-2"]+ assert heavy_placeholders["ts_start"].value == datetime(2026, 4, 27, 6, 0, tzinfo=UTC)+ assert heavy_placeholders["ts_end"].value == datetime(2026, 4, 27, 7, 0, tzinfo=UTC)++ @patch("products.llm_analytics.backend.api.sentiment.execute_with_ai_events_fallback")+ @patch("products.llm_analytics.backend.api.sentiment.execute_hogql_query")+ def test_traces_without_heavy_match_get_null_ai_input(+ self, mock_preflight: MagicMock, mock_heavy: MagicMock+ ) -> None:+ mock_preflight.return_value = self._make_response(+ [+ self._preflight_row(uuid="uuid-1", trace_id="trace-1"),+ self._preflight_row(uuid="uuid-2", trace_id="trace-2"),+ ]+ )+ mock_heavy.return_value = self._make_response([["trace-1", '[{"role":"user","content":"hi"}]']])++ response = self.client.post(self.URL, {"filters": {}}, content_type="application/json")+ assert response.status_code == status.HTTP_200_OK+ body = response.json()+ assert len(body["results"]) == 2+ assert body["results"][0][2] == '[{"role":"user","content":"hi"}]'+ assert body["results"][1][2] is Nonediff --git a/products/llm_analytics/frontend/generated/api.ts b/products/llm_analytics/frontend/generated/api.tsindex 7e6d38bed0e5..f33981096354 100644--- a/products/llm_analytics/frontend/generated/api.ts+++ b/products/llm_analytics/frontend/generated/api.ts@@ -1263,15 +1263,6 @@ export const llmAnalyticsSentimentCreate = async (})}-/**- * Fetch the recent $ai_generation events for the sentiment tab.--Backed by `_SENTIMENT_GENERATIONS_SQL` reading `posthog.ai_events` through-`execute_with_ai_events_fallback`, so heavy `input` values survive the-post-cutover strip on `events.properties.$ai_input`. Frontend callers-pass the same `HogQLFilters` payload they previously passed to-`api.query({kind: HogQLQuery, filters: ...})`.- */export const getLlmAnalyticsSentimentGenerationsCreateUrl = (projectId: string) => {return `/api/environments/${projectId}/llm_analytics/sentiment/generations/`}diff --git a/products/llm_analytics/frontend/generated/api.zod.ts b/products/llm_analytics/frontend/generated/api.zod.tsindex 762a98dcad5a..23541a85b81d 100644--- a/products/llm_analytics/frontend/generated/api.zod.ts+++ b/products/llm_analytics/frontend/generated/api.zod.ts@@ -1105,15 +1105,6 @@ export const LlmAnalyticsSentimentCreateBody = /* @__PURE__ */ zod.object({date_to: zod.string().nullish().describe('End of date range for the lookup. Defaults to now.'),})-/**- * Fetch the recent $ai_generation events for the sentiment tab.--Backed by `_SENTIMENT_GENERATIONS_SQL` reading `posthog.ai_events` through-`execute_with_ai_events_fallback`, so heavy `input` values survive the-post-cutover strip on `events.properties.$ai_input`. Frontend callers-pass the same `HogQLFilters` payload they previously passed to-`api.query({kind: HogQLQuery, filters: ...})`.- */export const LlmAnalyticsSentimentGenerationsCreateBody = /* @__PURE__ */ zod.object({filters: zod.unknown().optional(),