: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): add explicit LIMIT to sentiment heavy SQL to stop row truncation (#59130)
Andrew Maguired073aeefc4c5
diff --git a/products/llm_analytics/backend/api/sentiment.py b/products/llm_analytics/backend/api/sentiment.pyindex 37753738ea9b..417754845760 100644--- a/products/llm_analytics/backend/api/sentiment.py+++ b/products/llm_analytics/backend/api/sentiment.py@@ -144,17 +144,24 @@ ORDER BY ts_max DESC, trace_id DESCLIMIT {GENERATIONS_QUERY_LIMIT}"""-_SENTIMENT_GENERATIONS_HEAVY_SQL = """+# The explicit `LIMIT` matches the preflight's `GENERATIONS_QUERY_LIMIT` —+# without it, `execute_hogql_query` (via `LimitContext.QUERY`) injects its+# default of 100 rows, silently truncating the heavy `GROUP BY trace_id`+# to the first 100 trace_ids whenever the preflight returns more. That+# manifests in the UI as blank sentiment cards for the truncated half,+# even though the underlying input is present in ClickHouse.+_SENTIMENT_GENERATIONS_HEAVY_SQL = f"""SELECTtrace_id,argMax(input, timestamp) as ai_inputFROM posthog.ai_events AS ai_eventsWHERE event = '$ai_generation'- AND trace_id IN {trace_ids}- AND uuid IN {uuids}- AND timestamp >= {ts_start}- AND timestamp <= {ts_end}+ AND trace_id IN {{trace_ids}}+ AND uuid IN {{uuids}}+ AND timestamp >= {{ts_start}}+ AND timestamp <= {{ts_end}}GROUP BY trace_id+LIMIT {GENERATIONS_QUERY_LIMIT}"""_PreflightRow = namedtuple("_PreflightRow", ["uuid", "trace_id", "model", "distinct_id", "ts_max", "ts_min"])@@ -370,15 +377,16 @@ class LLMAnalyticsSentimentViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSts_end = max(row.ts_max for row in preflight_rows)heavy_query = parse_select(_SENTIMENT_GENERATIONS_HEAVY_SQL)+ heavy_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),+ }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),- },+ placeholders=heavy_placeholders,team=self.team,query_type="LLMSentimentGenerations",limit_context=LimitContext.QUERY,diff --git a/products/llm_analytics/backend/api/test/test_sentiment_generations.py b/products/llm_analytics/backend/api/test/test_sentiment_generations.pyindex 405be979917b..10ad1ff85ba6 100644--- a/products/llm_analytics/backend/api/test/test_sentiment_generations.py+++ b/products/llm_analytics/backend/api/test/test_sentiment_generations.py@@ -183,6 +183,36 @@ class TestSentimentGenerationsEndpoint(APIBaseTest):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)+ # The heavy SQL must carry an explicit `LIMIT` matching the preflight's+ # `GENERATIONS_QUERY_LIMIT`. Without it, `execute_hogql_query` (via+ # `LimitContext.QUERY`) injects a default of 100 rows and the `GROUP BY+ # trace_id` is silently truncated when the preflight returns more, so+ # the truncated half renders as blank cards on the Sentiment tab.+ @patch("products.llm_analytics.backend.api.sentiment.execute_with_ai_events_fallback")+ @patch("products.llm_analytics.backend.api.sentiment.execute_hogql_query")+ def test_heavy_query_has_explicit_limit(self, mock_preflight: MagicMock, mock_heavy: MagicMock) -> None:+ from posthog.hogql import ast as hogql_ast++ from products.llm_analytics.backend.api.sentiment import GENERATIONS_QUERY_LIMIT++ mock_preflight.return_value = self._make_response([self._preflight_row()])+ 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++ heavy_query = mock_heavy.call_args.kwargs["query"]+ heavy_select = cast(hogql_ast.SelectQuery, heavy_query)+ assert heavy_select.limit is not None, "heavy query must have an explicit LIMIT"+ assert isinstance(heavy_select.limit, hogql_ast.Constant)+ assert heavy_select.limit.value == GENERATIONS_QUERY_LIMIT++ # When the heavy table returns fewer rows than the preflight (e.g. a+ # trace had no input column, or partial ai_events coverage in some+ # future state), the un-matched traces fall back to null ai_input and+ # the response still includes them positionally. This keeps the+ # frontend dedup grouping (and the per-card "View trace" links)+ # working for the remaining rows.@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(