:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(aio): summarize traces by ID instead of posting their contents (#79051)
Radu Raicea2a0af03c02da
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 79b05089453e..ec2164c2e1c1 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6139,7 +6139,7 @@ snapshots:scenes-app-experiments--experiment-with-multi-step-funnel-metric--dark:hash: v1.k794b7964.b59d17fc7aa41c9d54d50ebcad07ee995472e82d0509a99a3534f689402d8014.SWRehUneMfgPHvrdCTfEc6TWMR2LSyxma5jGOhO-iSAscenes-app-experiments--experiment-with-multi-step-funnel-metric--light:- hash: v1.k794b7964.0f81873b7b3e44139ef64b33d35aaa9c9857943789e7f88fe0dd8eb9d84b6125.0yFYuT8reEOckBG0v7K4CTlrcHgCWGlaDbiVhp7Euck+ hash: v1.k794b7964.97d7402f9b51d0c2d446c61c0022bb257b60230ee9ef045fb98f9a6f6881021a.u-DOTSJ-2l7aMIVwI4CBomzduA0B_q6-6kfVwbLKl5Mscenes-app-experiments--experiment-with-multiple-metrics--dark:hash: v1.k794b7964.935a9474cbc0ab0c65ece0051d8ebc3a88c8f40de3bb8a7a7621dbe1766a4105.2TXN7Cqx8Qd7XzXBjoaslAsm-r4qbXmG0Vlch8j6ph0scenes-app-experiments--experiment-with-multiple-metrics--light:@@ -6603,7 +6603,7 @@ snapshots:scenes-app-insights-error-empty-states--query-server-error--dark:hash: v1.k794b7964.5e0a4f13fb00ef944649228004095f84fd1d859bd66cdd5ec9e25bd745d6828d.k4NYuOAkHqlOwwSIUSHJiywF8FxVwqlIbahs9NdgpF4scenes-app-insights-error-empty-states--query-server-error--light:- hash: v1.k794b7964.2b569e38b9188a1b6651645db04fc1861a1fbca67c8a36c59a717d949b3e9cb6.6wC07yLeoObvqkr-b3JIDgOLa-iqmpa8aO-eLLzWoEw+ hash: v1.k794b7964.8cbd2901888aa723067ddea0dc2c6045628c0cb872438beca4e667592d25aaf6.4GmhzW21hmldOgELAwHy522bovvzkaq8b4i0NowPhb8scenes-app-insights-error-empty-states--server-error--dark:hash: v1.k794b7964.c78c9eaddad034d4747bccc025468e045b9e641e8f70daa75c428ac94def566c.WSvKXlMMIMORSx1W_7pTEH4AQMQUtr_4cSHSVfBGl_0scenes-app-insights-error-empty-states--server-error--light:diff --git a/frontend/src/initKea.ts b/frontend/src/initKea.tsindex 02699344cd17..4e6c89741495 100644--- a/frontend/src/initKea.ts+++ b/frontend/src/initKea.ts@@ -47,6 +47,7 @@ const ERROR_FILTER_ALLOW_LIST = ['loadDatasetItemDetails', // Dataset item modals render their own retry state'loadDatasetItemVersions', // Dataset item modals render their own retry state'exportDataset', // Dataset scenes render their own retry state+ 'generateSummary', // Summary view renders its own retry state'loadSelfDrivingEvaluationReports', // The self-driving eval table renders its own retry state'loadToolDataEvents','loadPrChecks', // Polled in the Inbox report detail; the CI checks section renders its own error statediff --git a/products/ai_observability/backend/api/summarization.py b/products/ai_observability/backend/api/summarization.pyindex 6344f8c82797..ab1c1bcb311f 100644--- a/products/ai_observability/backend/api/summarization.py+++ b/products/ai_observability/backend/api/summarization.py@@ -10,6 +10,7 @@ Endpoints:"""import time+from datetime import datetimefrom django.core.cache import cache@@ -54,6 +55,9 @@ from products.ai_observability.backend.text_repr.formatters import (logger = structlog.get_logger(__name__)+# Event types the formatters can render on their own, so a single one of them can be summarized by UUID.+SUMMARIZABLE_EVENT_TYPES = ["$ai_generation", "$ai_span", "$ai_embedding", "$ai_evaluation"]+# Request/Response Serializersclass SummarizeRequestSerializer(serializers.Serializer):@@ -289,15 +293,16 @@ class AIObservabilitySummarizationViewSet(TeamAndOrgViewSetMixin, viewsets.Generraise exceptions.NotFound(f"Trace '{trace_id}' not found in the given date range.")trace_obj = response.results[0]- trace_dict, hierarchy = llm_trace_to_formatter_format(trace_obj)+ trace_dict, hierarchy = llm_trace_to_formatter_format(trace_obj, nest_children=True)return trace_id, {"trace": trace_dict, "hierarchy": hierarchy}def _fetch_generation_data(self, generation_id: str, date_from: str | None, date_to: str | None) -> tuple[str, dict]:- """Fetch a single generation event by UUID and return (entity_id, entity_data) for summarization."""- from datetime import datetime+ """Fetch a single event by UUID and return (entity_id, entity_data) for summarization.+ Covers every event type the trace view offers a summary for, not just generations.+ """qdr = QueryDateRange(DateRange(date_from=date_from or "-30d", date_to=date_to),self.team,@@ -311,7 +316,7 @@ class AIObservabilitySummarizationViewSet(TeamAndOrgViewSetMixin, viewsets.Gener"""SELECT uuid, event, timestamp, propertiesFROM events- WHERE event = '$ai_generation'+ WHERE event IN {summarizable_events}AND uuid = {generation_uuid}AND timestamp >= {date_from}AND timestamp <= {date_to}@@ -319,6 +324,7 @@ class AIObservabilitySummarizationViewSet(TeamAndOrgViewSetMixin, viewsets.Gener""",),placeholders={+ "summarizable_events": ast.Tuple(exprs=[ast.Constant(value=e) for e in SUMMARIZABLE_EVENT_TYPES]),"generation_uuid": ast.Constant(value=generation_id),"date_from": ast.Constant(value=qdr.date_from().isoformat()),"date_to": ast.Constant(value=qdr.date_to().isoformat()),@@ -327,7 +333,7 @@ class AIObservabilitySummarizationViewSet(TeamAndOrgViewSetMixin, viewsets.Gener)if not result.results:- raise exceptions.NotFound(f"Generation '{generation_id}' not found in the given date range.")+ raise exceptions.NotFound(f"Event '{generation_id}' not found in the given date range.")row = result.results[0]props = row[3]@@ -512,10 +518,11 @@ The response includes the structured summary, the text representation, and metaddate_from = serializer.validated_data.get("date_from")date_to = serializer.validated_data.get("date_to")+ entity_data: dict | None = Noneif trace_id:- entity_id, entity_data = self._fetch_trace_data(trace_id, date_from, date_to)+ entity_id = trace_idelif generation_id:- entity_id, entity_data = self._fetch_generation_data(generation_id, date_from, date_to)+ entity_id = generation_idelse:data = serializer.validated_data["data"]entity_id, entity_data = self._extract_entity_id(summarize_type, data)@@ -533,6 +540,14 @@ The response includes the structured summary, the text representation, and metad)return Response(cached_result, status=status.HTTP_200_OK)+ if trace_id:+ _, entity_data = self._fetch_trace_data(trace_id, date_from, date_to)+ elif generation_id:+ _, entity_data = self._fetch_generation_data(generation_id, date_from, date_to)++ if entity_data is None:+ raise exceptions.ValidationError("No trace or event data was provided for summarization.")+text_repr = self._generate_text_repr(summarize_type, entity_data)start_time = time.time()diff --git a/products/ai_observability/backend/api/test/test_summarization.py b/products/ai_observability/backend/api/test/test_summarization.pyindex ccd33889b7c1..0206c3e388e5 100644--- a/products/ai_observability/backend/api/test/test_summarization.py+++ b/products/ai_observability/backend/api/test/test_summarization.py@@ -4,9 +4,11 @@ Tests for summarization API endpoint.Tests cover title field presence, request validation, and response format."""+import uuid+from datetime import UTC, datetime, timedeltafrom typing import Any-from posthog.test.base import APIBaseTest+from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_eventsfrom unittest.mock import patchfrom rest_framework import status@@ -355,3 +357,99 @@ class TestSummarizationAPI(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)self.assertIn("AI data processing must be approved", response.data["detail"])+++class TestSummarizationByID(ClickhouseTestMixin, APIBaseTest):+ def _approve_ai_processing(self) -> None:+ self.organization.is_ai_data_processing_approved = True+ self.organization.save()++ @patch("products.ai_observability.backend.api.summarization.summarize")+ def test_summarizes_a_span_by_event_uuid(self, mock_summarize):+ self._approve_ai_processing()+ mock_summarize.return_value = SummarizationResponse(+ title="Span Summary",+ flow_diagram="Start\n |\nComplete",+ summary_bullets=[SummaryBullet(text="Span fetched documents", line_refs="L1")],+ interesting_notes=[],+ )++ span_uuid = uuid.uuid4()+ timestamp = datetime(2026, 1, 15, 12, 0, tzinfo=UTC)+ _create_event(+ event="$ai_span",+ distinct_id="user-1",+ team=self.team,+ timestamp=timestamp,+ event_uuid=str(span_uuid),+ properties={+ "$ai_trace_id": "trace-1",+ "$ai_span_id": "span-1",+ "$ai_span_name": "fetch-docs",+ "$ai_input_state": {"query": "docs"},+ "$ai_output_state": {"documents": 3},+ },+ )+ flush_persons_and_events()++ response = self.client.post(+ f"/api/environments/{self.team.id}/llm_analytics/summarization/",+ {+ "generation_id": str(span_uuid),+ "mode": "minimal",+ "date_from": (timestamp - timedelta(days=1)).isoformat(),+ "date_to": (timestamp + timedelta(days=1)).isoformat(),+ },+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK, response.data)+ self.assertEqual(response.data["summary"]["title"], "Span Summary")+ # The formatter upper-cases the span name in its header.+ self.assertIn("fetch-docs", response.data["text_repr"].lower())++ def test_unknown_event_uuid_is_reported_as_not_found(self):+ self._approve_ai_processing()++ response = self.client.post(+ f"/api/environments/{self.team.id}/llm_analytics/summarization/",+ {"generation_id": str(uuid.uuid4()), "mode": "minimal", "date_from": "-7d"},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)+ self.assertIn("not found", response.data["detail"])++ @patch("products.ai_observability.backend.api.summarization.summarize")+ def test_returns_cached_trace_when_source_trace_is_unavailable(self, mock_summarize):+ self._approve_ai_processing()+ mock_summarize.return_value = SummarizationResponse(+ title="Cached Trace Summary",+ flow_diagram="Start\n |\nComplete",+ summary_bullets=[SummaryBullet(text="Trace completed", line_refs="L1")],+ interesting_notes=[],+ )+ trace_id = f"cached-trace-{uuid.uuid4()}"++ initial_response = self.client.post(+ f"/api/environments/{self.team.id}/llm_analytics/summarization/",+ {+ "summarize_type": "trace",+ "mode": "minimal",+ "data": {+ "trace": {"id": trace_id, "properties": {"$ai_span_name": "cached-trace"}},+ "hierarchy": [],+ },+ },+ format="json",+ )+ cached_response = self.client.post(+ f"/api/environments/{self.team.id}/llm_analytics/summarization/",+ {"trace_id": trace_id, "mode": "minimal", "date_from": "-7d"},+ format="json",+ )++ self.assertEqual(initial_response.status_code, status.HTTP_200_OK, initial_response.data)+ self.assertEqual(cached_response.status_code, status.HTTP_200_OK, cached_response.data)+ self.assertEqual(cached_response.data["summary"]["title"], "Cached Trace Summary")+ self.assertEqual(mock_summarize.call_count, 1)diff --git a/products/ai_observability/backend/text_repr/formatters/test/test_trace_formatter.py b/products/ai_observability/backend/text_repr/formatters/test/test_trace_formatter.pyindex c90c52e425f6..953913bf0edb 100644--- a/products/ai_observability/backend/text_repr/formatters/test/test_trace_formatter.py+++ b/products/ai_observability/backend/text_repr/formatters/test/test_trace_formatter.py@@ -6,6 +6,11 @@ Tests cover tree structure rendering, expandable nodes, ASCII art, and options hfrom typing import Any+from parameterized import parameterized++from posthog.schema import LLMTrace, LLMTraceEvent++from ..constants import MAX_TREE_DEPTHfrom ..message_formatter import truncate_contentfrom ..trace_formatter import (_format_cost,@@ -14,6 +19,7 @@ from ..trace_formatter import (_get_event_summary,_render_tree,format_trace_text_repr,+ llm_trace_to_formatter_format,)@@ -647,3 +653,170 @@ class TestEdgeCases:assert "TRACE ERROR:" in result# Should serialize error objectassert "message" in result or "error" in result+++class TestLLMTraceToFormatterFormat:+ TRACE_ID = "trace-1"++ def _trace(self, *events: LLMTraceEvent) -> LLMTrace:+ return LLMTrace(+ id=self.TRACE_ID,+ createdAt="2026-08-06T12:00:00Z",+ distinctId="user-1",+ events=list(events),+ )++ def _event(+ self,+ event_id: str,+ properties: dict[str, Any],+ event: str = "$ai_span",+ created_at: str = "2026-08-06T12:00:00Z",+ ) -> LLMTraceEvent:+ return LLMTraceEvent(id=event_id, event=event, createdAt=created_at, properties=properties)++ def test_defaults_to_a_flat_hierarchy(self):+ trace = self._trace(+ self._event("span-1", {"$ai_span_id": "span-1", "$ai_trace_id": self.TRACE_ID}),+ self._event("gen-1", {"$ai_parent_id": "span-1"}, event="$ai_generation"),+ )++ _, hierarchy = llm_trace_to_formatter_format(trace)++ assert [node["event"]["id"] for node in hierarchy] == ["span-1", "gen-1"]+ assert all(node["children"] == [] for node in hierarchy)++ def test_nests_children_under_their_parent(self):+ trace = self._trace(+ self._event("span-1", {"$ai_span_id": "span-1", "$ai_trace_id": self.TRACE_ID}),+ self._event(+ "gen-1",+ {"$ai_generation_id": "gen-1", "$ai_parent_id": "span-1"},+ event="$ai_generation",+ ),+ self._event("span-2", {"$ai_span_id": "span-2", "$ai_parent_id": "gen-1"}),+ )++ _, hierarchy = llm_trace_to_formatter_format(trace, nest_children=True)++ assert [node["event"]["id"] for node in hierarchy] == ["span-1"]+ assert [node["event"]["id"] for node in hierarchy[0]["children"]] == ["gen-1"]+ assert [node["event"]["id"] for node in hierarchy[0]["children"][0]["children"]] == ["span-2"]++ def test_promotes_events_whose_parent_is_missing_to_roots(self):+ trace = self._trace(+ self._event("span-1", {"$ai_span_id": "span-1", "$ai_trace_id": self.TRACE_ID}),+ self._event("gen-1", {"$ai_parent_id": "span-never-ingested"}, event="$ai_generation"),+ )++ _, hierarchy = llm_trace_to_formatter_format(trace, nest_children=True)++ assert sorted(node["event"]["id"] for node in hierarchy) == ["gen-1", "span-1"]++ @parameterized.expand(+ [+ ("generation_list", "$ai_generation_id", ["invalid"]),+ ("span_object", "$ai_span_id", {"invalid": "id"}),+ ("parent_list", "$ai_parent_id", ["invalid"]),+ ("trace_object", "$ai_trace_id", {"invalid": "id"}),+ ]+ )+ def test_ignores_non_scalar_hierarchy_ids(+ self, _case_name: str, property_name: str, malformed_id: list[str] | dict[str, str]+ ) -> None:+ properties: dict[str, Any] = {property_name: malformed_id}+ if property_name in {"$ai_generation_id", "$ai_span_id"}:+ properties["$ai_trace_id"] = self.TRACE_ID+ else:+ properties["$ai_span_id"] = "span-1"+ trace = self._trace(self._event("event-1", properties))++ _, hierarchy = llm_trace_to_formatter_format(trace, nest_children=True)++ assert [node["event"]["id"] for node in hierarchy] == ["event-1"]++ @parameterized.expand([("integer", 1, "1"), ("boolean", True, "true")])+ def test_normalizes_scalar_hierarchy_ids(+ self, _case_name: str, parent_id: int | bool, child_parent_id: str+ ) -> None:+ trace = self._trace(+ self._event("parent", {"$ai_span_id": parent_id, "$ai_trace_id": self.TRACE_ID}),+ self._event("child", {"$ai_span_id": "child", "$ai_parent_id": child_parent_id}),+ )++ _, hierarchy = llm_trace_to_formatter_format(trace, nest_children=True)++ assert [node["event"]["id"] for node in hierarchy] == ["parent"]+ assert [node["event"]["id"] for node in hierarchy[0]["children"]] == ["child"]++ def test_excludes_feedback_and_metric_events(self):+ trace = self._trace(+ self._event("span-1", {"$ai_span_id": "span-1", "$ai_trace_id": self.TRACE_ID}),+ self._event("feedback-1", {"$ai_trace_id": self.TRACE_ID}, event="$ai_feedback"),+ self._event("metric-1", {"$ai_trace_id": self.TRACE_ID}, event="$ai_metric"),+ )++ _, hierarchy = llm_trace_to_formatter_format(trace, nest_children=True)++ assert [node["event"]["id"] for node in hierarchy] == ["span-1"]++ def test_preserves_events_in_a_parent_cycle(self) -> None:+ trace = self._trace(+ self._event("span-1", {"$ai_span_id": "span-1", "$ai_parent_id": "span-2"}),+ self._event("span-2", {"$ai_span_id": "span-2", "$ai_parent_id": "span-1"}),+ )++ _, hierarchy = llm_trace_to_formatter_format(trace, nest_children=True)++ assert [node["event"]["id"] for node in hierarchy] == ["span-1"]+ assert [node["event"]["id"] for node in hierarchy[0]["children"]] == ["span-2"]++ def test_emits_duplicate_node_ids_once_under_the_retained_parent(self) -> None:+ trace = self._trace(+ self._event("root-1", {"$ai_span_id": "root-1", "$ai_trace_id": self.TRACE_ID}),+ self._event("root-2", {"$ai_span_id": "root-2", "$ai_trace_id": self.TRACE_ID}),+ self._event("shared-old", {"$ai_span_id": "shared", "$ai_parent_id": "root-1"}),+ self._event("shared-duplicate", {"$ai_span_id": "shared", "$ai_parent_id": "root-2"}),+ self._event("shared-retained", {"$ai_span_id": "shared", "$ai_parent_id": "root-2"}),+ )++ _, hierarchy = llm_trace_to_formatter_format(trace, nest_children=True)++ assert [node["event"]["id"] for node in hierarchy] == ["root-1", "root-2"]+ assert hierarchy[0]["children"] == []+ assert [node["event"]["id"] for node in hierarchy[1]["children"]] == ["shared-retained"]++ def test_splits_overdeep_branches_into_additional_roots(self) -> None:+ events = [self._event("span-0", {"$ai_span_id": "span-0", "$ai_trace_id": self.TRACE_ID})]+ events.extend(+ self._event(+ f"span-{index}",+ {"$ai_span_id": f"span-{index}", "$ai_parent_id": f"span-{index - 1}"},+ )+ for index in range(1, MAX_TREE_DEPTH + 3)+ )+ trace = self._trace(*events)++ _, hierarchy = llm_trace_to_formatter_format(trace, nest_children=True)++ assert [node["event"]["id"] for node in hierarchy] == ["span-0", f"span-{MAX_TREE_DEPTH + 1}"]+ assert [node["event"]["id"] for node in hierarchy[1]["children"]] == [f"span-{MAX_TREE_DEPTH + 2}"]++ def test_orders_siblings_by_when_their_operation_began(self):+ # Captured on completion, so the event that finished first is not the one that started first.+ trace = self._trace(+ self._event(+ "slow-start-first",+ {"$ai_span_id": "slow-start-first", "$ai_trace_id": self.TRACE_ID, "$ai_latency": 2},+ created_at="2026-08-06T12:00:02Z",+ ),+ self._event(+ "quick-start-second",+ {"$ai_span_id": "quick-start-second", "$ai_trace_id": self.TRACE_ID, "$ai_latency": 0},+ created_at="2026-08-06T12:00:01Z",+ ),+ )++ _, hierarchy = llm_trace_to_formatter_format(trace, nest_children=True)++ assert [node["event"]["id"] for node in hierarchy] == ["slow-start-first", "quick-start-second"]diff --git a/products/ai_observability/backend/text_repr/formatters/trace_formatter.py b/products/ai_observability/backend/text_repr/formatters/trace_formatter.pyindex 2d81f28b6a83..13706743b5d9 100644--- a/products/ai_observability/backend/text_repr/formatters/trace_formatter.py+++ b/products/ai_observability/backend/text_repr/formatters/trace_formatter.py@@ -10,7 +10,11 @@ import jsonimport base64from typing import Any-from posthog.schema import LLMTrace+from dateutil.parser import isoparse++from posthog.schema import LLMTrace, LLMTraceEvent++from posthog.dataclasses import frozenfrom .constants import DEFAULT_MAX_LENGTH, MAX_TREE_DEPTH, SEPARATORfrom .event_formatter import format_event_text_repr@@ -23,13 +27,133 @@ from .message_formatter import (truncate_content,)+# Annotations the trace view attaches to other nodes rather than rendering as steps of its own.+FEEDBACK_EVENT_TYPES = frozenset({"$ai_feedback", "$ai_metric"})+++@frozen(order=True)+class _TraceEventSortKey:+ operation_start_ms: float+ negative_latency_ms: float+++def _first_set_property(properties: dict[str, Any], *keys: str) -> Any:+ """First of `keys` that is set, mirroring the `??` chains the trace view resolves IDs with."""+ for key in keys:+ value = properties.get(key)+ if value is not None:+ return value+ return None+++def _normalize_hierarchy_id(value: Any) -> str | None:+ if isinstance(value, bool):+ return str(value).lower()+ if isinstance(value, str | int | float):+ return str(value)+ return None+++def _latency_ms(event: LLMTraceEvent) -> float:+ try:+ latency = float(event.properties.get("$ai_latency", 0))+ except (TypeError, ValueError):+ return 0.0+ return latency * 1000 if latency > 0 else 0.0+++def _operation_start_ms(event: LLMTraceEvent) -> float:+ """Epoch ms the event's operation began. PostHog AI SDKs capture an event when the operation+ finishes, so its timestamp is the end; OTel-ingested spans already carry the start."""+ try:+ end_ms = isoparse(event.createdAt).timestamp() * 1000+ except (TypeError, ValueError):+ return 0.0+ if event.properties.get("$ai_ingestion_source") == "otel":+ return end_ms+ return end_ms - _latency_ms(event)+++def _to_formatter_event(event: LLMTraceEvent) -> dict[str, Any]:+ return {+ "id": event.id,+ "event": event.event,+ "properties": event.properties,+ "timestamp": event.createdAt,+ }-def llm_trace_to_formatter_format(llm_trace: LLMTrace) -> tuple[dict[str, Any], list[dict[str, Any]]]:++def _nest_events(llm_trace: LLMTrace) -> list[dict[str, Any]]:+ """Rebuild the parent/child hierarchy the trace view shows, following `$ai_parent_id` links."""+ events_by_node_id: dict[str, LLMTraceEvent] = {}++ for event in llm_trace.events:+ if event.event in FEEDBACK_EVENT_TYPES:+ continue+ node_id = _normalize_hierarchy_id(_first_set_property(event.properties, "$ai_generation_id", "$ai_span_id"))+ if node_id is None:+ node_id = event.id+ events_by_node_id[node_id] = event++ child_ids: dict[str, list[str]] = {}+ for node_id, event in events_by_node_id.items():+ parent_id = _normalize_hierarchy_id(_first_set_property(event.properties, "$ai_parent_id", "$ai_trace_id"))+ if parent_id is not None:+ child_ids.setdefault(parent_id, []).append(node_id)++ def sort_key(node_id: str) -> _TraceEventSortKey:+ event = events_by_node_id[node_id]+ # Siblings that began together are ordered longest first, matching the timeline.+ return _TraceEventSortKey(+ operation_start_ms=_operation_start_ms(event), negative_latency_ms=-_latency_ms(event)+ )++ emitted_node_ids: set[str] = set()++ def build(node_id: str, depth: int) -> dict[str, Any] | None:+ event = events_by_node_id.get(node_id)+ if event is None or node_id in emitted_node_ids or depth > MAX_TREE_DEPTH:+ return None+ emitted_node_ids.add(node_id)+ children = sorted(child_ids.get(node_id, []), key=sort_key)+ return {+ "event": _to_formatter_event(event),+ "children": [node for node in (build(child_id, depth + 1) for child_id in children) if node is not None],+ }++ # An event whose parent never made it into the trace still has to be rendered, so it becomes a root.+ orphan_ids = [+ node_id+ for node_id, event in events_by_node_id.items()+ if (+ parent_id := _normalize_hierarchy_id(_first_set_property(event.properties, "$ai_parent_id", "$ai_trace_id"))+ )+ is not None+ and parent_id != llm_trace.id+ and parent_id not in events_by_node_id+ ]+ root_ids = sorted([*child_ids.get(llm_trace.id, []), *orphan_ids], key=sort_key)+ hierarchy = [node for node in (build(root_id, 0) for root_id in root_ids) if node is not None]++ # Start unvisited components at a new root so cycles and depth-limited branches still render once.+ remaining_root_ids = sorted(+ (node_id for node_id in events_by_node_id if node_id not in emitted_node_ids), key=sort_key+ )+ hierarchy.extend(node for node in (build(root_id, 0) for root_id in remaining_root_ids) if node is not None)+ return hierarchy+++def llm_trace_to_formatter_format(+ llm_trace: LLMTrace, *, nest_children: bool = False+) -> tuple[dict[str, Any], list[dict[str, Any]]]:"""Convert an LLMTrace object to the format expected by format_trace_text_repr.Args:llm_trace: The LLMTrace object from TraceQueryRunner+ nest_children: Reconstruct the parent/child hierarchy instead of returning every event as a+ root. Callers that render a trace for a reader want this; the flat shape is kept as the+ default so existing prompts and evaluations see the events they saw before.Returns:A tuple of (trace_dict, hierarchy) suitable for format_trace_text_repr@@ -45,18 +169,10 @@ def llm_trace_to_formatter_format(llm_trace: LLMTrace) -> tuple[dict[str, Any],},}- hierarchy = [- {- "event": {- "id": event.id,- "event": event.event,- "properties": event.properties,- "timestamp": event.createdAt,- },- "children": [],- }- for event in llm_trace.events- ]+ if nest_children:+ return trace_dict, _nest_events(llm_trace)++ hierarchy = [{"event": _to_formatter_event(event), "children": []} for event in llm_trace.events]return trace_dict, hierarchydiff --git a/products/ai_observability/frontend/summary-view/SummaryViewDisplay.tsx b/products/ai_observability/frontend/summary-view/SummaryViewDisplay.tsxindex e2be241f8872..199609dab210 100644--- a/products/ai_observability/frontend/summary-view/SummaryViewDisplay.tsx+++ b/products/ai_observability/frontend/summary-view/SummaryViewDisplay.tsx@@ -27,16 +27,9 @@ export interface SummaryViewDisplayProps {autoGenerate?: boolean}-interface SummaryViewLogicValues {- summaryData: { summary: any; text_repr: string } | null- summaryDataLoading: boolean- summaryMode: 'minimal' | 'detailed'- summaryDataFailure?: Error | string | unknown-}-export function SummaryViewDisplay({ trace, event, tree, autoGenerate }: SummaryViewDisplayProps): JSX.Element {const logic = summaryViewLogic({ trace, event, tree, autoGenerate })- const { summaryData, summaryDataLoading, summaryMode } = useValues(logic)+ const { summaryData, summaryDataLoading, summaryMode, summaryError } = useValues(logic)const { generateSummary, setSummaryMode, regenerateSummary } = useActions(logic)const { dataProcessingAccepted } = useValues(maxGlobalLogic)@@ -66,19 +59,9 @@ export function SummaryViewDisplay({ trace, event, tree, autoGenerate }: Summaryreturn <div className="p-4 text-muted">Summary is only available for traces, generations, and spans.</div>}- // Extract error message from loader failure if any- const logicValues = logic.values as SummaryViewLogicValues- const errorMessage = logicValues.summaryDataFailure- ? logicValues.summaryDataFailure instanceof Error- ? logicValues.summaryDataFailure.message- : typeof logicValues.summaryDataFailure === 'string'- ? logicValues.summaryDataFailure- : 'An unexpected error occurred'- : null-return (<div className="p-4 flex flex-col gap-4 h-full overflow-hidden">- {!summaryData && !summaryDataLoading && !errorMessage && (+ {!summaryData && !summaryDataLoading && !summaryError && (<div className="flex flex-col items-center gap-4 py-8"><div className="text-muted text-center"><p>Generate an AI-powered summary of this {eventTypeName}.</p>@@ -148,10 +131,10 @@ export function SummaryViewDisplay({ trace, event, tree, autoGenerate }: Summary</div>)}- {errorMessage && (+ {summaryError && (<div className="bg-danger-highlight border border-danger rounded p-4"><div className="font-semibold text-danger">Failed to generate summary</div>- <div className="text-sm mt-2">{errorMessage}</div>+ <div className="text-sm mt-2">{summaryError}</div>{!dataProcessingAccepted ? (<AIConsentPopoverWrappershowArrowdiff --git a/products/ai_observability/frontend/summary-view/components/SummaryRenderer.tsx b/products/ai_observability/frontend/summary-view/components/SummaryRenderer.tsxindex fdf4cc5e9d9a..ac9cd47f9b4e 100644--- a/products/ai_observability/frontend/summary-view/components/SummaryRenderer.tsx+++ b/products/ai_observability/frontend/summary-view/components/SummaryRenderer.tsx@@ -7,11 +7,12 @@ import { Tooltip } from '@posthog/lemon-ui'import { LLMTrace, LLMTraceEvent } from '~/queries/schema/schema-general'-import { StructuredSummary, summaryViewLogic } from '../summaryViewLogic'+import type { StructuredSummaryApi } from '../../generated/api.schemas'+import { summaryViewLogic } from '../summaryViewLogic'import { parseLineReferences } from '../utils/lineReferenceUtils'export interface SummaryRendererProps {- summary: StructuredSummary+ summary: StructuredSummaryApitrace?: LLMTraceevent?: LLMTraceEventtree?: any[]diff --git a/products/ai_observability/frontend/summary-view/summaryViewLogic.test.ts b/products/ai_observability/frontend/summary-view/summaryViewLogic.test.tsnew file mode 100644index 000000000000..990908de2798--- /dev/null+++ b/products/ai_observability/frontend/summary-view/summaryViewLogic.test.ts@@ -0,0 +1,102 @@+import { expectLogic } from 'kea-test-utils'++import api from 'lib/api'+import { ApiError } from 'lib/api-error'++import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'+import type { LLMTrace } from '~/queries/schema/schema-general'+import { initKeaTests } from '~/test/init'++import { summaryViewLogic } from './summaryViewLogic'++describe('summaryViewLogic', () => {+ let logic: ReturnType<typeof summaryViewLogic.build>+ let createSpy: jest.SpyInstance++ const SUMMARIZATION_PATH = '/llm_analytics/summarization/'++ const trace: LLMTrace = {+ id: 'trace-1',+ createdAt: '2026-01-15T12:00:00Z',+ distinctId: 'person-1',+ events: [+ {+ id: 'gen-1',+ event: '$ai_generation',+ createdAt: '2026-01-15T12:00:00Z',+ properties: { $ai_input: [{ role: 'user', content: 'a very long prompt' }] },+ },+ ],+ }++ /** Other mounted logics post too, so only summarization requests get the test's response. */+ function mockSummarization(response: Promise<any>): void {+ createSpy.mockImplementation((url: string) =>+ url.includes(SUMMARIZATION_PATH) ? response : Promise.resolve({})+ )+ }++ function summarizationPayload(): any {+ const call = createSpy.mock.calls.find(([url]) => url.includes(SUMMARIZATION_PATH))+ return call?.[1]+ }++ async function generateSummary(): Promise<void> {+ logic = summaryViewLogic({ trace, tree: [] })+ logic.mount()+ await expectLogic(logic, () => {+ logic.actions.generateSummary({ mode: 'minimal' })+ }).toFinishAllListeners()+ }++ beforeEach(() => {+ silenceKeaLoadersErrors()+ initKeaTests()+ createSpy = jest.spyOn(api, 'create')+ mockSummarization(+ Promise.resolve({+ summary: { title: 'Summary', flow_diagram: '', summary_bullets: [], interesting_notes: [] },+ text_repr: 'L1 trace',+ })+ )+ })++ afterEach(() => {+ logic?.unmount()+ jest.restoreAllMocks()+ resumeKeaLoadersErrors()+ })++ it('asks for the trace by ID instead of sending its contents', async () => {+ await generateSummary()++ expect(summarizationPayload()).toEqual({+ mode: 'minimal',+ force_refresh: false,+ trace_id: 'trace-1',+ date_from: '2026-01-14T12:00:00.000Z',+ date_to: '2026-01-16T12:00:00.000Z',+ })+ })++ it('shows a readable message when the response carries no error body', async () => {+ mockSummarization(Promise.reject(new ApiError(undefined, 504, undefined, null)))++ await generateSummary()++ expect(logic.values.summaryError).toBe('Generating this summary took too long. Try again in a moment.')+ })++ it('clears a stale summary when regeneration fails', async () => {+ await generateSummary()+ expect(logic.values.summaryData?.summary.title).toBe('Summary')+ mockSummarization(Promise.reject(new Error('Regeneration failed')))++ await expectLogic(logic, () => {+ logic.actions.regenerateSummary()+ }).toFinishAllListeners()++ expect(logic.values.summaryData).toBeNull()+ expect(logic.values.summaryError).toBe('Regeneration failed')+ })+})diff --git a/products/ai_observability/frontend/summary-view/summaryViewLogic.ts b/products/ai_observability/frontend/summary-view/summaryViewLogic.tsindex 51a047e9aa1b..38afb7a89b88 100644--- a/products/ai_observability/frontend/summary-view/summaryViewLogic.ts+++ b/products/ai_observability/frontend/summary-view/summaryViewLogic.ts@@ -1,32 +1,20 @@import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'-import api from 'lib/api'+import { ApiError } from 'lib/api-error'+import { dayjs } from 'lib/dayjs'import { maxGlobalLogic } from 'scenes/max/maxGlobalLogic'import { teamLogic } from 'scenes/teamLogic'import { LLMTrace, LLMTraceEvent } from '~/queries/schema/schema-general'import { EnrichedTraceTreeNode } from '../aiObservabilityTraceDataLogic'+import { llmAnalyticsSummarizationCreate } from '../generated/api'+import type { StructuredSummaryApi, SummarizeRequestApi, SummarizeResponseApi } from '../generated/api.schemas'-export type SummaryMode = 'minimal' | 'detailed'+export type SummaryMode = NonNullable<SummarizeRequestApi['mode']>-export interface SummaryBullet {- text: string- line_refs: string-}--export interface InterestingNote {- text: string- line_refs: string // Can be empty string if no line refs-}--export interface StructuredSummary {- title: string- flow_diagram: string- summary_bullets: SummaryBullet[]- interesting_notes: InterestingNote[] // Empty array if none-}+type SummaryData = Pick<SummarizeResponseApi, 'summary' | 'text_repr'>export interface SummaryViewLogicProps {trace?: LLMTrace@@ -43,11 +31,9 @@ export interface summaryViewLogicValues {isFlowExpanded: booleanisNotesExpanded: booleanisSummaryExpanded: boolean- summaryData: {- summary: StructuredSummary- text_repr: string- } | null+ summaryData: SummaryData | nullsummaryDataLoading: boolean+ summaryError: string | nullsummaryMode: SummaryMode}@@ -66,8 +52,8 @@ export interface summaryViewLogicActions {}generateSummarySuccess: (summaryData: {- summary: any- text_repr: any+ summary: StructuredSummaryApi+ text_repr: string},payload?: {mode: SummaryMode@@ -75,8 +61,8 @@ export interface summaryViewLogicActions {}) => {summaryData: {- summary: any- text_repr: any+ summary: StructuredSummaryApi+ text_repr: string}payload?: {mode: SummaryMode@@ -118,6 +104,37 @@ export type summaryViewLogicType = MakeLogicType<summaryViewLogicMeta>+/**+ * Days either side of the entity's own timestamp to search for it, instead of the endpoint's 30-day+ * default. Narrow keeps the lookup off traces that reuse a customer-supplied ID, and a single trace+ * rarely spans longer than this.+ */+const LOOKUP_WINDOW_DAYS = 1++function lookupWindow(createdAt: string): Pick<SummarizeRequestApi, 'date_from' | 'date_to'> {+ const timestamp = dayjs(createdAt)+ return {+ date_from: timestamp.subtract(LOOKUP_WINDOW_DAYS, 'day').toISOString(),+ date_to: timestamp.add(LOOKUP_WINDOW_DAYS, 'day').toISOString(),+ }+}++/**+ * A gateway rejection or timeout carries no body, so `ApiError` has no `detail` to show and falls+ * back to its own `Non-OK response [POST ...] (status 504: )` string. The status is carried over so+ * transient gateway errors stay out of error tracking.+ */+function toReadableError(error: unknown): unknown {+ if (!(error instanceof ApiError) || error.detail) {+ return error+ }+ const message =+ error.status === 504+ ? 'Generating this summary took too long. Try again in a moment.'+ : "Couldn't generate a summary. Try again, and if it keeps happening contact support."+ return new ApiError(message, error.status, error.headers, error.data)+}+export const summaryViewLogic = kea<summaryViewLogicType>([path(['products', 'ai_observability', 'frontend', 'summary-view', 'summaryViewLogic']),props({} as SummaryViewLogicProps),@@ -167,6 +184,23 @@ export const summaryViewLogic = kea<summaryViewLogicType>([toggleNotesExpanded: (state) => !state,},],+ summaryData: [+ null as SummaryData | null,+ {+ generateSummary: () => null,+ },+ ],+ // kea-loaders dispatches `generateSummaryFailure` but keeps no value, so the failure has to+ // be held here for the view to show it.+ summaryError: [+ null as string | null,+ {+ generateSummary: () => null,+ generateSummarySuccess: () => null,+ generateSummaryFailure: (_, { error }) =>+ error || "Couldn't generate a summary. Try again, and if it keeps happening contact support.",+ },+ ],}),selectors({entityId: [@@ -184,7 +218,6 @@ export const summaryViewLogic = kea<summaryViewLogicType>([}),loaders(({ props, values }) => ({summaryData: {- __default: null as { summary: StructuredSummary; text_repr: string } | null,generateSummary: async ({ mode, forceRefresh }: { mode: SummaryMode; forceRefresh?: boolean }) => {// Initialize here rather than in the function signature to avoid TS2371// Kea should be fixed to avoid including the default value in the function signature@@ -197,37 +230,27 @@ export const summaryViewLogic = kea<summaryViewLogicType>([throw new Error('AI data processing must be approved before generating summaries')}- // Determine if we're summarizing a trace or an event- const isTrace = !!props.trace-- // Build request payload- const payload = isTrace- ? {- summarize_type: 'trace',- mode,- force_refresh: forceRefresh,- data: {- trace: props.trace,- hierarchy: props.tree || [],- },- }- : {- summarize_type: 'event',- mode,- force_refresh: forceRefresh,- data: {- event: props.event,- },- }-- // Call the summarization API endpointconst teamId = values.currentTeamIdif (!teamId) {throw new Error('Team ID not available')}- // nosemgrep: prefer-codegen-api- const data = await api.create(`api/environments/${teamId}/llm_analytics/summarization/`, payload)+ // Ask for the trace or event by ID: the endpoint reads it back from ClickHouse itself,+ // so a trace with large prompts no longer has to fit in a request body.+ const entity = props.trace ?? props.event+ if (!entity) {+ throw new Error('Nothing to summarize')+ }+ const request: SummarizeRequestApi = {+ mode,+ force_refresh: forceRefresh,+ ...(props.trace ? { trace_id: entity.id } : { generation_id: entity.id }),+ ...lookupWindow(entity.createdAt),+ }++ const data = await llmAnalyticsSummarizationCreate(String(teamId), request).catch((error: unknown) => {+ throw toReadableError(error)+ })// The endpoint can resolve to an empty body (e.g. no summary available yet),// so guard before reading fields to avoid a null dereference.