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.

feat(llma): ai events strip fixes (#56763)

Carlos Marchal9f20d2a0ab7e
diff --git a/frontend/bin/generate-openapi-types.mjs b/frontend/bin/generate-openapi-types.mjs
index 2db8a3e02869..9f25a273df18 100755
--- a/frontend/bin/generate-openapi-types.mjs
+++ b/frontend/bin/generate-openapi-types.mjs
@@ -194,6 +194,7 @@ function buildGroupedSchemasByOutput(schema, mappings) {
const grouped = new Map()
const httpMethods = new Set(['get', 'put', 'post', 'delete', 'options', 'head', 'patch', 'trace'])
const allSchemas = schema.components?.schemas ?? {}
+ const allParameters = schema.components?.parameters ?? {}
const skippedTags = new Map()
let skippedNoTags = 0
let routedByTag = 0
@@ -307,6 +308,19 @@ function buildGroupedSchemasByOutput(schema, mappings) {
// Build final schemas with only referenced components
for (const [outputDir, entry] of grouped.entries()) {
+ const filteredParameters = {}
+ for (const ref of entry._refs) {
+ if (!ref.startsWith('#/components/parameters/')) {
+ continue
+ }
+ const paramName = ref.replace('#/components/parameters/', '')
+ const paramDef = allParameters[paramName]
+ if (paramDef) {
+ filteredParameters[paramName] = paramDef
+ collectSchemaRefs(paramDef, entry._refs)
+ }
+ }
+
const allRefs = resolveNestedRefs(allSchemas, entry._refs)
const filteredSchemas = {}
@@ -317,19 +331,26 @@ function buildGroupedSchemasByOutput(schema, mappings) {
}
}
- // Inline the full `components.parameters` (and any other top-level
- // component buckets we don't slice) verbatim. The per-product paths
- // reference shared parameter objects like `#/components/parameters/
- // ProjectIdPath` — without these, orval validation fails with
- // INVALID_REFERENCE and silently writes nothing. The parameter set
- // is small and reused across products, so the duplication is fine.
+ // Inline non-schema component buckets (securitySchemes, responses,
+ // headers, etc.) verbatim — per-product paths reference shared
+ // objects like `#/components/parameters/ProjectIdPath`, and without
+ // them orval validation fails with INVALID_REFERENCE and silently
+ // writes nothing. Parameters specifically are slicing-friendly and
+ // tracked via `_refs`, so we override with the filtered subset.
const sharedComponents = { ...schema.components }
delete sharedComponents.schemas
+ delete sharedComponents.parameters
+
+ const components = { ...sharedComponents, schemas: filteredSchemas }
+ if (Object.keys(filteredParameters).length > 0) {
+ components.parameters = filteredParameters
+ }
+
grouped.set(outputDir, {
openapi: entry.openapi,
info: { ...entry.info, title: `${entry.info?.title ?? 'API'} - ${path.basename(outputDir)}` },
paths: entry.paths,
- components: { ...sharedComponents, schemas: filteredSchemas },
+ components,
})
}
diff --git a/posthog/hogql_queries/ai/ai_table_resolver.py b/posthog/hogql_queries/ai/ai_table_resolver.py
index 1e207bc0a89d..3f1f12da1902 100644
--- a/posthog/hogql_queries/ai/ai_table_resolver.py
+++ b/posthog/hogql_queries/ai/ai_table_resolver.py
@@ -26,10 +26,11 @@ AI_EVENTS_QUERY_DURATION_SECONDS = Histogram(
)
if TYPE_CHECKING:
- from posthog.hogql.constants import LimitContext
+ from posthog.hogql.constants import HogQLGlobalSettings, LimitContext
from posthog.hogql.modifiers import HogQLQueryModifiers
from posthog.hogql.timings import HogQLTimings
+ from posthog.clickhouse.client.connection import Workload
from posthog.models import Team
@@ -56,6 +57,8 @@ def execute_with_ai_events_fallback(
timings: HogQLTimings | None = None,
modifiers: HogQLQueryModifiers | None = None,
limit_context: LimitContext | None = None,
+ settings: HogQLGlobalSettings | None = None,
+ workload: Workload | None = None,
) -> Any:
"""Execute a query written against ai_events, falling back to events if no results.
@@ -64,6 +67,12 @@ def execute_with_ai_events_fallback(
which are rewritten to native columns for ai_events and back for the events fallback.
When the kill switch (is_ai_events_enabled) is off, skips the ai_events attempt entirely.
+
+ `workload` should be specified explicitly for batch / scheduled callers (e.g. usage
+ reports). Inside a Celery task the `task_prerun` signal sets `Workload.OFFLINE` on
+ the thread default, but outside Celery (Django shell, pytest, management commands)
+ that signal does not fire — so callers that must run on a specific pool should not
+ rely on it implicitly.
"""
kwargs: dict[str, Any] = {"query_type": query_type, "team": team}
if timings is not None:
@@ -72,6 +81,10 @@ def execute_with_ai_events_fallback(
kwargs["modifiers"] = modifiers
if limit_context is not None:
kwargs["limit_context"] = limit_context
+ if settings is not None:
+ kwargs["settings"] = settings
+ if workload is not None:
+ kwargs["workload"] = workload
with tags_context(product=Product.LLM_ANALYTICS):
if is_ai_events_enabled(team):
diff --git a/posthog/hogql_queries/ai/test/test_ai_table_resolver.py b/posthog/hogql_queries/ai/test/test_ai_table_resolver.py
index f748df2527ba..13d4df2144cb 100644
--- a/posthog/hogql_queries/ai/test/test_ai_table_resolver.py
+++ b/posthog/hogql_queries/ai/test/test_ai_table_resolver.py
@@ -164,6 +164,8 @@ class TestExecuteWithAiEventsFallback:
timings = Mock()
modifiers = Mock()
limit_context = Mock()
+ settings = Mock()
+ workload = Mock()
execute_with_ai_events_fallback(
query=self._make_query(),
@@ -173,9 +175,35 @@ class TestExecuteWithAiEventsFallback:
timings=timings,
modifiers=modifiers,
limit_context=limit_context,
+ settings=settings,
+ workload=workload,
)
kwargs = mock_execute.call_args.kwargs
assert kwargs["timings"] is timings
assert kwargs["modifiers"] is modifiers
assert kwargs["limit_context"] is limit_context
+ assert kwargs["settings"] is settings
+ assert kwargs["workload"] is workload
+
+ @patch("posthog.hogql_queries.ai.ai_table_resolver.execute_hogql_query")
+ @patch("posthog.hogql_queries.ai.ai_table_resolver.is_ai_events_enabled", return_value=True)
+ def test_omits_unset_optional_kwargs(self, _mock_flag, mock_execute):
+ # Unset kwargs must NOT appear in the forwarded call so they don't override
+ # execute_hogql_query's defaults (workload=DEFAULT, etc).
+ mock_execute.return_value = self._make_result([["found"]])
+
+ team = Mock(id=1, organization_id="org")
+ execute_with_ai_events_fallback(
+ query=self._make_query(),
+ placeholders={},
+ team=team,
+ query_type="TestQuery",
+ )
+
+ kwargs = mock_execute.call_args.kwargs
+ assert "timings" not in kwargs
+ assert "modifiers" not in kwargs
+ assert "limit_context" not in kwargs
+ assert "settings" not in kwargs
+ assert "workload" not in kwargs
diff --git a/posthog/hogql_queries/ai/trace_id_resolver.py b/posthog/hogql_queries/ai/trace_id_resolver.py
new file mode 100644
index 000000000000..17a39503f71e
--- /dev/null
+++ b/posthog/hogql_queries/ai/trace_id_resolver.py
@@ -0,0 +1,84 @@
+"""Resolve generation event UUIDs → parent trace_id via a small `events` lookup.
+
+Used as a preflight before heavy-column reads on `ai_events`. The `ai_events`
+sorting key `(team_id, trace_id, timestamp)` is useless for `WHERE uuid IN (...)`
+queries that don't carry trace_id — they fan out across every shard via the
+`cityHash64(team_id, trace_id, ...)` sharding key, then read heavy columns
+(input, output, output_choices, ...) on each one. A bloom filter on `uuid`
+helps with within-shard granule skipping but can't address the cross-shard
+fan-out — only knowing trace_id can.
+
+This helper does the trace_id discovery cheaply on the shared `events` table:
+its sorting key `(team_id, toDate(timestamp), event, ...)` lets the scan be
+narrowed by `(team, date_range, event='$ai_generation')`, and we project only
+`properties.$ai_trace_id` (HogQL resolves to the materialized
+`mat_$ai_trace_id` column on events). Small column read on a narrowed range
+even when the row-level uuid filter has to scan.
+
+Then the caller plugs the discovered trace_ids into the heavy-column query on
+`ai_events` — getting the full sorting-key prefix `(team_id, trace_id,
+timestamp)` plus single-shard pruning via the sharding key.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from posthog.hogql import ast
+from posthog.hogql.parser import parse_select
+from posthog.hogql.query import execute_hogql_query
+
+from posthog.clickhouse.query_tagging import Product, tags_context
+
+if TYPE_CHECKING:
+ from datetime import datetime
+
+ from posthog.models.team import Team
+
+
+def resolve_trace_ids_for_generation_uuids(
+ team: Team,
+ generation_uuids: list[str],
+ ts_start: datetime,
+ ts_end: datetime,
+ *,
+ query_type: str = "TraceIdResolveForHeavyFetch",
+) -> dict[str, str]:
+ """Map generation event UUIDs → parent trace_id by reading `events`.
+
+ Returns `{uuid: trace_id}` for uuids whose trace_id was found. UUIDs
+ without a known trace_id are silently dropped — the caller decides how
+ to handle (e.g. skip the heavy fetch entirely, or fall back to a
+ no-trace-id query).
+
+ `ts_start` / `ts_end` are required and bound the events scan via the
+ `toDate(timestamp)` sorting-key segment + partition pruning. Pass a
+ window aligned with the eventual heavy-fetch window.
+ """
+ if not generation_uuids:
+ return {}
+
+ query = parse_select(
+ """
+ SELECT toString(uuid) AS uuid, properties.$ai_trace_id AS trace_id
+ FROM events
+ WHERE event = '$ai_generation'
+ AND timestamp >= {ts_start}
+ AND timestamp < {ts_end}
+ AND toString(uuid) IN {uuids}
+ """
+ )
+
+ with tags_context(product=Product.LLM_ANALYTICS):
+ result = execute_hogql_query(
+ query_type=query_type,
+ query=query,
+ placeholders={
+ "ts_start": ast.Constant(value=ts_start),
+ "ts_end": ast.Constant(value=ts_end),
+ "uuids": ast.Array(exprs=[ast.Constant(value=u) for u in generation_uuids]),
+ },
+ team=team,
+ )
+
+ return {row[0]: row[1] for row in (result.results or []) if row[0] and row[1]}
diff --git a/posthog/temporal/llm_analytics/eval_reports/report_agent/test/test_tools_strip_migration.py b/posthog/temporal/llm_analytics/eval_reports/report_agent/test/test_tools_strip_migration.py
new file mode 100644
index 000000000000..1565827b3a68
--- /dev/null
+++ b/posthog/temporal/llm_analytics/eval_reports/report_agent/test/test_tools_strip_migration.py
@@ -0,0 +1,354 @@
+"""Strip-migration tests for the eval-report agent's heavy-prop tools.
+
+`sample_generation_details`, `get_generation_detail`, and
+`get_generation_text_repr` are the three tools that read heavy columns. They
+route through `_execute_hogql_via_ai_events` which wraps the resolver. The
+other query sites in `tools.py` deliberately stay on `events` directly via
+`_execute_hogql` (see the module docstring on `_execute_hogql` for the
+rationale).
+"""
+
+from typing import cast
+
+from posthog.test.base import BaseTest
+from unittest.mock import MagicMock, patch
+
+from posthog.hogql import ast
+
+from posthog.temporal.llm_analytics.eval_reports.report_agent.schema import EvalReportContent
+from posthog.temporal.llm_analytics.eval_reports.report_agent.tools import (
+ get_generation_detail,
+ get_generation_text_repr,
+ sample_generation_details,
+)
+
+_VALID_GEN_ID = "12345678-1234-1234-1234-123456789abc"
+_VALID_GEN_ID_2 = "abcdefab-cdef-abcd-efab-cdefabcdefab"
+
+_sample_fn = sample_generation_details.func # type: ignore[attr-defined]
+_get_detail_fn = get_generation_detail.func # type: ignore[attr-defined]
+_get_text_repr_fn = get_generation_text_repr.func # type: ignore[attr-defined]
+
+_RESOLVE_PATH = "posthog.hogql_queries.ai.trace_id_resolver.resolve_trace_ids_for_generation_uuids"
+
+
+def _state(team_id: int) -> dict:
+ return {
+ "team_id": team_id,
+ "evaluation_id": "eval-1",
+ "period_start": "2026-04-27T00:00:00+00:00",
+ "period_end": "2026-04-28T00:00:00+00:00",
+ "previous_period_start": "2026-04-26T00:00:00+00:00",
+ "report": EvalReportContent(),
+ }
+
+
+def _resolver_response(rows: list[list]) -> MagicMock:
+ response = MagicMock()
+ response.results = rows
+ return response
+
+
+class TestSampleGenerationDetailsRoutesThroughResolver(BaseTest):
+ @patch("posthog.hogql_queries.ai.ai_table_resolver.execute_with_ai_events_fallback")
+ @patch(_RESOLVE_PATH, return_value={_VALID_GEN_ID: "trace-1"})
+ def test_routes_through_resolver_against_ai_events(self, _mock_lookup, mock_resolver):
+ """The heavy-prop tool must hit the resolver, not raw `execute_hogql_query`."""
+ mock_resolver.return_value = _resolver_response(
+ [
+ [
+ _VALID_GEN_ID,
+ "gpt-4o", # model
+ [{"role": "user", "content": "hi"}], # input (heavy, native column)
+ [{"role": "assistant", "content": "hello"}], # output
+ 10,
+ 5,
+ "trace-1",
+ False,
+ None,
+ None,
+ None,
+ None,
+ None,
+ ]
+ ]
+ )
+
+ result = _sample_fn(state=_state(self.team.id), generation_ids=[_VALID_GEN_ID])
+
+ # Returns rendered JSON with input/output previews from heavy columns.
+ assert "post-strip" not in result # sanity: nothing weird leaked
+ assert mock_resolver.call_count == 1
+ kwargs = mock_resolver.call_args.kwargs
+ select = cast(ast.SelectQuery, kwargs["query"])
+ from_chain = select.select_from.table.chain # type: ignore[union-attr]
+ # nosemgrep: hogql-no-string-table-chain
+ assert from_chain == ["posthog", "ai_events"]
+ assert kwargs["query_type"] == "EvalReportAgent"
+ placeholders = kwargs["placeholders"]
+ assert "trace_ids" in placeholders
+ trace_id_values = [const.value for const in placeholders["trace_ids"].exprs]
+ assert trace_id_values == ["trace-1"]
+
+ @patch("posthog.hogql_queries.ai.ai_table_resolver.execute_with_ai_events_fallback")
+ @patch(_RESOLVE_PATH, return_value={})
+ def test_skips_heavy_fetch_when_no_trace_ids_resolved(self, _mock_lookup, mock_resolver):
+ """If the events preflight finds no rows (uuids purged or never existed),
+ skip the heavy ai_events query entirely — no point fanning out across
+ shards for a known-empty result."""
+ result = _sample_fn(state=_state(self.team.id), generation_ids=[_VALID_GEN_ID])
+
+ assert result == "[]"
+ assert mock_resolver.call_count == 0
+
+
+class TestGetGenerationDetailRoutesThroughResolver(BaseTest):
+ @patch("posthog.hogql_queries.ai.ai_table_resolver.execute_with_ai_events_fallback")
+ @patch("posthog.hogql.query.execute_hogql_query")
+ @patch(_RESOLVE_PATH, return_value={_VALID_GEN_ID: "trace-1"})
+ def test_main_query_uses_resolver_eval_query_uses_events(self, _mock_lookup, mock_events, mock_resolver):
+ """Within `get_generation_detail`, the main generation lookup reads heavy
+ columns and routes via the resolver. The eval-rows lookup reads only
+ non-heavy fields (`$ai_evaluation_*`) and stays on `events` directly.
+ """
+ from datetime import datetime
+
+ # Resolver returns the gen row (heavy path).
+ mock_resolver.return_value = _resolver_response(
+ [
+ [
+ _VALID_GEN_ID,
+ "gpt-4o", # model
+ "openai", # provider
+ [{"role": "user", "content": "hi"}], # input
+ [{"role": "assistant", "content": "hello"}], # output
+ 10,
+ 5,
+ 0.001,
+ 0.4,
+ "trace-1",
+ "https://api.openai.com/v1/",
+ datetime(2026, 4, 27, 7, 0),
+ False,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ ]
+ ]
+ )
+ # Non-resolver path returns eval rows.
+ mock_events.return_value = MagicMock(results=[])
+
+ _get_detail_fn(state=_state(self.team.id), generation_id=_VALID_GEN_ID)
+
+ # Heavy path went through the resolver.
+ assert mock_resolver.call_count == 1
+ # Non-heavy eval-rows query went through plain execute_hogql_query (events).
+ assert mock_events.call_count == 1
+ # Heavy fetch carries the resolved trace_id — proves the two-query
+ # pattern wires through, not just that the WHERE has uuid.
+ kwargs = mock_resolver.call_args.kwargs
+ placeholders = kwargs["placeholders"]
+ assert "trace_id" in placeholders
+ assert placeholders["trace_id"].value == "trace-1"
+
+ @patch("posthog.hogql_queries.ai.ai_table_resolver.execute_with_ai_events_fallback")
+ @patch(_RESOLVE_PATH, return_value={})
+ def test_returns_not_found_when_trace_id_lookup_misses(self, _mock_lookup, mock_resolver):
+ """If the events preflight can't find the generation, surface a not-found
+ error to the agent without paying for a heavy ai_events fan-out."""
+ result = _get_detail_fn(state=_state(self.team.id), generation_id=_VALID_GEN_ID)
+ assert "not found" in result.lower()
+ assert mock_resolver.call_count == 0
+
+ def test_invalid_generation_id_returns_error_without_querying(self):
+ with patch("posthog.hogql_queries.ai.ai_table_resolver.execute_with_ai_events_fallback") as mock_resolver:
+ result = _get_detail_fn(state=_state(self.team.id), generation_id="not-a-uuid")
+ assert "error" in result.lower()
+ assert mock_resolver.call_count == 0
+
+
+class TestGetGenerationTextReprRoutesThroughResolver(BaseTest):
+ """`get_generation_text_repr` reads `$ai_input`/`$ai_output`/`$ai_output_choices`/
+ `$ai_tools` indirectly through the formatter. Those are 4 of the 6 stripped
+ heavy columns, so the tool must hit ai_events — querying `events.properties`
+ directly would render an empty skeleton post-cutover."""
+
+ @patch("posthog.hogql_queries.ai.ai_table_resolver.execute_with_ai_events_fallback")
+ @patch(_RESOLVE_PATH, return_value={_VALID_GEN_ID: "trace-1"})
+ def test_routes_through_resolver_against_ai_events(self, _mock_lookup, mock_resolver):
+ """Heavy fetch goes through the resolver and selects from posthog.ai_events."""
+ from datetime import datetime
+
+ mock_resolver.return_value = _resolver_response(
+ [
+ [
+ _VALID_GEN_ID,
+ "$ai_generation",
+ datetime(2026, 4, 27, 7, 0),
+ '[{"role":"user","content":"hi"}]', # input
+ '"hello"', # output (JSON-encoded string — text-output call shape)
+ None, # output_choices
+ None, # tools
+ 0, # is_error
+ None, # error
+ ]
+ ]
+ )
+
+ result = _get_text_repr_fn(state=_state(self.team.id), generation_id=_VALID_GEN_ID)
+
+ # Sanity: rendered both input and output sections from heavy columns.
+ assert "INPUT:" in result
+ assert "OUTPUT:" in result
+ assert "hi" in result
+ assert "hello" in result
+
+ assert mock_resolver.call_count == 1
+ kwargs = mock_resolver.call_args.kwargs
+ select = cast(ast.SelectQuery, kwargs["query"])
+ from_chain = select.select_from.table.chain # type: ignore[union-attr]
+ # nosemgrep: hogql-no-string-table-chain
+ assert from_chain == ["posthog", "ai_events"]
+ assert kwargs["query_type"] == "EvalReportAgent"
+ placeholders = kwargs["placeholders"]
+ assert placeholders["trace_id"].value == "trace-1"
+ assert placeholders["generation_id"].value == _VALID_GEN_ID
+
+ @patch("posthog.hogql_queries.ai.ai_table_resolver.execute_with_ai_events_fallback")
+ @patch(_RESOLVE_PATH, return_value={_VALID_GEN_ID: "trace-1"})
+ def test_parses_output_choices_dict_format(self, _mock_lookup, mock_resolver):
+ """`$ai_output_choices` must arrive as a parsed structure — the formatter's
+ `isinstance(..., dict)` / `isinstance(..., list)` checks reject raw JSON
+ strings, so the choices wouldn't render."""
+ from datetime import datetime
+
+ mock_resolver.return_value = _resolver_response(
+ [
+ [
+ _VALID_GEN_ID,
+ "$ai_generation",
+ datetime(2026, 4, 27, 7, 0),
+ '[{"role":"user","content":"hi"}]',
+ "", # empty output (chat-format calls)
+ '[{"message":{"role":"assistant","content":"choice content"}}]',
+ None,
+ 0,
+ None,
+ ]
+ ]
+ )
+
+ result = _get_text_repr_fn(state=_state(self.team.id), generation_id=_VALID_GEN_ID)
+ assert "choice content" in result
+
+ @patch("posthog.hogql_queries.ai.ai_table_resolver.execute_with_ai_events_fallback")
+ @patch(_RESOLVE_PATH, return_value={_VALID_GEN_ID: "trace-1"})
+ def test_renders_error_section_when_is_error(self, _mock_lookup, mock_resolver):
+ """`is_error` / `error` are dedicated columns — propagate them as
+ `$ai_is_error` / `$ai_error` on the synthetic props so the formatter's
+ error section fires."""
+ from datetime import datetime
+
+ mock_resolver.return_value = _resolver_response(
+ [
+ [
+ _VALID_GEN_ID,
+ "$ai_generation",
+ datetime(2026, 4, 27, 7, 0),
+ '[{"role":"user","content":"hi"}]',
+ None,
+ None,
+ None,
+ 1, # is_error
+ "boom", # error
+ ]
+ ]
+ )
+
+ result = _get_text_repr_fn(state=_state(self.team.id), generation_id=_VALID_GEN_ID)
+ assert "ERROR:" in result
+ assert "boom" in result
+
+ @patch("posthog.hogql_queries.ai.ai_table_resolver.execute_with_ai_events_fallback")
+ @patch(_RESOLVE_PATH, return_value={_VALID_GEN_ID: "trace-1"})
+ def test_handles_all_heavy_columns_null(self, _mock_lookup, mock_resolver):
+ """A generation with all heavy columns nulled should still render — the
+ formatter just produces an empty body, no exception."""
+ from datetime import datetime
+
+ mock_resolver.return_value = _resolver_response(
+ [
+ [
+ _VALID_GEN_ID,
+ "$ai_generation",
+ datetime(2026, 4, 27, 7, 0),
+ None,
+ None,
+ None,
+ None,
+ 0,
+ None,
+ ]
+ ]
+ )
+
+ result = _get_text_repr_fn(state=_state(self.team.id), generation_id=_VALID_GEN_ID)
+ # No INPUT / OUTPUT / TOOLS / ERROR sections — formatter returns empty string.
+ assert "INPUT:" not in result
+ assert "OUTPUT:" not in result
+ assert "ERROR:" not in result
+
+ @patch("posthog.hogql_queries.ai.ai_table_resolver.execute_with_ai_events_fallback")
+ @patch(_RESOLVE_PATH, return_value={_VALID_GEN_ID: "trace-1"})
+ def test_passes_non_json_string_input_through_to_formatter(self, _mock_lookup, mock_resolver):
+ """Heavy columns are usually JSON-encoded but a plain text input
+ (embedding-style instrumentation) should still render — fall back to
+ passing the raw string when JSON decoding fails."""
+ from datetime import datetime
+
+ mock_resolver.return_value = _resolver_response(
+ [
+ [
+ _VALID_GEN_ID,
+ "$ai_generation",
+ datetime(2026, 4, 27, 7, 0),
+ "plain text prompt", # not valid JSON
+ None,
+ None,
+ None,
+ 0,
+ None,
+ ]
+ ]
+ )
+
+ result = _get_text_repr_fn(state=_state(self.team.id), generation_id=_VALID_GEN_ID)
+ assert "plain text prompt" in result
+
+ @patch("posthog.hogql_queries.ai.ai_table_resolver.execute_with_ai_events_fallback")
+ @patch(_RESOLVE_PATH, return_value={})
+ def test_returns_not_found_when_trace_id_lookup_misses(self, _mock_lookup, mock_resolver):
+ """Skip the heavy fan-out when the events preflight can't find the uuid."""
+ result = _get_text_repr_fn(state=_state(self.team.id), generation_id=_VALID_GEN_ID)
+ assert "not found" in result.lower()
+ assert mock_resolver.call_count == 0
+
+ @patch("posthog.hogql_queries.ai.ai_table_resolver.execute_with_ai_events_fallback")
+ @patch(_RESOLVE_PATH, return_value={_VALID_GEN_ID: "trace-1"})
+ def test_returns_not_found_when_ai_events_query_empty(self, _mock_lookup, mock_resolver):
+ """Trace_id resolved but ai_events returns no rows (e.g. raced TTL eviction)."""
+ mock_resolver.return_value = _resolver_response([])
+ result = _get_text_repr_fn(state=_state(self.team.id), generation_id=_VALID_GEN_ID)
+ assert "not found" in result.lower()
+
+ def test_invalid_generation_id_returns_error_without_querying(self):
+ with patch("posthog.hogql_queries.ai.ai_table_resolver.execute_with_ai_events_fallback") as mock_resolver:
+ with patch(_RESOLVE_PATH) as mock_lookup:
+ result = _get_text_repr_fn(state=_state(self.team.id), generation_id="not-a-uuid")
+ assert "error" in result.lower()
+ assert mock_resolver.call_count == 0
+ assert mock_lookup.call_count == 0
diff --git a/posthog/temporal/llm_analytics/eval_reports/report_agent/tools.py b/posthog/temporal/llm_analytics/eval_reports/report_agent/tools.py
index 40df636f0bf6..ea3ab0858142 100644
--- a/posthog/temporal/llm_analytics/eval_reports/report_agent/tools.py
+++ b/posthog/temporal/llm_analytics/eval_reports/report_agent/tools.py
@@ -10,7 +10,7 @@ InjectedState, but whole-key replacement does not.
import re
import json
from datetime import UTC, datetime, timedelta
-from typing import Annotated
+from typing import TYPE_CHECKING, Annotated
from langchain_core.tools import tool
from langgraph.prebuilt import InjectedState
@@ -19,6 +19,9 @@ from posthog.hogql import ast
from posthog.temporal.llm_analytics.eval_reports.report_agent.schema import MAX_REPORT_SECTIONS, Citation, ReportSection
+if TYPE_CHECKING:
+ from posthog.models import Team
+
# Strict UUID match for validating IDs before string-interpolating into HogQL
# and before storing in Citation. Generation IDs reach this code from the LLM,
# which can relay arbitrary `$ai_target_event_id` property values set by user
@@ -66,7 +69,14 @@ def _widened_ts_window(state: dict) -> tuple[datetime, datetime]:
def _execute_hogql(team_id: int, query_str: str, placeholders: dict | None = None) -> list[list]:
- """Execute a HogQL query and return results."""
+ """Execute a HogQL query against `events` and return results.
+
+ Used by every query in this module that does NOT read the six stripped
+ heavy columns (`input`, `output`, `output_choices`, `input_state`,
+ `output_state`, `tools`). Sweeping these through the resolver too would
+ only buy uniform `ai_query_source` tagging — a deliberate scope choice,
+ not load-bearing for the strip-heavy migration.
+ """
from posthog.hogql.parser import parse_select
from posthog.hogql.query import execute_hogql_query
@@ -87,6 +97,34 @@ def _execute_hogql(team_id: int, query_str: str, placeholders: dict | None = Non
return result.results or []
+def _execute_hogql_via_ai_events(team: "Team", query_str: str, placeholders: dict | None = None) -> list[list]:
+ """Execute a HogQL query written against `posthog.ai_events` with the events-table fallback.
+
+ Use this only for queries that read heavy columns (`input`, `output`,
+ `output_choices`, `input_state`, `output_state`, `tools`) — those are
+ stripped from `events.properties` post-cutover and only survive in the
+ dedicated `ai_events` table. Other queries should keep using
+ `_execute_hogql` against `events`.
+ """
+ from posthog.hogql.parser import parse_select
+
+ from posthog.hogql_queries.ai.ai_table_resolver import execute_with_ai_events_fallback
+
+ query = parse_select(query_str)
+
+ # `execute_with_ai_events_fallback` wraps its own
+ # `tags_context(product=Product.LLM_ANALYTICS)` internally; no need to
+ # double-wrap here.
+ result = execute_with_ai_events_fallback(
+ query=query,
+ placeholders=placeholders or {},
+ team=team,
+ query_type="EvalReportAgent",
+ )
+
+ return result.results or []
+
+
def _fetch_period_counts(
team_id: int, evaluation_id: str, ts_start: datetime, ts_end: datetime
) -> tuple[int, int, int, int]:
@@ -401,8 +439,6 @@ def sample_generation_details(
Args:
generation_ids: List of generation IDs to look up (max 20)
"""
- team_id = state["team_id"]
-
if not generation_ids:
return json.dumps([])
@@ -418,33 +454,56 @@ def sample_generation_details(
# which the SDK doesn't set). Match on the event uuid column.
# $ai_output is empty for chat-format SDK calls (most OpenAI/Anthropic).
# The actual content lives in $ai_output_choices. Use COALESCE to fall back.
- rows = _execute_hogql(
- team_id,
+ # Reads heavy `input` / `output` / `output_choices` / `input_state` /
+ # `output_state` — must go through ai_events (post-strip those are NULL on
+ # events). On the events fallback the column rewriter rewrites these
+ # native columns back to `properties.$ai_*`, so the coalesce semantics are
+ # preserved on both branches.
+ from posthog.hogql_queries.ai.trace_id_resolver import resolve_trace_ids_for_generation_uuids
+ from posthog.models import Team
+
+ team = Team.objects.get(id=state["team_id"])
+ ts_start, ts_end = _widened_ts_window(state)
+ trace_id_by_uuid = resolve_trace_ids_for_generation_uuids(
+ team=team,
+ generation_uuids=ids_to_fetch,
+ ts_start=ts_start,
+ ts_end=ts_end,
+ query_type="EvalReportAgentTraceIdResolve",
+ )
+ trace_ids = sorted({tid for tid in trace_id_by_uuid.values() if tid})
+ if not trace_ids:
+ return json.dumps([])
+
+ rows = _execute_hogql_via_ai_events(
+ team,
"""
SELECT
toString(uuid) as generation_id,
- properties.$ai_model as model,
- properties.$ai_input as input,
+ model,
+ input,
coalesce(
- nullIf(properties.$ai_output, ''),
- properties.$ai_output_choices
+ nullIf(output, ''),
+ output_choices
) as output,
- properties.$ai_input_tokens as input_tokens,
- properties.$ai_output_tokens as output_tokens,
- properties.$ai_trace_id as trace_id,
- properties.$ai_is_error as is_error,
- properties.$ai_error as error,
+ input_tokens,
+ output_tokens,
+ trace_id,
+ is_error,
+ error,
properties.$ai_tools_called as tools_called,
properties.$ai_tool_call_count as tool_call_count,
- properties.$ai_input_state as input_state,
- properties.$ai_output_state as output_state
- FROM events
+ input_state,
+ output_state
+ FROM posthog.ai_events AS ai_events
WHERE event = '$ai_generation'
+ AND trace_id IN {trace_ids}
AND toString(uuid) IN {ids}
LIMIT {limit}
""",
placeholders={
"ids": ast.Array(exprs=[ast.Constant(value=gid) for gid in ids_to_fetch]),
+ "trace_ids": ast.Array(exprs=[ast.Constant(value=tid) for tid in trace_ids]),
"limit": ast.Constant(value=len(ids_to_fetch)),
},
)
@@ -497,6 +556,10 @@ def get_generation_detail(
if not _UUID_RE.fullmatch(generation_id):
return json.dumps({"error": "Invalid generation ID format"})
+ from posthog.hogql_queries.ai.trace_id_resolver import resolve_trace_ids_for_generation_uuids
+ from posthog.models import Team
+
+ team = Team.objects.get(id=team_id)
ts_start, ts_end = _widened_ts_window(state)
shared_placeholders = {
"generation_id": ast.Constant(value=generation_id),
@@ -504,41 +567,57 @@ def get_generation_detail(
"ts_end": ast.Constant(value=ts_end),
}
- # Full generation event data
- gen_rows = _execute_hogql(
- team_id,
+ trace_id_by_uuid = resolve_trace_ids_for_generation_uuids(
+ team=team,
+ generation_uuids=[generation_id],
+ ts_start=ts_start,
+ ts_end=ts_end,
+ query_type="EvalReportAgentTraceIdResolve",
+ )
+ trace_id = trace_id_by_uuid.get(generation_id)
+ if not trace_id:
+ return json.dumps({"error": f"Generation {generation_id} not found"})
+
+ gen_placeholders = {
+ "generation_id": shared_placeholders["generation_id"],
+ "trace_id": ast.Constant(value=trace_id),
+ }
+
+ # Full generation event data — heavy `input` / `output` / `output_choices` /
+ # `tools` / `input_state` / `output_state` only survive on ai_events.
+ gen_rows = _execute_hogql_via_ai_events(
+ team,
"""
SELECT
toString(uuid) as generation_id,
- properties.$ai_model as model,
- properties.$ai_provider as provider,
- properties.$ai_input as input,
+ model,
+ provider,
+ input,
coalesce(
- nullIf(properties.$ai_output, ''),
- properties.$ai_output_choices
+ nullIf(output, ''),
+ output_choices
) as output,
- properties.$ai_input_tokens as input_tokens,
- properties.$ai_output_tokens as output_tokens,
- properties.$ai_total_cost_usd as cost,
- properties.$ai_latency as latency,
- properties.$ai_trace_id as trace_id,
+ input_tokens,
+ output_tokens,
+ total_cost_usd as cost,
+ latency,
+ trace_id,
properties.$ai_base_url as base_url,
timestamp,
- properties.$ai_is_error as is_error,
- properties.$ai_error as error,
+ is_error,
+ error,
properties.$ai_tools_called as tools_called,
properties.$ai_tool_call_count as tool_call_count,
- properties.$ai_tools as tools_available,
- properties.$ai_input_state as input_state,
- properties.$ai_output_state as output_state
- FROM events
+ tools as tools_available,
+ input_state,
+ output_state
+ FROM posthog.ai_events AS ai_events
WHERE event = '$ai_generation'
+ AND trace_id = {trace_id}
AND toString(uuid) = {generation_id}
- AND timestamp >= {ts_start}
- AND timestamp < {ts_end}
LIMIT 1
""",
- placeholders=shared_placeholders,
+ placeholders=gen_placeholders,
)
if not gen_rows:
@@ -624,32 +703,50 @@ def get_generation_text_repr(
Args:
generation_id: The generation event UUID to look up
"""
- import orjson
+ from posthog.hogql_queries.ai.trace_id_resolver import resolve_trace_ids_for_generation_uuids
+ from posthog.models import Team
- from products.llm_analytics.backend.text_repr.formatters import format_event_text_repr
-
- team_id = state["team_id"]
+ from products.llm_analytics.backend.text_repr.formatters import format_event_text_repr_from_ai_events_row
if not _UUID_RE.fullmatch(generation_id):
return json.dumps({"error": "Invalid generation ID format"})
+ team = Team.objects.get(id=state["team_id"])
ts_start, ts_end = _widened_ts_window(state)
- rows = _execute_hogql(
- team_id,
+ trace_id_by_uuid = resolve_trace_ids_for_generation_uuids(
+ team=team,
+ generation_uuids=[generation_id],
+ ts_start=ts_start,
+ ts_end=ts_end,
+ query_type="EvalReportAgentTraceIdResolve",
+ )
+ trace_id = trace_id_by_uuid.get(generation_id)
+ if not trace_id:
+ return json.dumps({"error": f"Generation {generation_id} not found"})
+
+ rows = _execute_hogql_via_ai_events(
+ team,
"""
- SELECT uuid, event, timestamp, properties
- FROM events
+ SELECT
+ toString(uuid) as uuid,
+ event,
+ timestamp,
+ input,
+ output,
+ output_choices,
+ tools,
+ is_error,
+ error
+ FROM posthog.ai_events AS ai_events
WHERE event = '$ai_generation'
+ AND trace_id = {trace_id}
AND toString(uuid) = {generation_id}
- AND timestamp >= {ts_start}
- AND timestamp < {ts_end}
LIMIT 1
""",
placeholders={
"generation_id": ast.Constant(value=generation_id),
- "ts_start": ast.Constant(value=ts_start),
- "ts_end": ast.Constant(value=ts_end),
+ "trace_id": ast.Constant(value=trace_id),
},
)
@@ -657,18 +754,19 @@ def get_generation_text_repr(
return json.dumps({"error": f"Generation {generation_id} not found"})
row = rows[0]
- props = row[3]
- if isinstance(props, str):
- props = orjson.loads(props)
-
- event_data = {
- "id": str(row[0]),
- "event": row[1],
- "timestamp": row[2].isoformat() if hasattr(row[2], "isoformat") else str(row[2]),
- "properties": props,
- }
-
- text_repr = format_event_text_repr(event=event_data)
+ text_repr = format_event_text_repr_from_ai_events_row(
+ {
+ "uuid": row[0],
+ "event": row[1],
+ "timestamp": row[2],
+ "input": row[3],
+ "output": row[4],
+ "output_choices": row[5],
+ "tools": row[6],
+ "is_error": row[7],
+ "error": row[8],
+ }
+ )
# Cap at 10k chars to avoid blowing up context
if len(text_repr) > 10_000:
diff --git a/posthog/temporal/llm_analytics/evaluation_clustering/data.py b/posthog/temporal/llm_analytics/evaluation_clustering/data.py
index f55320616970..b66d06d58ea7 100644
--- a/posthog/temporal/llm_analytics/evaluation_clustering/data.py
+++ b/posthog/temporal/llm_analytics/evaluation_clustering/data.py
@@ -25,6 +25,8 @@ from posthog.hogql.parser import parse_select
from posthog.hogql.query import execute_hogql_query
from posthog.clickhouse.query_tagging import Feature, Product, tags_context
+from posthog.hogql_queries.ai.ai_table_resolver import execute_with_ai_events_fallback
+from posthog.hogql_queries.ai.trace_id_resolver import resolve_trace_ids_for_generation_uuids
from posthog.models.team import Team
from posthog.temporal.llm_analytics.evaluation_clustering.constants import (
LLMA_EVALUATION_DOCUMENT_TYPE,
@@ -345,8 +347,8 @@ def fetch_generation_contents(
team: Team,
generation_ids: list[str],
*,
- window_start: datetime | None = None,
- window_end: datetime | None = None,
+ window_start: datetime,
+ window_end: datetime,
max_input_chars: int = 1500,
max_output_chars: int = 1500,
) -> dict[str, dict]:
@@ -360,61 +362,62 @@ def fetch_generation_contents(
full transcripts and the clusters that matter are identified by *patterns*
across many members, not by deep reading of any one.
- ``window_start``/``window_end`` are optional but recommended — without them
- ClickHouse can't prune date partitions from the ``(team_id, toDate(timestamp))``
- index and the query does a full-team scan for a handful of UUIDs. The
- labeling agent passes the same metadata lookup window the workflow uses.
+ Two-query pattern: resolves uuid → trace_id off `events` first (cheap
+ small-column lookup using the events sorting-key prefix), then runs the
+ heavy fetch on `ai_events` with `trace_id IN (...)` so it hits the
+ sorting-key prefix `(team_id, trace_id, timestamp)` + single-shard via
+ the cityHash64 sharding key. ``window_start`` / ``window_end`` are
+ required so the events lookup is bounded by the events sorting key
+ `(team_id, toDate(timestamp), event)` instead of full-team scanning.
"""
if not generation_ids:
return {}
+ trace_id_by_uuid = resolve_trace_ids_for_generation_uuids(
+ team=team,
+ generation_uuids=generation_ids,
+ ts_start=window_start,
+ ts_end=window_end,
+ query_type="ClusteringTraceIdResolve",
+ )
+ trace_ids = sorted({tid for tid in trace_id_by_uuid.values() if tid})
+ if not trace_ids:
+ return {}
+
ids_tuple = ast.Tuple(exprs=[ast.Constant(value=gid) for gid in generation_ids])
- has_window = window_start is not None and window_end is not None
- if has_window:
- query = parse_select(
- """
- SELECT
- toString(uuid) as generation_id,
- properties.$ai_model as model,
- properties.$ai_input as input_raw,
- properties.$ai_output_choices as output_raw
- FROM events
- WHERE event = '$ai_generation'
- AND timestamp >= {start_dt}
- AND timestamp < {end_dt}
- AND toString(uuid) IN {ids}
- LIMIT {limit}
- """
- )
- else:
- query = parse_select(
- """
- SELECT
- toString(uuid) as generation_id,
- properties.$ai_model as model,
- properties.$ai_input as input_raw,
- properties.$ai_output_choices as output_raw
- FROM events
- WHERE event = '$ai_generation'
- AND toString(uuid) IN {ids}
- LIMIT {limit}
- """
- )
+ trace_ids_tuple = ast.Tuple(exprs=[ast.Constant(value=tid) for tid in trace_ids])
+ # Read from `posthog.ai_events` so the heavy `input` / `output_choices`
+ # columns survive the strip; the resolver re-runs against the shared
+ # `events` table when ai_events returns zero rows (rollout window /
+ # kill-switch off). `trace_id IN (...)` gets us the full sorting-key
+ # prefix + single-shard reads instead of an N-shard heavy fan-out.
+ query = parse_select(
+ """
+ SELECT
+ toString(uuid) as generation_id,
+ model,
+ input as input_raw,
+ output_choices as output_raw
+ FROM posthog.ai_events AS ai_events
+ WHERE event = '$ai_generation'
+ AND trace_id IN {trace_ids}
+ AND toString(uuid) IN {ids}
+ LIMIT {limit}
+ """
+ )
placeholders: dict[str, ast.Expr] = {
"ids": ids_tuple,
+ "trace_ids": trace_ids_tuple,
"limit": ast.Constant(value=len(generation_ids)),
}
- if has_window:
- placeholders["start_dt"] = ast.Constant(value=window_start)
- placeholders["end_dt"] = ast.Constant(value=window_end)
with tags_context(product=Product.LLM_ANALYTICS, feature=Feature.QUERY, team_id=team.id):
- result = execute_hogql_query(
- query_type="GenerationContentsForLabeling",
+ result = execute_with_ai_events_fallback(
query=query,
placeholders=placeholders,
team=team,
+ query_type="GenerationContentsForLabeling",
settings=HogQLGlobalSettings(max_execution_time=CLUSTERING_QUERY_MAX_EXECUTION_TIME),
)
diff --git a/posthog/temporal/llm_analytics/evaluation_clustering/labeling_agent/tools.py b/posthog/temporal/llm_analytics/evaluation_clustering/labeling_agent/tools.py
index 7e2039e2748b..232882f31c62 100644
--- a/posthog/temporal/llm_analytics/evaluation_clustering/labeling_agent/tools.py
+++ b/posthog/temporal/llm_analytics/evaluation_clustering/labeling_agent/tools.py
@@ -9,11 +9,31 @@ instead of trace summaries.
import json
from typing import Annotated
+import structlog
from langchain_core.tools import tool
from langgraph.prebuilt import InjectedState
from posthog.temporal.llm_analytics.trace_clustering.models import ClusterLabel
+logger = structlog.get_logger(__name__)
+
+
+def _handle_missing_window(state: dict) -> str:
+ """Log + return the JSON error for the defensive "missing window" branch.
+
+ Tool-level errors are returned as JSON strings to the agent (LangGraph feeds
+ them back to the LLM as a successful tool result), so they don't surface
+ through the workflow's exception path. Logging here makes the branch
+ visible in production should it ever trigger.
+ """
+ logger.warning(
+ "eval_labeling_window_missing",
+ team_id=state.get("team_id"),
+ has_window_start=state.get("window_start") is not None,
+ has_window_end=state.get("window_end") is not None,
+ )
+ return json.dumps({"error": "Clustering-run window missing from state"})
+
def _title_for_eval(eval_id: str, state: dict) -> str:
"""Render the short title the agent sees for an eval in overview passes."""
@@ -230,9 +250,9 @@ def get_generation_details(
team = Team.objects.get(id=state["team_id"])
generation_ids = [gen_id for _, gen_id in pairs]
- # Pass the clustering-run window through so ClickHouse can prune date partitions
- # on the `(team_id, toDate(timestamp))` primary index. Without bounds this would
- # full-scan the team for a handful of UUIDs.
+ # The clustering-run window scopes both the trace_id resolver lookup
+ # (events sorting key) and the heavy ai_events fetch. Required — without
+ # it, the events scan would full-scan the team for a handful of UUIDs.
from datetime import datetime
def _parse(ts: str | None) -> datetime | None:
@@ -243,11 +263,16 @@ def get_generation_details(
except ValueError:
return None
+ window_start = _parse(state.get("window_start"))
+ window_end = _parse(state.get("window_end"))
+ if window_start is None or window_end is None:
+ return _handle_missing_window(state)
+
fetched = fetch_generation_contents(
team=team,
generation_ids=generation_ids,
- window_start=_parse(state.get("window_start")),
- window_end=_parse(state.get("window_end")),
+ window_start=window_start,
+ window_end=window_end,
)
result = []
diff --git a/posthog/temporal/llm_analytics/evaluation_clustering/tests/test_strip_migration.py b/posthog/temporal/llm_analytics/evaluation_clustering/tests/test_strip_migration.py
new file mode 100644
index 000000000000..419efb503a98
--- /dev/null
+++ b/posthog/temporal/llm_analytics/evaluation_clustering/tests/test_strip_migration.py
@@ -0,0 +1,158 @@
+"""Strip-migration tests for the eval clustering data layer.
+
+`fetch_generation_contents` is the only at-risk reader in
+`evaluation_clustering/data.py` (it reads heavy `input` / `output_choices`).
+It uses a two-query pattern: resolves uuid → trace_id off `events`
+first, then runs the heavy fetch on `ai_events` with `trace_id IN (...)`
+so the lookup hits the sorting-key prefix `(team_id, trace_id, timestamp)`
+and lands on a single shard via the cityHash64 sharding key. Tests mock
+both layers.
+"""
+
+from datetime import UTC, datetime
+from typing import cast
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from posthog.hogql import ast
+
+from posthog.temporal.llm_analytics.evaluation_clustering.data import fetch_generation_contents
+
+_RESOLVE_PATH = "posthog.temporal.llm_analytics.evaluation_clustering.data.resolve_trace_ids_for_generation_uuids"
+_WINDOW_START = datetime(2026, 4, 27, 7, 0, 0, tzinfo=UTC)
+_WINDOW_END = datetime(2026, 4, 27, 8, 0, 0, tzinfo=UTC)
+
+
+def team(db):
+ from posthog.models.organization import Organization
+ from posthog.models.team import Team
+
+ organization = Organization.objects.create(name="Test Org")
+ return Team.objects.create(organization=organization, name="Test Team")
+
+
+def _resolver_response(rows: list[list]) -> MagicMock:
+ response = MagicMock()
+ response.results = rows
+ return response
+
+
+class TestFetchGenerationContents:
+ def test_empty_id_list_short_circuits(self, team):
+ # No queries at all when there's nothing to fetch — guards against
+ # an N×0 query that would scan the whole window.
+ with (
+ patch(
+ "posthog.temporal.llm_analytics.evaluation_clustering.data.execute_with_ai_events_fallback"
+ ) as mock_resolver,
+ patch(_RESOLVE_PATH) as mock_resolve,
+ ):
+ result = fetch_generation_contents(
+ team, generation_ids=[], window_start=_WINDOW_START, window_end=_WINDOW_END
+ )
+ assert result == {}
+ assert mock_resolver.call_count == 0
+ assert mock_resolve.call_count == 0
+
+ @patch(_RESOLVE_PATH, return_value={"gid-1": "trace-A", "gid-2": "trace-B"})
+ def test_returns_per_generation_dict(self, _mock_resolve, team):
+ with patch(
+ "posthog.temporal.llm_analytics.evaluation_clustering.data.execute_with_ai_events_fallback"
+ ) as mock_resolver:
+ # Row tuple: (generation_id, model, input_raw, output_raw)
+ mock_resolver.return_value = _resolver_response(
+ [
+ ["gid-1", "gpt-4o", '[{"role":"user","content":"hi"}]', '[{"role":"assistant","content":"hello"}]'],
+ ["gid-2", "gpt-4o", '[{"role":"user","content":"yo"}]', '[{"role":"assistant","content":"sup"}]'],
+ ]
+ )
+ result = fetch_generation_contents(
+ team, generation_ids=["gid-1", "gid-2"], window_start=_WINDOW_START, window_end=_WINDOW_END
+ )
+ assert set(result.keys()) == {"gid-1", "gid-2"}
+ assert result["gid-1"]["model"] == "gpt-4o"
+ assert "hi" in result["gid-1"]["input"]
+ assert "hello" in result["gid-1"]["output"]
+
+ @patch(_RESOLVE_PATH, return_value={"gid-1": "trace-A"})
+ def test_truncates_input_and_output(self, _mock_resolve, team):
+ big = "x" * 5000
+ with patch(
+ "posthog.temporal.llm_analytics.evaluation_clustering.data.execute_with_ai_events_fallback"
+ ) as mock_resolver:
+ mock_resolver.return_value = _resolver_response([["gid-1", "gpt-4o", big, big]])
+ result = fetch_generation_contents(
+ team,
+ generation_ids=["gid-1"],
+ max_input_chars=100,
+ max_output_chars=200,
+ window_start=_WINDOW_START,
+ window_end=_WINDOW_END,
+ )
+ # `_truncate` returns `s[:limit] + "… [N more chars]"` so the prefix
+ # length is `limit` and the total length is `limit + suffix_len`.
+ assert result["gid-1"]["input"].startswith("x" * 100)
+ assert "more chars]" in result["gid-1"]["input"]
+ assert result["gid-1"]["output"].startswith("x" * 200)
+ assert "more chars]" in result["gid-1"]["output"]
+
+ @patch(_RESOLVE_PATH, return_value={"gid-1": "trace-A"})
+ def test_query_reads_native_heavy_columns_from_ai_events(self, _mock_resolve, team):
+ """The whole point of the migration is that `input` / `output_choices`
+ come off the dedicated `ai_events` columns rather than NULL JSON-extracts
+ on `events.properties`. Lock the SQL shape."""
+ with patch(
+ "posthog.temporal.llm_analytics.evaluation_clustering.data.execute_with_ai_events_fallback"
+ ) as mock_resolver:
+ mock_resolver.return_value = _resolver_response([])
+ fetch_generation_contents(
+ team, generation_ids=["gid-1"], window_start=_WINDOW_START, window_end=_WINDOW_END
+ )
+
+ kwargs = mock_resolver.call_args.kwargs
+ select = cast(ast.SelectQuery, kwargs["query"])
+ from_chain = select.select_from.table.chain # type: ignore[union-attr]
+ # nosemgrep: hogql-no-string-table-chain
+ assert from_chain == ["posthog", "ai_events"]
+ # Settings forwarded so the resolver runs with the 120s clustering
+ # timeout. Lock the actual value so a future "tightening" of the
+ # default doesn't silently break clustering on long traces.
+ from posthog.temporal.llm_analytics.evaluation_clustering.data import CLUSTERING_QUERY_MAX_EXECUTION_TIME
+
+ assert kwargs["settings"] is not None
+ assert kwargs["settings"].max_execution_time == CLUSTERING_QUERY_MAX_EXECUTION_TIME
+ assert kwargs["query_type"] == "GenerationContentsForLabeling"
+
+ @patch(_RESOLVE_PATH, return_value={"gid-1": "trace-A", "gid-2": "trace-B"})
+ def test_trace_ids_flow_into_heavy_query(self, _mock_resolve, team):
+ """The discovered trace_ids must land in the WHERE so the heavy fetch
+ gets the full ai_events sorting-key prefix + cityHash64 sharding-key
+ single-shard pruning."""
+ with patch(
+ "posthog.temporal.llm_analytics.evaluation_clustering.data.execute_with_ai_events_fallback"
+ ) as mock_resolver:
+ mock_resolver.return_value = _resolver_response([])
+ fetch_generation_contents(
+ team, generation_ids=["gid-1", "gid-2"], window_start=_WINDOW_START, window_end=_WINDOW_END
+ )
+
+ placeholders = mock_resolver.call_args.kwargs["placeholders"]
+ assert "trace_ids" in placeholders
+ values = sorted(c.value for c in placeholders["trace_ids"].exprs)
+ assert values == ["trace-A", "trace-B"]
+
+ @patch(_RESOLVE_PATH, return_value={})
+ def test_no_trace_ids_resolved_skips_heavy_fetch(self, _mock_resolve, team):
+ """When the events preflight returns nothing — uuids purged or outside
+ the window — skip the heavy fan-out entirely."""
+ with patch(
+ "posthog.temporal.llm_analytics.evaluation_clustering.data.execute_with_ai_events_fallback"
+ ) as mock_resolver:
+ result = fetch_generation_contents(
+ team, generation_ids=["gid-1"], window_start=_WINDOW_START, window_end=_WINDOW_END
+ )
+ assert result == {}
+ assert mock_resolver.call_count == 0
diff --git a/posthog/temporal/llm_analytics/run_evaluation.py b/posthog/temporal/llm_analytics/run_evaluation.py
index a7944eb39668..30fb995647be 100644
--- a/posthog/temporal/llm_analytics/run_evaluation.py
+++ b/posthog/temporal/llm_analytics/run_evaluation.py
@@ -749,6 +749,22 @@ def extract_event_io(event_type: str, properties: dict[str, Any]) -> tuple[Any,
"""Extract raw input and output values from event properties.
Returns (input_raw, output_raw) for use in Hog eval globals and preview display.
+
+ Invariant: `properties` must already contain the heavy `$ai_*` keys when present
+ on the source event. Heavy props are stripped from `events.properties` after the
+ cutover (see AI events migration brief), so callers must source the event from a
+ path that re-populates them — today that's `EvaluationRunViewSet.create`, which
+ reads from `ai_events` and re-merges heavy columns via `merge_heavy_properties`
+ before handing `event_data` to this workflow. Adding a new caller? Use the same
+ pattern, or feed it `event_data` produced by an already-migrated reader.
+
+ Failure mode this invariant guards against: when `is_ai_events_enabled(team)` is
+ False (kill switch flipped) AND the team is post-strip, the events-fallback path
+ in `EvaluationRunViewSet.create` returns rows whose `properties` JSON has NULL
+ heavy keys. `extract_event_io` would then return empty `input_raw` / `output_raw`,
+ and the LLM judge / Hog eval would silently grade an empty conversation. The
+ invariant exists so any future caller short-circuiting around the migrated
+ reader has to confront this case explicitly.
"""
if event_type == "$ai_generation":
input_raw = properties.get("$ai_input") or properties.get("$ai_input_state", "")
diff --git a/posthog/temporal/llm_analytics/sentiment/constants.py b/posthog/temporal/llm_analytics/sentiment/constants.py
index 0852cc5587d8..50478b916452 100644
--- a/posthog/temporal/llm_analytics/sentiment/constants.py
+++ b/posthog/temporal/llm_analytics/sentiment/constants.py
@@ -40,24 +40,29 @@ BATCH_MAX_GENERATION_IDS = 5 # keep small to avoid upstream request timeouts
# Uses a window function to cap rows per trace at the ClickHouse level,
# and a size filter to skip accumulated conversation histories — the same
# user messages appear in earlier, smaller generations so we lose nothing.
+#
+# Reads from `posthog.ai_events` so post-strip rows still expose the heavy
+# `input` column (it's stripped from `events.properties.$ai_input` after
+# the cutover). `execute_with_ai_events_fallback` rewrites this back to
+# `events.properties.$ai_*` for the shared-table fallback.
GENERATIONS_QUERY = """
SELECT uuid, ai_input, trace_id
FROM (
SELECT
uuid,
- properties.$ai_input AS ai_input,
- properties.$ai_trace_id AS trace_id,
+ input AS ai_input,
+ trace_id,
row_number() OVER (
- PARTITION BY properties.$ai_trace_id
+ PARTITION BY trace_id
ORDER BY timestamp DESC
) AS rn
- FROM events
+ FROM posthog.ai_events AS ai_events
WHERE event = '$ai_generation'
AND timestamp >= toDateTime({date_from}, 'UTC')
AND timestamp <= toDateTime({date_to}, 'UTC')
- AND properties.$ai_trace_id IN {trace_ids}
+ AND trace_id IN {trace_ids}
-- skip huge accumulated conversation histories
- AND length(properties.$ai_input) <= {max_input_chars}
+ AND length(input) <= {max_input_chars}
)
-- last N qualified generations per trace
WHERE rn <= {max_gens_per_trace}
@@ -65,15 +70,17 @@ GENERATIONS_QUERY = """
"""
# Fetch specific generation events by UUID — no window function needed.
-# No length() filter here: it translates to JSONExtractRaw on every scanned
-# row which is expensive on high-volume teams (benchmarked 2.4x slower).
-# The size check is applied post-fetch in Python instead.
+# No length() filter here: on the events fallback it translates to
+# JSONExtractRaw on every scanned row which is expensive on high-volume
+# teams (benchmarked 2.4x slower). The size check is applied post-fetch
+# in Python instead.
GENERATIONS_BY_UUID_QUERY = """
SELECT
uuid,
- properties.$ai_input AS ai_input
- FROM events
+ input AS ai_input
+ FROM posthog.ai_events AS ai_events
WHERE event = '$ai_generation'
+ AND trace_id IN {trace_ids}
AND timestamp >= toDateTime({date_from}, 'UTC')
AND timestamp <= toDateTime({date_to}, 'UTC')
AND uuid IN {uuids}
diff --git a/posthog/temporal/llm_analytics/sentiment/data.py b/posthog/temporal/llm_analytics/sentiment/data.py
index de280cb82af4..d1289c01f662 100644
--- a/posthog/temporal/llm_analytics/sentiment/data.py
+++ b/posthog/temporal/llm_analytics/sentiment/data.py
@@ -38,15 +38,14 @@ def fetch_generations(
from posthog.hogql import ast
from posthog.hogql.constants import LimitContext
from posthog.hogql.parser import parse_select
- from posthog.hogql.query import execute_hogql_query
+ from posthog.hogql_queries.ai.ai_table_resolver import execute_with_ai_events_fallback
from posthog.models.team import Team
team = Team.objects.get(id=team_id)
query = parse_select(GENERATIONS_QUERY)
with tags_context(product=Product.LLM_ANALYTICS, feature=Feature.QUERY, team_id=team_id):
- result = execute_hogql_query(
- query_type="SentimentOnDemand",
+ result = execute_with_ai_events_fallback(
query=query,
placeholders={
"date_from": ast.Constant(value=date_from),
@@ -56,6 +55,7 @@ def fetch_generations(
"max_gens_per_trace": ast.Constant(value=MAX_GENERATIONS_PER_TRACE),
},
team=team,
+ query_type="SentimentOnDemand",
limit_context=LimitContext.QUERY_ASYNC,
)
@@ -86,26 +86,55 @@ def fetch_generations_by_uuid(
Simpler than fetch_generations — no window function, no trace grouping.
Returns a flat list of (uuid, ai_input) tuples.
+
+ Uses a two-query pattern: the `(team_id, trace_id, timestamp)` sorting
+ key + cityHash64 sharding key on `ai_events` mean a `WHERE uuid IN (...)`
+ fan-out reads heavy `input` on every shard. So we first resolve uuid →
+ trace_id off `events` (cheap small-column read using the events sorting
+ key) and pass the resulting trace_ids into the heavy fetch — keeping
+ the heavy read on a single shard.
"""
+ from datetime import UTC, datetime
+
from posthog.hogql import ast
from posthog.hogql.constants import LimitContext
from posthog.hogql.parser import parse_select
- from posthog.hogql.query import execute_hogql_query
+ from posthog.hogql_queries.ai.ai_table_resolver import execute_with_ai_events_fallback
+ from posthog.hogql_queries.ai.trace_id_resolver import resolve_trace_ids_for_generation_uuids
from posthog.models.team import Team
team = Team.objects.get(id=team_id)
+
+ # `date_from` / `date_to` arrive as `%Y-%m-%d %H:%M:%S` strings (per
+ # `resolve_date_bounds`). Parse them to UTC datetimes so the trace-id
+ # resolver can serialize them through HogQL placeholder substitution.
+ ts_start = datetime.strptime(date_from, "%Y-%m-%d %H:%M:%S").replace(tzinfo=UTC)
+ ts_end = datetime.strptime(date_to, "%Y-%m-%d %H:%M:%S").replace(tzinfo=UTC)
+
+ trace_id_by_uuid = resolve_trace_ids_for_generation_uuids(
+ team=team,
+ generation_uuids=generation_ids,
+ ts_start=ts_start,
+ ts_end=ts_end,
+ query_type="SentimentTraceIdResolve",
+ )
+ trace_ids = sorted({tid for tid in trace_id_by_uuid.values() if tid})
+ if not trace_ids:
+ return [], 0
+
query = parse_select(GENERATIONS_BY_UUID_QUERY)
with tags_context(product=Product.LLM_ANALYTICS, feature=Feature.QUERY, team_id=team_id):
- result = execute_hogql_query(
- query_type="SentimentOnDemandGeneration",
+ result = execute_with_ai_events_fallback(
query=query,
placeholders={
"date_from": ast.Constant(value=date_from),
"date_to": ast.Constant(value=date_to),
"uuids": ast.Tuple(exprs=[ast.Constant(value=uid) for uid in generation_ids]),
+ "trace_ids": ast.Tuple(exprs=[ast.Constant(value=tid) for tid in trace_ids]),
},
team=team,
+ query_type="SentimentOnDemandGeneration",
limit_context=LimitContext.QUERY_ASYNC,
)
diff --git a/posthog/temporal/llm_analytics/sentiment/tests/test_classify.py b/posthog/temporal/llm_analytics/sentiment/tests/test_classify.py
index bcdc29432a3d..2dbec459842a 100644
--- a/posthog/temporal/llm_analytics/sentiment/tests/test_classify.py
+++ b/posthog/temporal/llm_analytics/sentiment/tests/test_classify.py
@@ -25,10 +25,17 @@ def _single_input(trace_id: str = "trace-1", **kwargs) -> ClassifySentimentInput
return ClassifySentimentInput(team_id=1, ids=[trace_id], **kwargs)
-_PATCH_HOGQL = "posthog.hogql.query.execute_hogql_query"
+# `ai_table_resolver` imports `execute_hogql_query` at module top, so patching
+# the source module wouldn't reach its local binding. Patch where it's used.
+_PATCH_HOGQL = "posthog.hogql_queries.ai.ai_table_resolver.execute_hogql_query"
_PATCH_TEAM = "posthog.models.team.Team.objects"
_PATCH_CLASSIFY = "posthog.temporal.llm_analytics.sentiment.model.classify"
_PATCH_CAP = "posthog.temporal.llm_analytics.sentiment.constants.MAX_CLASSIFICATIONS_PER_TRACE"
+# `fetch_generations_by_uuid` does a uuid → trace_id preflight via the
+# resolver helper before the heavy fetch. Patch the source-module symbol
+# (the resolver does `from posthog.hogql.query import execute_hogql_query`
+# inside its body, so patching at the source propagates).
+_PATCH_RESOLVE = "posthog.hogql_queries.ai.trace_id_resolver.resolve_trace_ids_for_generation_uuids"
@pytest.fixture(autouse=True)
@@ -38,6 +45,15 @@ def _mock_team():
yield
[email protected](autouse=True)
+def _mock_trace_id_resolver():
+ """Resolver returns a synthetic trace_id per input uuid so the heavy fetch
+ isn't short-circuited as 'no generations found in window'."""
+ with patch(_PATCH_RESOLVE) as mock:
+ mock.side_effect = lambda team, generation_uuids, **kw: {u: f"trace-{u}" for u in generation_uuids}
+ yield
+
+
class TestClassifySentimentSingleTrace:
@pytest.mark.asyncio
@patch(_PATCH_HOGQL)
diff --git a/posthog/temporal/llm_analytics/sentiment/tests/test_data.py b/posthog/temporal/llm_analytics/sentiment/tests/test_data.py
new file mode 100644
index 000000000000..2bb5a351b3cf
--- /dev/null
+++ b/posthog/temporal/llm_analytics/sentiment/tests/test_data.py
@@ -0,0 +1,171 @@
+"""Strip-migration unit tests for sentiment Temporal data layer.
+
+`fetch_generations` and `fetch_generations_by_uuid` both moved from
+`FROM events SELECT properties.$ai_input` to `FROM posthog.ai_events SELECT input`
+behind the resolver. Both must continue to read populated `ai_input` for
+post-strip events (the resolver wires that up); these tests assert the contract
+without hitting ClickHouse.
+"""
+
+from typing import cast
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from posthog.hogql import ast
+
+from posthog.temporal.llm_analytics.sentiment.data import fetch_generations, fetch_generations_by_uuid
+
+
+def team(db):
+ from posthog.models.organization import Organization
+ from posthog.models.team import Team
+
+ organization = Organization.objects.create(name="Test Org")
+ return Team.objects.create(organization=organization, name="Test Team")
+
+
+def _resolver_response(rows: list[list]) -> MagicMock:
+ response = MagicMock()
+ response.results = rows
+ return response
+
+
+class TestFetchGenerations:
+ def test_groups_rows_by_trace_id(self, team):
+ # Each row tuple: (uuid, ai_input, trace_id) — order matches GENERATIONS_QUERY's outer SELECT.
+ with patch("posthog.hogql_queries.ai.ai_table_resolver.execute_with_ai_events_fallback") as mock_resolver:
+ mock_resolver.return_value = _resolver_response(
+ [
+ ["uuid-1", '[{"role":"user","content":"hi A"}]', "trace-A"],
+ ["uuid-2", '[{"role":"user","content":"hi B"}]', "trace-B"],
+ ["uuid-3", '[{"role":"user","content":"hi A again"}]', "trace-A"],
+ ]
+ )
+
+ result = fetch_generations(
+ team_id=team.id,
+ trace_ids=["trace-A", "trace-B"],
+ date_from="2026-04-27 07:00:00",
+ date_to="2026-04-27 08:00:00",
+ )
+
+ assert set(result.rows_by_trace.keys()) == {"trace-A", "trace-B"}
+ assert len(result.rows_by_trace["trace-A"]) == 2
+ assert len(result.rows_by_trace["trace-B"]) == 1
+ # Bytes accumulator counts the raw JSON strings sent over the wire.
+ assert result.total_input_bytes > 0
+
+ def test_skips_rows_with_unparseable_input(self, team):
+ with patch("posthog.hogql_queries.ai.ai_table_resolver.execute_with_ai_events_fallback") as mock_resolver:
+ mock_resolver.return_value = _resolver_response(
+ [
+ ["uuid-1", "{not-json", "trace-A"],
+ ["uuid-2", '[{"role":"user","content":"valid"}]', "trace-A"],
+ ]
+ )
+ result = fetch_generations(
+ team_id=team.id,
+ trace_ids=["trace-A"],
+ date_from="2026-04-27 07:00:00",
+ date_to="2026-04-27 08:00:00",
+ )
+ # Only the valid row survives; invalid JSON drops silently.
+ assert len(result.rows_by_trace["trace-A"]) == 1
+
+ def test_query_reads_native_input_from_ai_events(self, team):
+ """If someone reverts the GENERATIONS_QUERY template to
+ `properties.$ai_input`, this test catches it."""
+ with patch("posthog.hogql_queries.ai.ai_table_resolver.execute_with_ai_events_fallback") as mock_resolver:
+ mock_resolver.return_value = _resolver_response([])
+ fetch_generations(
+ team_id=team.id,
+ trace_ids=["trace-A"],
+ date_from="2026-04-27 07:00:00",
+ date_to="2026-04-27 08:00:00",
+ )
+
+ kwargs = mock_resolver.call_args.kwargs
+ outer = cast(ast.SelectQuery, kwargs["query"])
+ inner = outer.select_from.table # type: ignore[union-attr]
+ assert 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"]
+
+
+_TRACE_RESOLVE_PATH = "posthog.hogql_queries.ai.trace_id_resolver.resolve_trace_ids_for_generation_uuids"
+
+
+class TestFetchGenerationsByUuid:
+ @patch(_TRACE_RESOLVE_PATH, return_value={"uuid-1": "trace-A", "uuid-2": "trace-B"})
+ def test_returns_flat_list(self, _mock_resolve, team):
+ with patch("posthog.hogql_queries.ai.ai_table_resolver.execute_with_ai_events_fallback") as mock_resolver:
+ mock_resolver.return_value = _resolver_response(
+ [
+ ["uuid-1", '[{"role":"user","content":"hi"}]'],
+ ["uuid-2", '[{"role":"user","content":"there"}]'],
+ ]
+ )
+ rows, total_bytes = fetch_generations_by_uuid(
+ team_id=team.id,
+ generation_ids=["uuid-1", "uuid-2"],
+ date_from="2026-04-27 07:00:00",
+ date_to="2026-04-27 08:00:00",
+ )
+ assert len(rows) == 2
+ assert total_bytes > 0
+
+ @patch(_TRACE_RESOLVE_PATH, return_value={"uuid-good": "trace-A", "uuid-bad": "trace-A"})
+ def test_skips_unparseable_input(self, _mock_resolve, team):
+ with patch("posthog.hogql_queries.ai.ai_table_resolver.execute_with_ai_events_fallback") as mock_resolver:
+ mock_resolver.return_value = _resolver_response(
+ [
+ ["uuid-bad", "not-json"],
+ ["uuid-good", '[{"role":"user","content":"hi"}]'],
+ ]
+ )
+ rows, _ = fetch_generations_by_uuid(
+ team_id=team.id,
+ generation_ids=["uuid-bad", "uuid-good"],
+ date_from="2026-04-27 07:00:00",
+ date_to="2026-04-27 08:00:00",
+ )
+ assert len(rows) == 1
+ assert rows[0][0] == "uuid-good"
+
+ @patch(_TRACE_RESOLVE_PATH, return_value={})
+ def test_no_trace_ids_resolved_skips_heavy_fetch(self, _mock_resolve, team):
+ """When the events preflight returns no trace_ids — uuids purged or
+ outside the window — skip the heavy ai_events fan-out entirely."""
+ with patch("posthog.hogql_queries.ai.ai_table_resolver.execute_with_ai_events_fallback") as mock_resolver:
+ rows, total_bytes = fetch_generations_by_uuid(
+ team_id=team.id,
+ generation_ids=["uuid-1", "uuid-2"],
+ date_from="2026-04-27 07:00:00",
+ date_to="2026-04-27 08:00:00",
+ )
+ assert rows == []
+ assert total_bytes == 0
+ assert mock_resolver.call_count == 0
+
+ @patch(_TRACE_RESOLVE_PATH, return_value={"uuid-1": "trace-A", "uuid-2": "trace-B"})
+ def test_trace_ids_flow_into_heavy_query(self, _mock_resolve, team):
+ """The discovered trace_ids must land in the WHERE so the heavy fetch
+ hits the ai_events `(team_id, trace_id, timestamp)` sorting-key
+ prefix and single-shard via the cityHash64 sharding key."""
+ with patch("posthog.hogql_queries.ai.ai_table_resolver.execute_with_ai_events_fallback") as mock_resolver:
+ mock_resolver.return_value = _resolver_response([])
+ fetch_generations_by_uuid(
+ team_id=team.id,
+ generation_ids=["uuid-1", "uuid-2"],
+ date_from="2026-04-27 07:00:00",
+ date_to="2026-04-27 08:00:00",
+ )
+ placeholders = mock_resolver.call_args.kwargs["placeholders"]
+ assert "trace_ids" in placeholders
+ values = sorted(c.value for c in placeholders["trace_ids"].exprs)
+ assert values == ["trace-A", "trace-B"]
diff --git a/posthog/temporal/llm_analytics/sentiment/tests/test_generation_activity.py b/posthog/temporal/llm_analytics/sentiment/tests/test_generation_activity.py
index de17ea7c293b..a483b141146b 100644
--- a/posthog/temporal/llm_analytics/sentiment/tests/test_generation_activity.py
+++ b/posthog/temporal/llm_analytics/sentiment/tests/test_generation_activity.py
@@ -25,9 +25,16 @@ def _gen_input(generation_id: str = "gen-1", **kwargs) -> ClassifySentimentInput
return ClassifySentimentInput(team_id=1, ids=[generation_id], analysis_level="generation", **kwargs)
-_PATCH_HOGQL = "posthog.hogql.query.execute_hogql_query"
+# `ai_table_resolver` imports `execute_hogql_query` at module top, so patching
+# the source module wouldn't reach its local binding. Patch where it's used.
+_PATCH_HOGQL = "posthog.hogql_queries.ai.ai_table_resolver.execute_hogql_query"
_PATCH_TEAM = "posthog.models.team.Team.objects"
_PATCH_CLASSIFY = "posthog.temporal.llm_analytics.sentiment.model.classify"
+# `fetch_generations_by_uuid` does a uuid → trace_id preflight via the
+# resolver helper before the heavy fetch. Patch the source-module symbol so
+# the inline `from posthog.hogql.query import execute_hogql_query` inside
+# the resolver picks up the mock.
+_PATCH_RESOLVE = "posthog.hogql_queries.ai.trace_id_resolver.resolve_trace_ids_for_generation_uuids"
@pytest.fixture(autouse=True)
@@ -37,6 +44,15 @@ def _mock_team():
yield
[email protected](autouse=True)
+def _mock_trace_id_resolver():
+ """Resolver returns a synthetic trace_id per input uuid so the heavy fetch
+ isn't short-circuited as 'no generations found in window'."""
+ with patch(_PATCH_RESOLVE) as mock:
+ mock.side_effect = lambda team, generation_uuids, **kw: {u: f"trace-{u}" for u in generation_uuids}
+ yield
+
+
class TestGenerationLevelSingle:
@pytest.mark.asyncio
@patch(_PATCH_HOGQL)
diff --git a/posthog/temporal/llm_analytics/trace_summarization/constants.py b/posthog/temporal/llm_analytics/trace_summarization/constants.py
index de5e70beefc3..b6fc761574d2 100644
--- a/posthog/temporal/llm_analytics/trace_summarization/constants.py
+++ b/posthog/temporal/llm_analytics/trace_summarization/constants.py
@@ -43,20 +43,6 @@ MAX_TRACE_EVENTS_LIMIT = 50
# workers for minutes.
MAX_TRACE_PROPERTIES_SIZE = 2_000_000
-# AI event types used in trace queries (sampling and fetching)
-AI_EVENT_TYPES = (
- "$ai_span",
- "$ai_generation",
- "$ai_embedding",
- "$ai_metric",
- "$ai_feedback",
- "$ai_trace",
-)
-
-# Expand the time window by this amount each side when fetching traces,
-# so traces that started just before/after the window are still found.
-TRACE_CAPTURE_RANGE = timedelta(minutes=10)
-
# Schedule configuration
SCHEDULE_INTERVAL_HOURS = 1 # How often the coordinator runs
diff --git a/posthog/temporal/llm_analytics/trace_summarization/fetch_and_format.py b/posthog/temporal/llm_analytics/trace_summarization/fetch_and_format.py
index 5eb2f072bf56..bafdbeabbd07 100644
--- a/posthog/temporal/llm_analytics/trace_summarization/fetch_and_format.py
+++ b/posthog/temporal/llm_analytics/trace_summarization/fetch_and_format.py
@@ -7,9 +7,9 @@ import temporalio
from posthog.hogql import ast
from posthog.hogql.parser import parse_select
-from posthog.hogql.query import execute_hogql_query
from posthog.clickhouse.query_tagging import Feature, Product, tags_context
+from posthog.hogql_queries.ai.ai_table_resolver import execute_with_ai_events_fallback
from posthog.models.team import Team
from posthog.redis import get_async_client
from posthog.sync import database_sync_to_async
@@ -79,29 +79,45 @@ def _fetch_and_format_trace(
def _fetch_and_format_generation(
- generation_id: str, team_id: int, window_start: str, window_end: str, max_length: int | None = None
+ generation_id: str,
+ trace_id: str,
+ team_id: int,
+ window_start: str,
+ window_end: str,
+ max_length: int | None = None,
) -> FetchResult | None:
"""Fetch generation event data and format text representation.
Returns FetchResult or None if not found.
+
+ `trace_id` is required and used as a WHERE filter — it's the first variable
+ segment of the `ai_events` sorting key (`team_id, trace_id, timestamp`) and
+ of the sharding key, so adding it prunes the query to a single shard plus a
+ range scan instead of a fan-out across all shards. The caller
+ (`fetch_and_format_activity`) always has it set on `FetchAndFormatInput`.
"""
team = Team.objects.get(id=team_id)
start_dt_str = format_datetime_for_clickhouse(window_start)
end_dt_str = format_datetime_for_clickhouse(window_end)
+ # Query the dedicated table first; the resolver rewrites + re-runs against the
+ # shared `events` table when ai_events returns zero rows. Heavy columns (`input`,
+ # `output`) live as native columns on ai_events and as stripped JSON on events
+ # post-cutover — only the migrated path can recover them for recent rows.
query = parse_select(
"""
SELECT
- properties.$ai_model as model,
- properties.$ai_provider as provider,
- properties.$ai_input as input,
- properties.$ai_output as output,
- properties.$ai_input_tokens as input_tokens,
- properties.$ai_output_tokens as output_tokens,
- properties.$ai_latency as latency
- FROM events
+ model,
+ provider,
+ input,
+ output,
+ input_tokens,
+ output_tokens,
+ latency
+ FROM posthog.ai_events AS ai_events
WHERE event = '$ai_generation'
+ AND trace_id = {trace_id}
AND timestamp >= toDateTime({start_dt}, 'UTC')
AND timestamp < toDateTime({end_dt}, 'UTC')
AND uuid = {generation_id}
@@ -110,15 +126,16 @@ def _fetch_and_format_generation(
)
with tags_context(product=Product.LLM_ANALYTICS, feature=Feature.QUERY, team_id=team.id):
- result = execute_hogql_query(
- query_type="GenerationForSummarization",
+ result = execute_with_ai_events_fallback(
query=query,
placeholders={
"start_dt": ast.Constant(value=start_dt_str),
"end_dt": ast.Constant(value=end_dt_str),
"generation_id": ast.Constant(value=generation_id),
+ "trace_id": ast.Constant(value=trace_id),
},
team=team,
+ query_type="GenerationForSummarization",
)
if not result.results:
@@ -209,7 +226,12 @@ async def fetch_and_format_activity(input: FetchAndFormatInput) -> FetchAndForma
if input.generation_id:
result = await database_sync_to_async(_fetch_and_format_generation, thread_sensitive=False)(
- input.generation_id, input.team_id, input.window_start, input.window_end, input.max_length
+ input.generation_id,
+ input.trace_id,
+ input.team_id,
+ input.window_start,
+ input.window_end,
+ input.max_length,
)
else:
result = await database_sync_to_async(_fetch_and_format_trace, thread_sensitive=False)(
diff --git a/posthog/temporal/llm_analytics/trace_summarization/queries.py b/posthog/temporal/llm_analytics/trace_summarization/queries.py
index 3c699553f8cb..23ee89efd99e 100644
--- a/posthog/temporal/llm_analytics/trace_summarization/queries.py
+++ b/posthog/temporal/llm_analytics/trace_summarization/queries.py
@@ -1,109 +1,37 @@
"""ClickHouse queries for trace summarization.
-Simple, direct queries that avoid expensive JOINs (e.g. person table)
-which can OOM ClickHouse for teams with large AI traces.
+Routes through `TraceQueryRunner` so reads land on the dedicated `ai_events`
+table when the rollout flag is on (and fall back to the shared `events` table
+otherwise). The runner re-merges the stripped heavy columns into
+`event.properties`, so downstream formatters keep working post-strip.
"""
-from datetime import UTC, datetime
-from typing import Any
-
-import orjson
-
-from posthog.schema import LLMTrace, LLMTraceEvent, LLMTracePerson
-
-from posthog.hogql import ast
-from posthog.hogql.constants import LimitContext
-from posthog.hogql.parser import parse_select
-from posthog.hogql.query import execute_hogql_query
+from posthog.schema import DateRange, LLMTrace, NodeKind, TraceQuery
from posthog.clickhouse.query_tagging import Feature, Product, tags_context
+from posthog.hogql_queries.ai.trace_query_runner import TraceQueryRunner
from posthog.models.team import Team
-from posthog.temporal.llm_analytics.trace_summarization.constants import AI_EVENT_TYPES, TRACE_CAPTURE_RANGE
-
-_TRACE_EVENTS_QUERY = """
- SELECT uuid, event, timestamp, properties
- FROM events
- WHERE event IN {event_types}
- AND timestamp >= toDateTime({start_ts}, 'UTC')
- AND timestamp < toDateTime({end_ts}, 'UTC')
- AND properties.$ai_trace_id = {trace_id}
- ORDER BY timestamp
-"""
def fetch_trace(team: Team, trace_id: str, window_start: str, window_end: str) -> LLMTrace | None:
- """Fetch trace events with a simple query — no person JOIN, no aggregations.
+ """Fetch a single trace by ID via the migrated `TraceQueryRunner`.
- Returns an LLMTrace or None if no events found. The $ai_trace meta-event
- is used to populate trace-level fields (traceName, inputState, outputState)
- but is excluded from the events list (matching TraceQueryRunner behavior).
- """
- start_dt = datetime.fromisoformat(window_start).astimezone(UTC) - TRACE_CAPTURE_RANGE
- end_dt = datetime.fromisoformat(window_end).astimezone(UTC) + TRACE_CAPTURE_RANGE
+ The runner's `TraceQueryDateRange` widens the input window by ±10 minutes
+ internally, so callers should pass the raw window — no pre-widening here.
- query = parse_select(_TRACE_EVENTS_QUERY)
+ Returns the LLMTrace produced by the runner (with heavy columns re-merged
+ into `event.properties`), or None if no events were found in the window.
+ """
+ trace_query = TraceQuery(
+ kind=NodeKind.TRACE_QUERY,
+ traceId=trace_id,
+ dateRange=DateRange(date_from=window_start, date_to=window_end),
+ )
with tags_context(product=Product.LLM_ANALYTICS, feature=Feature.QUERY, team_id=team.id):
- result = execute_hogql_query(
- query_type="SummarizationTraceFetch",
- query=query,
- placeholders={
- "event_types": ast.Tuple(exprs=[ast.Constant(value=e) for e in AI_EVENT_TYPES]),
- "start_ts": ast.Constant(value=start_dt.strftime("%Y-%m-%d %H:%M:%S")),
- "end_ts": ast.Constant(value=end_dt.strftime("%Y-%m-%d %H:%M:%S")),
- "trace_id": ast.Constant(value=trace_id),
- },
- team=team,
- limit_context=LimitContext.QUERY_ASYNC,
- )
+ runner = TraceQueryRunner(team=team, query=trace_query)
+ response = runner.calculate()
- if not result.results:
+ if not response.results:
return None
- events: list[LLMTraceEvent] = []
- trace_name: str | None = None
- input_state: Any = None
- output_state: Any = None
- first_timestamp: str | None = None
-
- for row in result.results:
- event_uuid, event_name, event_timestamp, event_properties = row
- if first_timestamp is None:
- first_timestamp = event_timestamp.isoformat()
-
- props = orjson.loads(event_properties) if isinstance(event_properties, str) else event_properties
-
- if event_name == "$ai_trace":
- # Extract trace-level metadata; exclude from events list
- trace_name = props.get("$ai_span_name") or props.get("$ai_trace_name")
- try:
- input_state = orjson.loads(props["$ai_input_state"]) if props.get("$ai_input_state") else None
- except (orjson.JSONDecodeError, TypeError):
- input_state = None
- try:
- output_state = orjson.loads(props["$ai_output_state"]) if props.get("$ai_output_state") else None
- except (orjson.JSONDecodeError, TypeError):
- output_state = None
- continue
-
- events.append(
- LLMTraceEvent(
- id=str(event_uuid),
- event=event_name,
- createdAt=event_timestamp.isoformat(),
- properties=props,
- )
- )
-
- if not events:
- return None
-
- return LLMTrace(
- id=trace_id,
- createdAt=first_timestamp or events[0].createdAt,
- distinctId="",
- traceName=trace_name,
- inputState=input_state,
- outputState=output_state,
- events=events,
- person=LLMTracePerson(uuid="", distinct_id="", created_at=first_timestamp or "", properties={}),
- )
+ return response.results[0]
diff --git a/posthog/temporal/llm_analytics/trace_summarization/tests/test_fetch_and_format.py b/posthog/temporal/llm_analytics/trace_summarization/tests/test_fetch_and_format.py
index af52935c074e..40ea652cc428 100644
--- a/posthog/temporal/llm_analytics/trace_summarization/tests/test_fetch_and_format.py
+++ b/posthog/temporal/llm_analytics/trace_summarization/tests/test_fetch_and_format.py
@@ -106,7 +106,7 @@ class TestFetchAndFormatActivity:
@pytest.mark.asyncio
async def test_generation_not_found_returns_skipped(self, mock_team):
with patch(
- "posthog.temporal.llm_analytics.trace_summarization.fetch_and_format.execute_hogql_query"
+ "posthog.temporal.llm_analytics.trace_summarization.fetch_and_format.execute_with_ai_events_fallback"
) as mock_query:
mock_query.return_value.results = []
@@ -179,7 +179,7 @@ class TestFetchAndFormatActivity:
with (
patch(
- "posthog.temporal.llm_analytics.trace_summarization.fetch_and_format.execute_hogql_query"
+ "posthog.temporal.llm_analytics.trace_summarization.fetch_and_format.execute_with_ai_events_fallback"
) as mock_query,
patch("posthog.temporal.llm_analytics.trace_summarization.fetch_and_format.get_async_client"),
patch("posthog.temporal.llm_analytics.trace_summarization.fetch_and_format.store_text_repr") as mock_store,
diff --git a/posthog/temporal/llm_analytics/trace_summarization/tests/test_queries.py b/posthog/temporal/llm_analytics/trace_summarization/tests/test_queries.py
new file mode 100644
index 000000000000..fd7008ba78ac
--- /dev/null
+++ b/posthog/temporal/llm_analytics/trace_summarization/tests/test_queries.py
@@ -0,0 +1,88 @@
+"""Tests for the migrated `fetch_trace` in the trace-summarization Temporal pipeline.
+
+Covers the strip-migration contract: heavy columns must come back populated on
+the dedicated path (post-strip rows are only readable there) and the function
+must hand back a fully-formed LLMTrace, not raise.
+"""
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from posthog.schema import LLMTrace, TraceQueryResponse
+
+from posthog.temporal.llm_analytics.trace_summarization.queries import fetch_trace
+
+
+def team(db):
+ from posthog.models.organization import Organization
+ from posthog.models.team import Team
+
+ organization = Organization.objects.create(name="Test Org")
+ return Team.objects.create(organization=organization, name="Test Team")
+
+
+def _make_trace(trace_id: str, events: list | None = None) -> LLMTrace:
+ return LLMTrace(
+ id=trace_id,
+ createdAt="2026-04-27T07:00:00+00:00",
+ distinctId="d1",
+ events=events or [],
+ )
+
+
+class TestFetchTrace:
+ def test_returns_llmtrace_when_runner_has_results(self, team):
+ trace = _make_trace("trace-abc")
+ with patch("posthog.temporal.llm_analytics.trace_summarization.queries.TraceQueryRunner") as mock_runner_cls:
+ mock_runner = MagicMock()
+ mock_runner.calculate.return_value = TraceQueryResponse(results=[trace])
+ mock_runner_cls.return_value = mock_runner
+
+ result = fetch_trace(team, "trace-abc", "2026-04-27T07:00:00+00:00", "2026-04-27T08:00:00+00:00")
+
+ assert result is not None
+ assert result.id == "trace-abc"
+ # Runner was instantiated with the team and a TraceQuery scoped to that trace.
+ args, kwargs = mock_runner_cls.call_args
+ assert kwargs["team"] is team
+ assert kwargs["query"].traceId == "trace-abc"
+ # Date range is forwarded raw — TraceQueryDateRange handles ±10min widening.
+ assert kwargs["query"].dateRange.date_from == "2026-04-27T07:00:00+00:00"
+ assert kwargs["query"].dateRange.date_to == "2026-04-27T08:00:00+00:00"
+
+ def test_returns_none_when_runner_has_no_results(self, team):
+ with patch("posthog.temporal.llm_analytics.trace_summarization.queries.TraceQueryRunner") as mock_runner_cls:
+ mock_runner = MagicMock()
+ mock_runner.calculate.return_value = TraceQueryResponse(results=[])
+ mock_runner_cls.return_value = mock_runner
+
+ result = fetch_trace(team, "missing-trace", "2026-04-27T07:00:00+00:00", "2026-04-27T08:00:00+00:00")
+ assert result is None
+
+ def test_runner_handles_post_strip_heavy_columns(self, team):
+ """Smoke-checks the contract that the runner's response surfaces heavy
+ props on the events under `properties.$ai_input`. Real merge logic is
+ tested in `test_trace_query_runner.py`; here we just assert this
+ function returns whatever the runner produces unchanged."""
+ from posthog.schema import LLMTraceEvent
+
+ event_with_heavy = LLMTraceEvent(
+ id="evt-1",
+ event="$ai_generation",
+ createdAt="2026-04-27T07:00:00+00:00",
+ properties={"$ai_input": [{"role": "user", "content": "hi"}]},
+ )
+ trace = _make_trace("trace-1", events=[event_with_heavy])
+
+ with patch("posthog.temporal.llm_analytics.trace_summarization.queries.TraceQueryRunner") as mock_runner_cls:
+ mock_runner = MagicMock()
+ mock_runner.calculate.return_value = TraceQueryResponse(results=[trace])
+ mock_runner_cls.return_value = mock_runner
+
+ result = fetch_trace(team, "trace-1", "2026-04-27T07:00:00+00:00", "2026-04-27T08:00:00+00:00")
+
+ assert result is not None
+ assert len(result.events) == 1
+ assert result.events[0].properties["$ai_input"] == [{"role": "user", "content": "hi"}]
diff --git a/posthog/temporal/llm_analytics/trace_summarization/tests/test_strip_migration.py b/posthog/temporal/llm_analytics/trace_summarization/tests/test_strip_migration.py
new file mode 100644
index 000000000000..b49f6aa9a8d0
--- /dev/null
+++ b/posthog/temporal/llm_analytics/trace_summarization/tests/test_strip_migration.py
@@ -0,0 +1,125 @@
+"""Strip-migration unit tests for the `_fetch_and_format_generation` query.
+
+Verifies the by-uuid generation lookup routes through
+`execute_with_ai_events_fallback` and reads the heavy `input` / `output` from
+`posthog.ai_events` native columns.
+"""
+
+from typing import cast
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from posthog.hogql import ast
+
+from posthog.temporal.llm_analytics.trace_summarization.fetch_and_format import _fetch_and_format_generation
+
+
+def team(db):
+ from posthog.models.organization import Organization
+ from posthog.models.team import Team
+
+ organization = Organization.objects.create(name="Test Org")
+ return Team.objects.create(organization=organization, name="Test Team")
+
+
+def _resolver_response(rows: list[list]) -> MagicMock:
+ response = MagicMock()
+ response.results = rows
+ return response
+
+
+class TestFetchAndFormatGenerationStripMigration:
+ def test_returns_none_when_resolver_has_no_results(self, team):
+ with patch(
+ "posthog.temporal.llm_analytics.trace_summarization.fetch_and_format.execute_with_ai_events_fallback"
+ ) as mock_resolver:
+ mock_resolver.return_value = _resolver_response([])
+ result = _fetch_and_format_generation(
+ "gen-uuid",
+ "trace-uuid",
+ team.id,
+ "2026-04-27T07:00:00+00:00",
+ "2026-04-27T08:00:00+00:00",
+ )
+ assert result is None
+
+ def test_returns_text_repr_with_heavy_input_output(self, team):
+ with patch(
+ "posthog.temporal.llm_analytics.trace_summarization.fetch_and_format.execute_with_ai_events_fallback"
+ ) as mock_resolver:
+ # Order matches SELECT: model, provider, input, output, input_tokens, output_tokens, latency
+ mock_resolver.return_value = _resolver_response(
+ [
+ [
+ "gpt-4o",
+ "openai",
+ [{"role": "user", "content": "Hello"}],
+ [{"role": "assistant", "content": "Hi"}],
+ 10,
+ 5,
+ 0.4,
+ ]
+ ]
+ )
+
+ result = _fetch_and_format_generation(
+ "gen-uuid",
+ "trace-uuid",
+ team.id,
+ "2026-04-27T07:00:00+00:00",
+ "2026-04-27T08:00:00+00:00",
+ )
+
+ assert result is not None
+ assert result.event_count == 1
+ text = result.text_repr or ""
+ assert "Model: gpt-4o" in text
+ assert "Provider: openai" in text
+ assert "Hello" in text
+ assert "Hi" in text
+
+ def test_query_targets_ai_events_with_native_heavy_columns(self, team):
+ """If the projection regresses to `properties.$ai_input` / `FROM events`,
+ post-strip generation summaries silently empty out. Lock both."""
+ with patch(
+ "posthog.temporal.llm_analytics.trace_summarization.fetch_and_format.execute_with_ai_events_fallback"
+ ) as mock_resolver:
+ mock_resolver.return_value = _resolver_response([])
+
+ _fetch_and_format_generation(
+ "gen-uuid",
+ "trace-uuid",
+ team.id,
+ "2026-04-27T07:00:00+00:00",
+ "2026-04-27T08:00:00+00:00",
+ )
+
+ assert mock_resolver.call_count == 1
+ kwargs = mock_resolver.call_args.kwargs
+ select = cast(ast.SelectQuery, kwargs["query"])
+ from_chain = select.select_from.table.chain # type: ignore[union-attr]
+ # nosemgrep: hogql-no-string-table-chain
+ assert from_chain == ["posthog", "ai_events"]
+ # Heavy columns referenced as bare native names, not via properties.$ai_*.
+ select_aliases = [alias.alias for alias in select.select if isinstance(alias, ast.Alias)]
+
+ # Heavy input/output should be projected as native columns aliased to
+ # `input` / `output` (the `as` lines in the SQL preserve the field names).
+ def _field_chain_tail_is_model(s: ast.Expr) -> bool:
+ if not isinstance(s, ast.Field) or not s.chain:
+ return False
+ tail = s.chain[-1]
+ return isinstance(tail, str) and "model" in tail
+
+ assert "model" in select_aliases or any(_field_chain_tail_is_model(s) for s in select.select)
+ # query_type is set so observability dashboards can group by it.
+ assert kwargs["query_type"] == "GenerationForSummarization"
+ # trace_id flows into the WHERE so the lookup hits the
+ # `(team_id, trace_id, timestamp)` sorting-key prefix instead of
+ # fanning out across every shard for the team.
+ placeholders = kwargs["placeholders"]
+ assert "trace_id" in placeholders
+ assert placeholders["trace_id"].value == "trace-uuid"
diff --git a/products/llm_analytics/backend/api/sentiment.py b/products/llm_analytics/backend/api/sentiment.py
index 5755853f33f5..992cc0122882 100644
--- a/products/llm_analytics/backend/api/sentiment.py
+++ b/products/llm_analytics/backend/api/sentiment.py
@@ -15,13 +15,23 @@ from django.core.cache import cache
import structlog
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import extend_schema
+from pydantic import ValidationError as PydanticValidationError
from rest_framework import serializers, status, viewsets
+from rest_framework.decorators import action
from rest_framework.request import Request
from rest_framework.response import Response
from temporalio.common import RetryPolicy, WorkflowIDReusePolicy
+from posthog.schema import HogQLFilters
+
+from posthog.hogql.constants import LimitContext
+from posthog.hogql.filters import replace_filters
+from posthog.hogql.parser import parse_select
+
from posthog.api.monitoring import monitor
from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.clickhouse.query_tagging import Feature, Product, tags_context
+from posthog.hogql_queries.ai.ai_table_resolver import execute_with_ai_events_fallback
from posthog.permissions import AccessControlPermission
from posthog.rate_limit import LLMAnalyticsSentimentBurstThrottle, LLMAnalyticsSentimentSustainedThrottle
from posthog.temporal.common.client import sync_connect
@@ -37,6 +47,12 @@ from posthog.temporal.llm_analytics.sentiment.schema import ClassifySentimentInp
from products.llm_analytics.backend.api.metrics import llma_track_latency
+# Maximum rows returned from sentiment_generations.sql per call. Matches the
+# frontend's GENERATIONS_PAGE_SIZE so a single page request gets the full slice
+# in one round-trip. Baked into `_SENTIMENT_GENERATIONS_SQL` at import time
+# below so this is the single source of truth.
+GENERATIONS_QUERY_LIMIT = 200
+
logger = structlog.get_logger(__name__)
ANALYSIS_LEVEL_CHOICES = ["trace", "generation"]
@@ -52,7 +68,7 @@ class SentimentRequestSerializer(serializers.Serializer):
min_length=1,
max_length=BATCH_MAX_GENERATION_IDS,
required=True,
- help_text="Trace IDs or generation IDs to classify, depending on analysis_level.",
+ help_text="Trace IDs (analysis_level=trace) or generation event UUIDs (analysis_level=generation).",
)
analysis_level = serializers.ChoiceField(
choices=ANALYSIS_LEVEL_CHOICES,
@@ -97,6 +113,67 @@ 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"""
+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}}
+)
+GROUP BY trace_id
+ORDER BY timestamp DESC, trace_id DESC
+LIMIT {GENERATIONS_QUERY_LIMIT}
+"""
+
+
+class SentimentGenerationsRequestSerializer(serializers.Serializer):
+ """Filter shape mirrors the previous frontend `api.query({filters: ...})` payload.
+
+ `filters` accepts the same `HogQLFilters` schema that the legacy frontend HogQL
+ path used (dateRange, filterTestAccounts, properties), so the migration is
+ behaviour-preserving for callers that pass a request unchanged.
+ """
+
+ filters = serializers.JSONField(required=False, default=dict)
+
+
+class SentimentGenerationsRowSerializer(serializers.Serializer):
+ uuid = serializers.CharField(allow_null=True)
+ trace_id = serializers.CharField(allow_null=True)
+ ai_input = serializers.JSONField(allow_null=True)
+ model = serializers.CharField(allow_null=True)
+ distinct_id = serializers.CharField(allow_null=True)
+ timestamp = serializers.CharField(allow_null=True)
+ created_at = serializers.CharField(allow_null=True)
+
+
+class SentimentGenerationsResponseSerializer(serializers.Serializer):
+ # Shape kept tuple-style to match the existing frontend transformer (see
+ # `llmAnalyticsSentimentLogic.ts::fetchGenerations`); positions:
+ # [uuid, trace_id, ai_input, model, distinct_id, timestamp, created_at].
+ results = serializers.ListField(child=serializers.ListField())
+
+
class LLMAnalyticsSentimentViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
scope_object = "llm_analytics"
permission_classes = [AccessControlPermission]
@@ -214,3 +291,71 @@ class LLMAnalyticsSentimentViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewS
)
return Response({"results": results}, status=status.HTTP_200_OK)
+
+ @extend_schema(
+ request=SentimentGenerationsRequestSerializer,
+ responses={
+ 200: SentimentGenerationsResponseSerializer,
+ 400: OpenApiTypes.OBJECT,
+ 500: OpenApiTypes.OBJECT,
+ },
+ tags=["LLM Analytics"],
+ )
+ @action(detail=False, methods=["post"], url_path="generations")
+ @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)
+
+ filters_payload = serializer.validated_data.get("filters") or {}
+ # Narrow to pydantic's ValidationError so unrelated 500s (e.g. a future
+ # import shift making `HogQLFilters` resolve to None) surface as 500
+ # rather than getting masked as a 400. Heavy property filters (`$ai_input`
+ # etc.) would read as NULL on the dedicated path — assumed not exposed
+ # in the sentiment-tab UI's property picker, which only surfaces
+ # non-heavy props.
+ try:
+ filters = HogQLFilters.model_validate(filters_payload)
+ except PydanticValidationError as e:
+ # `e.errors()` is a structured list of pydantic error dicts — safe to
+ # serialize and free of stack-trace context. `str(e)` would surface
+ # 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)
+
+ 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,
+ placeholders={},
+ team=self.team,
+ query_type="LLMSentimentGenerations",
+ limit_context=LimitContext.QUERY,
+ )
+ except Exception as e:
+ logger.exception(
+ "Failed to fetch sentiment generations",
+ team_id=self.team_id,
+ error=str(e),
+ )
+ return Response(
+ {"error": "Failed to fetch sentiment generations"},
+ status=status.HTTP_500_INTERNAL_SERVER_ERROR,
+ )
+
+ return Response({"results": result.results or []}, 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.py
new file mode 100644
index 000000000000..c84af63958ed
--- /dev/null
+++ b/products/llm_analytics/backend/api/test/test_sentiment_generations.py
@@ -0,0 +1,127 @@
+"""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 posthog.test.base import APIBaseTest
+from unittest.mock import MagicMock, patch
+
+from rest_framework import status
+
+
+class TestSentimentGenerationsEndpoint(APIBaseTest):
+ URL: str = ""
+
+ def setUp(self) -> None:
+ 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:
+ response = MagicMock()
+ response.results = rows
+ return response
+
+ @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 = [
+ [
+ "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)
+
+ response = self.client.post(
+ self.URL,
+ {"filters": {"dateRange": {"date_from": "-7d", "date_to": None}, "properties": []}},
+ content_type="application/json",
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ body = response.json()
+ assert body == {"results": rows}
+ # Resolver received an LLMSentimentGenerations query_type for tagging dashboards.
+ assert mock_resolver.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).
+ 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
+
+ @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")
+
+ response = self.client.post(
+ self.URL,
+ {"filters": {}},
+ content_type="application/json",
+ )
+ assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR
+
+ @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."""
+ from posthog.hogql import ast
+
+ mock_resolver.return_value = self._make_resolver_response([])
+
+ 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}"
diff --git a/products/llm_analytics/backend/queries/sentiment_generations.sql b/products/llm_analytics/backend/queries/sentiment_generations.sql
deleted file mode 100644
index ec5696d915ae..000000000000
--- a/products/llm_analytics/backend/queries/sentiment_generations.sql
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
--- Sentiment tab: fetch recent generations with user input for on-demand sentiment analysis.
---
--- Performance notes (learned from PR #50634 benchmarks on teams with 1B+ events):
--- - DO NOT use length(properties.$ai_input) in WHERE — it forces JSONExtractRaw on every
--- scanned row (benchmarked 2.4x slower). Size filtering done post-fetch if needed.
--- - properties.$ai_trace_id uses materialized column mat_$ai_trace_id with bloom filter index.
--- - properties.$ai_model uses materialized column.
--- - Sort key is (team_id, toDate(timestamp), event) so event + date range filtering is efficient.
--- - {filters} handles date range, property filters, and test account filtering via HogQL.
--- - Selecting properties.$ai_input is fine (only reads for matched rows, not in WHERE).
-*/
-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,
- properties.$ai_trace_id as trace_id,
- properties.$ai_input as ai_input,
- properties.$ai_model as model,
- distinct_id as did,
- timestamp as ts
- FROM events
- WHERE event = '$ai_generation'
- AND properties.$ai_input != ''
- AND properties.$ai_trace_id != ''
- AND {filters}
-)
-GROUP BY trace_id
-ORDER BY timestamp DESC, trace_id DESC
-LIMIT 200
diff --git a/products/llm_analytics/backend/text_repr/formatters/__init__.py b/products/llm_analytics/backend/text_repr/formatters/__init__.py
index 736947dcfa22..6e9111c2e838 100644
--- a/products/llm_analytics/backend/text_repr/formatters/__init__.py
+++ b/products/llm_analytics/backend/text_repr/formatters/__init__.py
@@ -5,18 +5,23 @@ Pure Python implementation for formatting $ai_generation, $ai_span, and $ai_trac
into human-readable text representations.
Main entry points:
-- format_event_text_repr: Format single events ($ai_generation, $ai_span)
+- format_event_text_repr: Format single events ($ai_generation, $ai_span) from a
+ `properties`-shaped event dict (e.g. an `events`-table row).
+- format_event_text_repr_from_ai_events_row: Same, but for callers reading
+ `posthog.ai_events` directly — accepts the dedicated-column shape and
+ handles JSON decoding of heavy columns.
- format_trace_text_repr: Format full traces with hierarchy
- llm_trace_to_formatter_format: Convert LLMTrace to format_trace_text_repr input format
"""
-from .event_formatter import format_event_text_repr
+from .event_formatter import format_event_text_repr, format_event_text_repr_from_ai_events_row
from .message_formatter import FormatterOptions, reduce_by_uniform_sampling
from .trace_formatter import format_trace_text_repr, llm_trace_to_formatter_format
__all__ = [
"FormatterOptions",
"format_event_text_repr",
+ "format_event_text_repr_from_ai_events_row",
"format_trace_text_repr",
"llm_trace_to_formatter_format",
"reduce_by_uniform_sampling",
diff --git a/products/llm_analytics/backend/text_repr/formatters/event_formatter.py b/products/llm_analytics/backend/text_repr/formatters/event_formatter.py
index c4288d18e304..761cbd6b5970 100644
--- a/products/llm_analytics/backend/text_repr/formatters/event_formatter.py
+++ b/products/llm_analytics/backend/text_repr/formatters/event_formatter.py
@@ -8,6 +8,7 @@ Dispatches to span_formatter for $ai_span events.
"""
import json
+from datetime import date, datetime
from typing import Any
from .constants import SEPARATOR
@@ -194,3 +195,68 @@ def format_event_text_repr(event: dict[str, Any], options: FormatterOptions | No
# Default to generation formatter for $ai_generation and other events
return format_generation_text_repr(event, options)
+
+
+def _maybe_decode_json(value: Any) -> Any:
+ """Parse a JSON-encoded string, falling back to the raw value on miss.
+
+ On `posthog.ai_events`, the heavy columns (`input`, `output`,
+ `output_choices`, `tools`, `input_state`, `output_state`) are stored as
+ JSON-encoded strings. The formatter needs them as parsed structures
+ (lists / dicts), but plain-text inputs that were never JSON should still
+ render as text — so we attempt a decode and pass the original through on
+ failure.
+ """
+ if not isinstance(value, str) or not value:
+ return value
+ try:
+ return json.loads(value)
+ except (json.JSONDecodeError, ValueError):
+ return value
+
+
+def format_event_text_repr_from_ai_events_row(row: dict[str, Any], options: FormatterOptions | None = None) -> str:
+ """Format an event whose heavy fields come from `posthog.ai_events` columns.
+
+ Bridges the dedicated-column shape (`input`, `output`, `output_choices`,
+ `tools`, `is_error`, `error`, `input_state`, `output_state`) to the
+ `properties`-shaped event dict that `format_event_text_repr` consumes.
+
+ Use this from query callers that read `posthog.ai_events` directly (i.e.
+ that need the heavy columns post-strip-migration). Callers that already
+ have an `events.properties` blob should keep using `format_event_text_repr`.
+
+ Expected `row` keys: `uuid`, `event`, `timestamp`, plus any of the heavy /
+ error / state columns listed above. Missing keys render as if the property
+ were absent.
+ """
+ props: dict[str, Any] = {}
+ if "input" in row:
+ props["$ai_input"] = _maybe_decode_json(row["input"])
+ if "output" in row:
+ props["$ai_output"] = _maybe_decode_json(row["output"])
+ if "output_choices" in row:
+ props["$ai_output_choices"] = _maybe_decode_json(row["output_choices"])
+ if "tools" in row:
+ props["$ai_tools"] = _maybe_decode_json(row["tools"])
+ if "input_state" in row:
+ props["$ai_input_state"] = _maybe_decode_json(row["input_state"])
+ if "output_state" in row:
+ props["$ai_output_state"] = _maybe_decode_json(row["output_state"])
+ if row.get("is_error"):
+ props["$ai_is_error"] = True
+ if row.get("error"):
+ props["$ai_error"] = row["error"]
+
+ timestamp = row.get("timestamp")
+ if isinstance(timestamp, datetime | date):
+ timestamp_str = timestamp.isoformat()
+ else:
+ timestamp_str = str(timestamp or "")
+ event_data = {
+ "id": str(row.get("uuid", "")),
+ "event": row.get("event"),
+ "timestamp": timestamp_str,
+ "properties": props,
+ }
+ return format_event_text_repr(event_data, options)
diff --git a/products/llm_analytics/backend/text_repr/formatters/test/test_event_formatter.py b/products/llm_analytics/backend/text_repr/formatters/test/test_event_formatter.py
index 51e4af4c7d89..5d3e1d4c9455 100644
--- a/products/llm_analytics/backend/text_repr/formatters/test/test_event_formatter.py
+++ b/products/llm_analytics/backend/text_repr/formatters/test/test_event_formatter.py
@@ -6,8 +6,14 @@ dicts, nested structures, and plain text.
"""
import json
+from datetime import datetime
-from ..event_formatter import _dict_to_yaml_lines, format_embedding_text_repr, format_generation_text_repr
+from ..event_formatter import (
+ _dict_to_yaml_lines,
+ format_embedding_text_repr,
+ format_event_text_repr_from_ai_events_row,
+ format_generation_text_repr,
+)
class TestDictToYamlLines:
@@ -189,3 +195,111 @@ class TestErrorFormattingEmbedding:
assert "ERROR:" in result
assert error_string in result
+
+
+class TestFormatEventTextReprFromAiEventsRow:
+ """Adapter for callers reading the ai_events dedicated-column shape.
+
+ Heavy columns (`input` / `output` / `output_choices` / `tools` / state)
+ are stored on `posthog.ai_events` as JSON-encoded strings. The shared
+ formatter wants parsed structures, so this adapter handles the decode and
+ builds the `properties` dict the existing formatters expect.
+ """
+
+ def test_decodes_json_input_and_output(self):
+ result = format_event_text_repr_from_ai_events_row(
+ {
+ "uuid": "u1",
+ "event": "$ai_generation",
+ "timestamp": datetime(2026, 4, 27),
+ "input": '[{"role":"user","content":"hi"}]',
+ "output": '"hello"',
+ }
+ )
+ assert "INPUT:" in result
+ assert "hi" in result
+ assert "OUTPUT:" in result
+ assert "hello" in result
+
+ def test_decodes_output_choices_dict_shape(self):
+ """`format_output_messages` requires `$ai_output_choices` as a parsed
+ list/dict — a raw JSON string would silently render nothing."""
+ result = format_event_text_repr_from_ai_events_row(
+ {
+ "uuid": "u1",
+ "event": "$ai_generation",
+ "timestamp": datetime(2026, 4, 27),
+ "input": '[{"role":"user","content":"hi"}]',
+ "output_choices": '[{"message":{"role":"assistant","content":"choice content"}}]',
+ }
+ )
+ assert "choice content" in result
+
+ def test_decodes_tools(self):
+ result = format_event_text_repr_from_ai_events_row(
+ {
+ "uuid": "u1",
+ "event": "$ai_generation",
+ "timestamp": datetime(2026, 4, 27),
+ "tools": '[{"type":"function","function":{"name":"lookup","description":"finds things"}}]',
+ "input": '[{"role":"user","content":"go"}]',
+ }
+ )
+ assert "lookup" in result
+
+ def test_passes_invalid_json_string_through(self):
+ """A non-JSON heavy value (e.g. plain text input) should still render —
+ the adapter falls back to the raw string."""
+ result = format_event_text_repr_from_ai_events_row(
+ {
+ "uuid": "u1",
+ "event": "$ai_generation",
+ "timestamp": datetime(2026, 4, 27),
+ "input": "plain text prompt",
+ }
+ )
+ assert "plain text prompt" in result
+
+ def test_renders_error_section_from_dedicated_columns(self):
+ """`is_error` / `error` come from native columns, not properties — the
+ adapter must surface them as `$ai_is_error` / `$ai_error` so the
+ existing error section fires."""
+ result = format_event_text_repr_from_ai_events_row(
+ {
+ "uuid": "u1",
+ "event": "$ai_generation",
+ "timestamp": datetime(2026, 4, 27),
+ "is_error": 1,
+ "error": "boom",
+ }
+ )
+ assert "ERROR:" in result
+ assert "boom" in result
+
+ def test_skips_missing_columns(self):
+ """A row that omits all heavy/error fields renders empty (no exception)."""
+ result = format_event_text_repr_from_ai_events_row(
+ {
+ "uuid": "u1",
+ "event": "$ai_generation",
+ "timestamp": datetime(2026, 4, 27),
+ }
+ )
+ assert "INPUT:" not in result
+ assert "OUTPUT:" not in result
+ assert "ERROR:" not in result
+
+ def test_dispatches_to_embedding_formatter_for_embedding_event(self):
+ """Adapter passes through to `format_event_text_repr` which routes by
+ event type — confirm `$ai_embedding` still ends up at the embedding
+ formatter (so its OUTPUT placeholder still appears)."""
+ result = format_event_text_repr_from_ai_events_row(
+ {
+ "uuid": "u1",
+ "event": "$ai_embedding",
+ "timestamp": datetime(2026, 4, 27),
+ "input": '"text to embed"',
+ }
+ )
+ assert "Embedding vector generated" in result
+ assert "text to embed" in result
diff --git a/products/llm_analytics/backend/tools/run_hog_eval_test.py b/products/llm_analytics/backend/tools/run_hog_eval_test.py
index b385e0f916d7..1cc0381d2e22 100644
--- a/products/llm_analytics/backend/tools/run_hog_eval_test.py
+++ b/products/llm_analytics/backend/tools/run_hog_eval_test.py
@@ -1,4 +1,3 @@
-import json
from typing import Any
from pydantic import BaseModel, Field
@@ -6,8 +5,9 @@ from pydantic import BaseModel, Field
from posthog.schema import AssistantTool
from posthog.hogql import ast
-from posthog.hogql.query import execute_hogql_query
+from posthog.hogql_queries.ai.ai_table_resolver import execute_with_ai_events_fallback
+from posthog.hogql_queries.ai.utils import HEAVY_COLUMN_NAMES, merge_heavy_properties
from posthog.sync import database_sync_to_async
from ee.hogai.tool import MaxTool
@@ -57,14 +57,20 @@ class RunHogEvalTestTool(MaxTool):
team = self._team
+ # Read from ai_events with native heavy columns so the Hog body still
+ # sees `event.properties.$ai_input` etc. for post-strip rows. Falls
+ # back to the events table when ai_events returns nothing — only
+ # legacy paths still write heavy props into events.properties on the
+ # fallback side.
query = ast.SelectQuery(
select=[
ast.Field(chain=["uuid"]),
ast.Field(chain=["event"]),
ast.Field(chain=["properties"]),
ast.Field(chain=["distinct_id"]),
+ *[ast.Field(chain=[col]) for col in HEAVY_COLUMN_NAMES],
],
- select_from=ast.JoinExpr(table=ast.Field(chain=["events"])),
+ select_from=ast.JoinExpr(table=ast.Field(chain=["posthog", "ai_events"]), alias="ai_events"),
where=ast.And(
exprs=[
ast.CompareOperation(
@@ -87,7 +93,12 @@ class RunHogEvalTestTool(MaxTool):
limit=ast.Constant(value=sample_count),
)
- response = await database_sync_to_async(execute_hogql_query)(query=query, team=team, limit_context=None)
+ response = await database_sync_to_async(execute_with_ai_events_fallback)(
+ query=query,
+ placeholders={},
+ team=team,
+ query_type="RunHogEvalTest",
+ )
if not response.results:
return (
@@ -95,13 +106,19 @@ class RunHogEvalTestTool(MaxTool):
None,
)
- # Parse all events first to collect property keys and build event data
+ # Parse all events first to collect property keys and build event data.
+ # Heavy columns trail the four base columns in row order — re-merge them
+ # into `properties` so the Hog body can read `properties.$ai_input` etc.
+ # On the events fallback the rewriter rewrites the heavy slots back to
+ # `properties.$ai_*`, so the merge is *idempotent*: pre-strip rows
+ # re-merge values already in `properties`; post-strip rows have NULL
+ # heavy slots that `merge_heavy_properties` skips.
parsed_events: list[dict[str, Any]] = []
all_property_keys: set[str] = set()
for row in response.results:
- properties = row[2]
- if isinstance(properties, str):
- properties = json.loads(properties)
+ heavy_values = row[4 : 4 + len(HEAVY_COLUMN_NAMES)]
+ heavy_columns = dict(zip(HEAVY_COLUMN_NAMES, heavy_values))
+ properties = merge_heavy_properties(row[2], heavy_columns)
all_property_keys.update(properties.keys())
parsed_events.append(
{
diff --git a/products/llm_analytics/backend/tools/test_run_hog_eval_test.py b/products/llm_analytics/backend/tools/test_run_hog_eval_test.py
index e6b5deaf0c39..98d1f152b0f2 100644
--- a/products/llm_analytics/backend/tools/test_run_hog_eval_test.py
+++ b/products/llm_analytics/backend/tools/test_run_hog_eval_test.py
@@ -7,6 +7,8 @@ from unittest.mock import MagicMock, patch
from asgiref.sync import async_to_sync
from parameterized import parameterized
+from posthog.hogql_queries.ai.utils import HEAVY_COLUMN_NAMES
+
from products.llm_analytics.backend.tools.run_hog_eval_test import RunHogEvalTestTool
@@ -30,6 +32,7 @@ def _make_event(
}
),
"test-user",
+ *(None,) * len(HEAVY_COLUMN_NAMES),
]
@@ -49,7 +52,7 @@ class TestRunHogEvalTestTool(BaseTest):
("length_check", "return length(output) > 0;", True),
]
)
- @patch("products.llm_analytics.backend.tools.run_hog_eval_test.execute_hogql_query")
+ @patch("products.llm_analytics.backend.tools.run_hog_eval_test.execute_with_ai_events_fallback")
def test_compilation_and_execution(self, _name, source, expected_verdict, mock_query):
mock_response = MagicMock()
mock_response.results = [_make_event()]
@@ -71,7 +74,7 @@ class TestRunHogEvalTestTool(BaseTest):
assert "Compilation error" in result
assert artifact is None
- @patch("products.llm_analytics.backend.tools.run_hog_eval_test.execute_hogql_query")
+ @patch("products.llm_analytics.backend.tools.run_hog_eval_test.execute_with_ai_events_fallback")
def test_no_events_found(self, mock_query):
mock_response = MagicMock()
mock_response.results = []
@@ -83,7 +86,7 @@ class TestRunHogEvalTestTool(BaseTest):
assert "No recent AI events" in result
assert artifact is None
- @patch("products.llm_analytics.backend.tools.run_hog_eval_test.execute_hogql_query")
+ @patch("products.llm_analytics.backend.tools.run_hog_eval_test.execute_with_ai_events_fallback")
def test_runtime_error_handling(self, mock_query):
mock_response = MagicMock()
mock_response.results = [_make_event()]
@@ -95,7 +98,7 @@ class TestRunHogEvalTestTool(BaseTest):
assert artifact is None
assert "Event" in result
- @patch("products.llm_analytics.backend.tools.run_hog_eval_test.execute_hogql_query")
+ @patch("products.llm_analytics.backend.tools.run_hog_eval_test.execute_with_ai_events_fallback")
def test_result_formatting_includes_previews(self, mock_query):
mock_response = MagicMock()
mock_response.results = [
@@ -113,7 +116,7 @@ class TestRunHogEvalTestTool(BaseTest):
assert "Output:" in result
assert "Result: PASS" in result
- @patch("products.llm_analytics.backend.tools.run_hog_eval_test.execute_hogql_query")
+ @patch("products.llm_analytics.backend.tools.run_hog_eval_test.execute_with_ai_events_fallback")
def test_null_return_shows_na(self, mock_query):
mock_response = MagicMock()
mock_response.results = [_make_event()]
@@ -126,7 +129,7 @@ class TestRunHogEvalTestTool(BaseTest):
assert "N/A" in result
assert "ERROR" not in result
- @patch("products.llm_analytics.backend.tools.run_hog_eval_test.execute_hogql_query")
+ @patch("products.llm_analytics.backend.tools.run_hog_eval_test.execute_with_ai_events_fallback")
def test_runtime_error_shows_error_not_na(self, mock_query):
mock_response = MagicMock()
mock_response.results = [_make_event()]
@@ -139,7 +142,7 @@ class TestRunHogEvalTestTool(BaseTest):
assert "Result: ERROR" in result
assert "Result: N/A" not in result
- @patch("products.llm_analytics.backend.tools.run_hog_eval_test.execute_hogql_query")
+ @patch("products.llm_analytics.backend.tools.run_hog_eval_test.execute_with_ai_events_fallback")
def test_ai_metric_event_type(self, mock_query):
mock_response = MagicMock()
event_row = [
@@ -156,3 +159,61 @@ class TestRunHogEvalTestTool(BaseTest):
assert "PASS" in result
assert "$ai_metric" in result
+
+ @patch("products.llm_analytics.backend.tools.run_hog_eval_test.execute_with_ai_events_fallback")
+ def test_heavy_column_remerge_for_stripped_event(self, mock_query):
+ """Post-strip rows have empty `properties.$ai_input` on `events`, but
+ the dedicated `ai_events` table carries the value in the `input`
+ column. The tool must re-merge those native columns back into
+ `properties` so the Hog body can read `properties.$ai_input` as
+ before. This test simulates the post-strip shape coming back from
+ the resolver."""
+ from posthog.hogql_queries.ai.utils import HEAVY_COLUMN_NAMES
+
+ # row[2]: stripped properties (no $ai_input).
+ # row[4..9]: native heavy column values, in HEAVY_COLUMN_NAMES order
+ # ("input", "output", "output_choices", "input_state", "output_state", "tools").
+ stripped_props = json.dumps({"$ai_model": "gpt-4o"})
+ heavy_input = '[{"role":"user","content":"recovered from native column"}]'
+ row = [
+ str(uuid.uuid4()),
+ "$ai_generation",
+ stripped_props,
+ "test-user",
+ heavy_input, # input
+ None, # output
+ None, # output_choices
+ None, # input_state
+ None, # output_state
+ None, # tools
+ ]
+ # Sanity: row layout matches what the source expects.
+ assert len(row) == 4 + len(HEAVY_COLUMN_NAMES)
+ mock_query.return_value = MagicMock(results=[row])
+
+ tool = self._make_tool()
+ # Hog body reads `properties.$ai_input` — this must be populated post-merge.
+ result, _artifact = _run_tool(
+ tool,
+ source="return properties.$ai_input != null;",
+ sample_count=1,
+ )
+
+ assert "Result: PASS" in result, f"expected PASS after heavy-merge, got: {result}"
+
+ @patch("products.llm_analytics.backend.tools.run_hog_eval_test.execute_with_ai_events_fallback")
+ def test_query_targets_ai_events(self, mock_query):
+ """The constructed SelectQuery must target `posthog.ai_events` — otherwise
+ the heavy column slots in the projection are NULL on the events table."""
+ from posthog.hogql import ast
+
+ mock_query.return_value = MagicMock(results=[])
+ tool = self._make_tool()
+ _run_tool(tool, source="return true;", sample_count=1)
+
+ kwargs = mock_query.call_args.kwargs
+ select = kwargs["query"]
+ assert isinstance(select, ast.SelectQuery)
+ from_chain = select.select_from.table.chain # type: ignore[union-attr]
+ # nosemgrep: hogql-no-string-table-chain
+ assert from_chain == ["posthog", "ai_events"]
diff --git a/products/llm_analytics/frontend/generated/api.schemas.ts b/products/llm_analytics/frontend/generated/api.schemas.ts
index 76a0158588dd..631fea249ab0 100644
--- a/products/llm_analytics/frontend/generated/api.schemas.ts
+++ b/products/llm_analytics/frontend/generated/api.schemas.ts
@@ -1163,7 +1163,7 @@ export const SentimentRequestAnalysisLevelEnumApi = {
export interface SentimentRequestApi {
/**
- * Trace IDs or generation IDs to classify, depending on analysis_level.
+ * Trace IDs (analysis_level=trace) or generation event UUIDs (analysis_level=generation).
* @minItems 1
* @maxItems 5
*/
@@ -1213,6 +1213,21 @@ export interface SentimentBatchResponseApi {
results: SentimentBatchResponseApiResults
}
+/**
+ * Filter shape mirrors the previous frontend `api.query({filters: ...})` payload.
+
+`filters` accepts the same `HogQLFilters` schema that the legacy frontend HogQL
+path used (dateRange, filterTestAccounts, properties), so the migration is
+behaviour-preserving for callers that pass a request unchanged.
+ */
+export interface SentimentGenerationsRequestApi {
+ filters?: unknown
+}
+
+export interface SentimentGenerationsResponseApi {
+ results: unknown[][]
+}
+
/**
* * `trace` - trace
* `event` - event
@@ -2347,6 +2362,10 @@ export type LlmAnalyticsSentimentCreate400 = { [key: string]: unknown }
export type LlmAnalyticsSentimentCreate500 = { [key: string]: unknown }
+export type LlmAnalyticsSentimentGenerationsCreate400 = { [key: string]: unknown }
+
+export type LlmAnalyticsSentimentGenerationsCreate500 = { [key: string]: unknown }
+
export type LlmAnalyticsSummarizationCreate400 = { [key: string]: unknown }
export type LlmAnalyticsSummarizationCreate403 = { [key: string]: unknown }
diff --git a/products/llm_analytics/frontend/generated/api.ts b/products/llm_analytics/frontend/generated/api.ts
index 650b34fdb36b..7e6d38bed0e5 100644
--- a/products/llm_analytics/frontend/generated/api.ts
+++ b/products/llm_analytics/frontend/generated/api.ts
@@ -94,6 +94,8 @@ import type {
ScoreDefinitionCreateApi,
ScoreDefinitionNewVersionApi,
SentimentBatchResponseApi,
+ SentimentGenerationsRequestApi,
+ SentimentGenerationsResponseApi,
SentimentRequestApi,
SummarizeRequestApi,
SummarizeResponseApi,
@@ -1261,6 +1263,32 @@ 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/`
+}
+
+export const llmAnalyticsSentimentGenerationsCreate = async (
+ projectId: string,
+ sentimentGenerationsRequestApi: SentimentGenerationsRequestApi,
+ options?: RequestInit
+): Promise<SentimentGenerationsResponseApi> => {
+ return apiMutator<SentimentGenerationsResponseApi>(getLlmAnalyticsSentimentGenerationsCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(sentimentGenerationsRequestApi),
+ })
+}
+
/**
*
Generate an AI-powered summary of an LLM trace or event.
diff --git a/products/llm_analytics/frontend/generated/api.zod.ts b/products/llm_analytics/frontend/generated/api.zod.ts
index 9c8af0f00a7f..40d54d866397 100644
--- a/products/llm_analytics/frontend/generated/api.zod.ts
+++ b/products/llm_analytics/frontend/generated/api.zod.ts
@@ -1079,7 +1079,7 @@ export const LlmAnalyticsSentimentCreateBody = /* @__PURE__ */ zod.object({
.array(zod.string())
.min(1)
.max(llmAnalyticsSentimentCreateBodyIdsMax)
- .describe('Trace IDs or generation IDs to classify, depending on analysis_level.'),
+ .describe('Trace IDs (analysis_level=trace) or generation event UUIDs (analysis_level=generation).'),
analysis_level: zod
.enum(['trace', 'generation'])
.describe('* `trace` - trace\n* `generation` - generation')
@@ -1098,6 +1098,23 @@ 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(),
+ })
+ .describe(
+ 'Filter shape mirrors the previous frontend `api.query({filters: ...})` payload.\n\n`filters` accepts the same `HogQLFilters` schema that the legacy frontend HogQL\npath used (dateRange, filterTestAccounts, properties), so the migration is\nbehaviour-preserving for callers that pass a request unchanged.'
+ )
+
/**
*
Generate an AI-powered summary of an LLM trace or event.
diff --git a/products/llm_analytics/frontend/tabs/llmAnalyticsSentimentLogic.ts b/products/llm_analytics/frontend/tabs/llmAnalyticsSentimentLogic.ts
index 6b42c6ed405a..d605b24e2cb3 100644
--- a/products/llm_analytics/frontend/tabs/llmAnalyticsSentimentLogic.ts
+++ b/products/llm_analytics/frontend/tabs/llmAnalyticsSentimentLogic.ts
@@ -3,13 +3,12 @@ import { loaders } from 'kea-loaders'
import { subscriptions } from 'kea-subscriptions'
import posthog from 'posthog-js'
-import api from 'lib/api'
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
+import { getCurrentTeamId } from '~/lib/utils/getAppContext'
import { groupsModel } from '~/models/groupsModel'
-import { HogQLQueryResponse, NodeKind } from '~/queries/schema/schema-general'
-import sentimentGenerationsQueryTemplate from '../../backend/queries/sentiment_generations.sql?raw'
+import { llmAnalyticsSentimentGenerationsCreate } from '../generated/api'
import { llmAnalyticsSharedLogic } from '../llmAnalyticsSharedLogic'
import { llmGenerationSentimentLazyLoaderLogic } from '../llmGenerationSentimentLazyLoaderLogic'
import type { GenerationSentiment, MessageSentiment } from '../llmSentimentLazyLoaderLogic'
@@ -168,9 +167,14 @@ interface GenerationsQueryValues {
let lastRawFetchCount = 0
async function fetchGenerations(values: GenerationsQueryValues, cursor: string | null): Promise<SentimentGeneration[]> {
- const response = (await api.query({
- kind: NodeKind.HogQLQuery,
- query: sentimentGenerationsQueryTemplate,
+ // Routed through `LLMAnalyticsSentimentViewSet.generations` which wraps
+ // `execute_with_ai_events_fallback`. This keeps the read on the standard
+ // kill-switch / fallback / `ai_query_source` tagging contract for the
+ // rollout. Response shape is tuple-positional ([uuid, trace_id, ai_input,
+ // model, distinct_id, timestamp, created_at]) — the generated wrapper
+ // types `results` as `unknown[][]` so the position casts here are
+ // unavoidable until the response serializer declares per-element types.
+ const response = await llmAnalyticsSentimentGenerationsCreate(String(getCurrentTeamId()), {
filters: {
dateRange: {
date_from: values.dateFilter.dateFrom || null,
@@ -179,9 +183,9 @@ async function fetchGenerations(values: GenerationsQueryValues, cursor: string |
filterTestAccounts: values.shouldFilterTestAccounts,
properties: values.propertyFilters,
},
- })) as HogQLQueryResponse
+ })
- return (response.results || []).map((row) => ({
+ return (response.results || []).map((row: unknown[]) => ({
uuid: row[0] as string,
traceId: row[1] as string,
aiInput: row[2],
diff --git a/products/llm_analytics/mcp/tools.yaml b/products/llm_analytics/mcp/tools.yaml
index 04117ff86d3e..9b21c7dc1ac3 100644
--- a/products/llm_analytics/mcp/tools.yaml
+++ b/products/llm_analytics/mcp/tools.yaml
@@ -14,6 +14,9 @@ ui_apps:
data_type: LLMCostsData
view_component: LLMCostsView
tools:
+ llm-analytics-sentiment-generations-create:
+ operation: llm_analytics_sentiment_generations_create
+ enabled: false
llma-clustering-config-get:
operation: llm_analytics_clustering_config_retrieve
enabled: false
diff --git a/products/llm_analytics/skills/exploring-llm-traces/SKILL.md b/products/llm_analytics/skills/exploring-llm-traces/SKILL.md
index cde0e0a681d0..a7c263d39703 100644
--- a/products/llm_analytics/skills/exploring-llm-traces/SKILL.md
+++ b/products/llm_analytics/skills/exploring-llm-traces/SKILL.md
@@ -207,24 +207,6 @@ posthog:query-llm-traces-list
}
```
-### By SQL (for full-text search or custom aggregations)
-
-Use SQL when you need something `query-llm-traces-list` can't express — typically full-text search across message content or custom aggregations.
-
-```sql
-SELECT
- properties.$ai_trace_id AS trace_id,
- properties.$ai_model AS model,
- timestamp
-FROM events
-WHERE
- event = '$ai_generation'
- AND timestamp >= now() - INTERVAL 1 HOUR
- AND properties.$ai_input ILIKE '%search term%'
-ORDER BY timestamp DESC
-LIMIT 20
-```
-
For more complex SQL patterns, read these references:
- [Single trace retrieval](./references/example-llm-trace.md.j2) — fetches a single trace by ID with all events and properties (renders the `TraceQuery` HogQL)
diff --git a/products/llm_analytics/skills/exploring-llm-traces/references/example-llm-traces-list.md b/products/llm_analytics/skills/exploring-llm-traces/references/example-llm-traces-list.md
index 86d56b3fcf72..c9d18c9ec776 100644
--- a/products/llm_analytics/skills/exploring-llm-traces/references/example-llm-traces-list.md
+++ b/products/llm_analytics/skills/exploring-llm-traces/references/example-llm-traces-list.md
@@ -4,8 +4,8 @@ List multiple LLM traces with aggregated latency, token usage, costs, and error
This is a two-phase query for performance: first find matching trace IDs, then fetch full trace data.
Time ranges are always required. Results can be large — dump to a file if needed.
-This query intentionally omits large content fields (`$ai_input`, `$ai_output_choices`, `$ai_input_state`, `$ai_output_state`).
-Use the [single trace query](./example-llm-trace.md) to retrieve those for a specific trace.
+This query intentionally omits large content fields (`$ai_input`, `$ai_output`, `$ai_output_choices`, `$ai_input_state`, `$ai_output_state`, `$ai_tools`).
+Use the [single trace query](./example-llm-trace.md) (or the `query-llm-trace` wrapper) to retrieve those for a specific trace; both read from a dedicated table that retains the full payload for ~30 days.
## Phase 1 — Find trace IDs
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 8b4343185348..e46b6189844c 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -35841,6 +35841,21 @@ export namespace Schemas {
results: SentimentBatchResponseResults;
}
+ /**
+ * Filter shape mirrors the previous frontend `api.query({filters: ...})` payload.
+
+ `filters` accepts the same `HogQLFilters` schema that the legacy frontend HogQL
+ path used (dateRange, filterTestAccounts, properties), so the migration is
+ behaviour-preserving for callers that pass a request unchanged.
+ */
+ export interface SentimentGenerationsRequest {
+ filters?: unknown;
+ }
+
+ export interface SentimentGenerationsResponse {
+ results: unknown[][];
+ }
+
/**
* * `trace` - trace
* `generation` - generation
@@ -35855,7 +35870,7 @@ export namespace Schemas {
export interface SentimentRequest {
/**
- * Trace IDs or generation IDs to classify, depending on analysis_level.
+ * Trace IDs (analysis_level=trace) or generation event UUIDs (analysis_level=generation).
* @minItems 1
* @maxItems 5
*/
@@ -40900,6 +40915,10 @@ export namespace Schemas {
export type LlmAnalyticsSentimentCreate500 = { [key: string]: unknown };
+ export type LlmAnalyticsSentimentGenerationsCreate400 = { [key: string]: unknown };
+
+ export type LlmAnalyticsSentimentGenerationsCreate500 = { [key: string]: unknown };
+
export type LlmAnalyticsSummarizationCreate400 = { [key: string]: unknown };
export type LlmAnalyticsSummarizationCreate403 = { [key: string]: unknown };
diff --git a/services/mcp/src/generated/llm_analytics/api.ts b/services/mcp/src/generated/llm_analytics/api.ts
index 9474fc6fffb4..95a1a5b2b95e 100644
--- a/services/mcp/src/generated/llm_analytics/api.ts
+++ b/services/mcp/src/generated/llm_analytics/api.ts
@@ -826,7 +826,7 @@ export const LlmAnalyticsSentimentCreateBody = /* @__PURE__ */ zod.object({
.array(zod.string())
.min(1)
.max(llmAnalyticsSentimentCreateBodyIdsMax)
- .describe('Trace IDs or generation IDs to classify, depending on analysis_level.'),
+ .describe('Trace IDs (analysis_level=trace) or generation event UUIDs (analysis_level=generation).'),
analysis_level: zod
.enum(['trace', 'generation'])
.describe('* `trace` - trace\n* `generation` - generation')
diff --git a/services/mcp/src/templates/execute-sql-prompt.md b/services/mcp/src/templates/execute-sql-prompt.md
index ffaf6fb5c7e9..dffdaff36ecd 100644
--- a/services/mcp/src/templates/execute-sql-prompt.md
+++ b/services/mcp/src/templates/execute-sql-prompt.md
@@ -35,6 +35,19 @@ If the required events, properties, or tables do not exist, say so — do not ru
Large JSON values in results (notably full `properties` objects) are truncated by default. If you anticipate a large result set, or you are selecting the full `properties` object (e.g., `SELECT properties FROM events`), dump the results to a file and process them with bash rather than returning them inline. Alternatively, cherry-pick specific keys (`properties.$browser`) instead of the whole object.
+### Large LLM trace fields are stripped from `events.properties`
+
+For LLM events (`$ai_generation`, `$ai_trace`, `$ai_span`, etc.), these specific keys with large values are stripped from `events.properties`:
+
+- `properties.$ai_input`
+- `properties.$ai_output`
+- `properties.$ai_output_choices`
+- `properties.$ai_input_state`
+- `properties.$ai_output_state`
+- `properties.$ai_tools`
+
+Prefer `query-llm-trace` / `query-llm-traces-list` whenever you need any of those six keys — they contain information on the proper read patterns to a dedicated AI events table which contains these fields. Other AI properties (token counts, costs, model, trace IDs) stay on `events` in all three regimes and are safe to query directly.
+
### Example: searching for existing insights
<example>
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/llma-sentiment-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/llma-sentiment-create.json
index 59e966613c31..b1445526c0fc 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/llma-sentiment-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/llma-sentiment-create.json
@@ -35,7 +35,7 @@
"type": "boolean"
},
"ids": {
- "description": "Trace IDs or generation IDs to classify, depending on analysis_level.",
+ "description": "Trace IDs (analysis_level=trace) or generation event UUIDs (analysis_level=generation).",
"items": {
"type": "string"
},