Skip to content

: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.

fix(llma): sentiment preflight 500s on non-UTC team timezone (#58387)

Andrew Maguire6cd27c0fbd4d
diff --git a/products/llm_analytics/backend/api/sentiment.py b/products/llm_analytics/backend/api/sentiment.py
index a308deaf8005..37753738ea9b 100644
--- a/products/llm_analytics/backend/api/sentiment.py
+++ b/products/llm_analytics/backend/api/sentiment.py
@@ -120,20 +120,27 @@ class SentimentBatchResponseSerializer(serializers.Serializer):
# 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.
+#
+# The `max(timestamp)` / `min(timestamp)` aggregates intentionally use distinct
+# aliases (`ts_max` / `ts_min`) rather than reusing `timestamp` / `created_at`.
+# `replace_filters` injects a timestamp range as `toTimeZone(timestamp, '<tz>') > ...`
+# for teams whose timezone is non-UTC, and HogQL would bind that inner `timestamp`
+# to a same-named SELECT alias, producing `max(toTimeZone(timestamp, ...))` inside
+# WHERE — an illegal aggregate in WHERE that surfaces as a 500 to the Sentiment tab.
_SENTIMENT_GENERATIONS_PREFLIGHT_SQL = f"""
SELECT
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
+ max(timestamp) as ts_max,
+ min(timestamp) as ts_min
FROM events
WHERE event = '$ai_generation'
AND length(coalesce(properties.$ai_trace_id, '')) > 0
AND {{filters}}
GROUP BY trace_id
-ORDER BY timestamp DESC, trace_id DESC
+ORDER BY ts_max DESC, trace_id DESC
LIMIT {GENERATIONS_QUERY_LIMIT}
"""
@@ -150,7 +157,7 @@ WHERE event = '$ai_generation'
GROUP BY trace_id
"""
-_PreflightRow = namedtuple("_PreflightRow", ["uuid", "trace_id", "model", "distinct_id", "timestamp", "created_at"])
+_PreflightRow = namedtuple("_PreflightRow", ["uuid", "trace_id", "model", "distinct_id", "ts_max", "ts_min"])
class SentimentGenerationsRequestSerializer(serializers.Serializer):
@@ -359,8 +366,8 @@ class LLMAnalyticsSentimentViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewS
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)
+ ts_start = min(row.ts_min for row in preflight_rows)
+ ts_end = max(row.ts_max for row in preflight_rows)
heavy_query = parse_select(_SENTIMENT_GENERATIONS_HEAVY_SQL)
try:
@@ -388,6 +395,11 @@ class LLMAnalyticsSentimentViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewS
)
ai_input_by_trace = {str(trace_id): ai_input for trace_id, ai_input in (heavy_result.results or [])}
+ # Positional response shape (unchanged, frontend depends on it): row[0..6] =
+ # [uuid, trace_id, ai_input, model, distinct_id, ts_max, ts_min]. The internal
+ # `ts_max` / `ts_min` aliases (see `_SENTIMENT_GENERATIONS_PREFLIGHT_SQL`) are
+ # the same values the frontend consumes as `timestamp` and `createdAt` at
+ # `llmAnalyticsSentimentLogic.ts::fetchGenerations`.
results = [
[
row.uuid,
@@ -395,8 +407,8 @@ class LLMAnalyticsSentimentViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewS
ai_input_by_trace.get(str(row.trace_id)),
row.model,
row.distinct_id,
- row.timestamp,
- row.created_at,
+ row.ts_max,
+ row.ts_min,
]
for row in preflight_rows
]
diff --git a/products/llm_analytics/backend/api/test/test_sentiment_generations.py b/products/llm_analytics/backend/api/test/test_sentiment_generations.py
index 5fb00c6aaf82..405be979917b 100644
--- a/products/llm_analytics/backend/api/test/test_sentiment_generations.py
+++ b/products/llm_analytics/backend/api/test/test_sentiment_generations.py
@@ -1,7 +1,7 @@
from datetime import UTC, datetime
from typing import Any, cast
-from posthog.test.base import APIBaseTest
+from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person
from unittest.mock import MagicMock, patch
from parameterized import parameterized
@@ -202,3 +202,86 @@ class TestSentimentGenerationsEndpoint(APIBaseTest):
assert len(body["results"]) == 2
assert body["results"][0][2] == '[{"role":"user","content":"hi"}]'
assert body["results"][1][2] is None
+
+
+class TestSentimentGenerationsRealClickhouse(ClickhouseTestMixin, APIBaseTest):
+ """Regression coverage that exercises the real `replace_filters` + ClickHouse
+ pipeline for the Sentiments-tab preflight, not the mocked path.
+
+ Previously the preflight aliased `max(timestamp) AS timestamp`, which shadowed
+ the `timestamp` column. `replace_filters` injects `toTimeZone(timestamp, '<tz>')`
+ comparisons for any team whose `timezone` is not UTC, and HogQL bound that
+ inner `timestamp` to the aggregate alias — surfacing as an "illegal aggregate
+ in WHERE" 500 from ClickHouse. The frontend swallowed the 500 into an empty
+ `results` array, rendering the "No generations with user input found" copy on
+ the Sentiments tab even when valid `$ai_generation` events existed for the
+ team. The mocked tests above never tripped this because they short-circuit
+ `execute_hogql_query`.
+ """
+
+ URL: str = ""
+
+ def setUp(self) -> None:
+ super().setUp()
+ self.URL = f"/api/environments/{self.team.id}/llm_analytics/sentiment/generations/"
+ # Reproduce the customer config that triggered the bug — any non-UTC tz
+ # is sufficient; `replace_filters` only wraps `timestamp` in `toTimeZone`
+ # when the team timezone differs from UTC.
+ self.team.timezone = "US/Eastern"
+ self.team.save()
+
+ @parameterized.expand(
+ [
+ ("no_events", False),
+ ("with_event", True),
+ ]
+ )
+ @patch("products.llm_analytics.backend.api.sentiment.execute_with_ai_events_fallback")
+ def test_preflight_against_real_clickhouse_for_non_utc_team(
+ self,
+ _name: str,
+ seed_event: bool,
+ mock_heavy: MagicMock,
+ ) -> None:
+ """Without the alias-shadow fix, the preflight 500s here regardless of data
+ — the regression is in the SQL/`replace_filters` interaction, not in row
+ retrieval. The `with_event` case additionally confirms end-to-end shape on
+ a non-UTC team so a future refactor of the preflight can't silently drop
+ rows for the affected timezone class."""
+ if seed_event:
+ _create_person(team_id=self.team.pk, distinct_ids=["person-1"])
+ _create_event(
+ event="$ai_generation",
+ team=self.team,
+ distinct_id="person-1",
+ properties={
+ "$ai_trace_id": "trace-non-utc-1",
+ "$ai_model": "gpt-4",
+ "$ai_input": [{"role": "user", "content": "hi"}],
+ },
+ )
+ mock_heavy.return_value = MagicMock(
+ results=[("trace-non-utc-1", '[{"role":"user","content":"hi"}]')],
+ )
+ else:
+ mock_heavy.return_value = MagicMock(results=[])
+
+ response = self.client.post(
+ self.URL,
+ {"filters": {"dateRange": {"date_from": "-1d", "date_to": None}}},
+ content_type="application/json",
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ body = response.json()
+ if seed_event:
+ assert len(body["results"]) == 1
+ # Response tuple positions: [uuid, trace_id, ai_input, model, distinct_id, ts_max, ts_min]
+ assert body["results"][0][1] == "trace-non-utc-1"
+ assert body["results"][0][3] == "gpt-4"
+ assert body["results"][0][4] == "person-1"
+ else:
+ assert body == {"results": []}
+ # Heavy query is skipped when preflight is empty — confirms the preflight
+ # ran to completion (rather than crashing) and returned no rows.
+ assert mock_heavy.call_count == 0