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(tracing): show a trace's ai events inline in the waterfall (#105723)

Jon McCallum5b6d911bb82c
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index fc8627971d7f..731472f4cc4d 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6928,6 +6928,10 @@ snapshots:
hash: v1.k794b7964.e0e79a77be55d932e351dd624093d0107d0fc1737ad2377ff59625f8c9d2919f.FoUJvZ3pT1VvRHqfLTd8ng_hDXpYvjWqiodIwsZhnGw
products-tracing-spanerrorsbadge--trace-tier-with-more-in-session--light:
hash: v1.k794b7964.b816e38267a9feb005f365b0826180703192d0d7e1775020b201aa4b9c4a1832.I52iOSlgYhkIDdh5N-Zm-Kb0yYD09_Fdkwzq1RvocwQ
+ products-tracing-traceaieventscapnotice--past-the-cap--dark:
+ hash: v1.k794b7964.d6977b391a9f26309799ef1ef522b6834aa7f0e23dab4e293069c58c2a0b54e4.IwwwLP99sni7rCWBvJCE_8dpsla1s7t7mGMyixDS0rI
+ products-tracing-traceaieventscapnotice--past-the-cap--light:
+ hash: v1.k794b7964.feda0df05e8e57c124b6730048dd57d0d678d429c263cff2c5fcb575f945b280.ahdaUiPk9d3Xp8PlnXG7oy3Y5sUkAslXiNwntmQsWAk
products-tracing-virtualizedspanlist--custom-columns--dark:
hash: v1.k794b7964.706ec8b392aa8b7e63123ae73233f0aa49314df1f4c32894f6f48c7883c35cf3.4royX3fTwY_wCZ7DXohmhbu1njNM4B7nRI6YgxJaKiw
products-tracing-virtualizedspanlist--custom-columns--light:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 7b5097e10ee1..b034820e50a3 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -535,6 +535,7 @@ export const FEATURE_FLAGS = {
TEXT_CARD_WORD_ART: 'text-card-word-art', // owner: @jonmcwest, gates the word art insert button in dashboard text cards
TOOLBAR_PAID_HEATMAPS: 'toolbar-paid-heatmaps', // owner: #team-web-analytics
TRACING: 'tracing', // owner: #team-apm (@jonmcwest, @frankh)
+ TRACING_AI_EVENTS: 'tracing-ai-events', // owner: #team-apm — shows a trace's LLM analytics events inline in the trace drawer waterfall
TRACING_FACET_RAIL: 'tracing-facet-rail', // owner: #team-apm — gates the facet rail (faceted filter sidebar) in tracing
TRACING_IMPACT_STRIP: 'tracing-impact-strip', // owner: #team-apm — gates the sessions/users impact strip and the Operations table's impact columns
TRACING_LATENCY_HEATMAP: 'tracing-latency-heatmap', // owner: #team-apm — gates the latency-over-time heatmap chart in tracing
diff --git a/products/tracing/backend/ai_events.py b/products/tracing/backend/ai_events.py
index cd3f9f103777..9262e6ebb3d6 100644
--- a/products/tracing/backend/ai_events.py
+++ b/products/tracing/backend/ai_events.py
@@ -12,7 +12,8 @@ if TYPE_CHECKING:
from posthog.models import Team, User
# A run rarely makes more than a few hundred model calls, and past this many rows the waterfall
-# stops being readable, so the lookup does not page.
+# stops being readable, so the lookup does not page. A trace past the cap reports `has_more`, and
+# the caller links to AI observability, which lists every event.
MAX_AI_EVENTS_PER_TRACE = 500
# The LLM analytics event kinds that carry a latency, so each one can be placed on the timeline.
@@ -45,9 +46,15 @@ class TraceAiEvent:
is_error: bool
-def fetch_trace_ai_events(*, team: "Team", user: "User | None", trace_id: str) -> list[TraceAiEvent]:
+@frozen
+class TraceAiEvents:
+ events: list[TraceAiEvent]
+ has_more: bool
+
+
+def fetch_trace_ai_events(*, team: "Team", user: "User | None", trace_id: str) -> TraceAiEvents:
"""LLM analytics events whose `$ai_trace_id` is the OpenTelemetry trace id, earliest start
- first. Matches the 32-hex form OTel ingestion writes and the hyphenated UUID form the LLM
+ first, capped at `MAX_AI_EVENTS_PER_TRACE`. Matches the 32-hex form OTel ingestion writes and the hyphenated UUID form the LLM
gateway writes for a `traceparent` header.
Reads `ai_events`, whose sort key starts with `(team_id, trace_id)`, so a trace with no AI
@@ -98,15 +105,20 @@ def fetch_trace_ai_events(*, team: "Team", user: "User | None", trace_id: str) -
"trace_ids": ast.Constant(value=_stored_trace_id_forms(trace_id)),
"otel_source": ast.Constant(value=OTEL_INGESTION_SOURCE),
"max_latency": ast.Constant(value=MAX_LATENCY_SECONDS),
- # Explicit, because HogQL caps a select without a LIMIT at 100 rows.
- "limit": ast.Constant(value=MAX_AI_EVENTS_PER_TRACE),
+ # Explicit, because HogQL caps a select without a LIMIT at 100 rows. One row past the
+ # cap tells a full trace from a truncated one.
+ "limit": ast.Constant(value=MAX_AI_EVENTS_PER_TRACE + 1),
},
)
response = execute_hogql_query(query=query, team=team, user=user, query_type="TracingTraceAiEventsQuery")
# The event alias differs from the column it aggregates, because an alias equal to a column
# name shadows it in WHERE and ClickHouse then rejects the aggregate there.
columns = [{"event_name": "event"}.get(c, c) for c in response.columns or []]
- return [TraceAiEvent(**dict(zip(columns, row))) for row in response.results or []]
+ rows = response.results or []
+ return TraceAiEvents(
+ events=[TraceAiEvent(**dict(zip(columns, row))) for row in rows[:MAX_AI_EVENTS_PER_TRACE]],
+ has_more=len(rows) > MAX_AI_EVENTS_PER_TRACE,
+ )
def _stored_trace_id_forms(trace_id: str) -> list[str]:
diff --git a/products/tracing/backend/facade/api.py b/products/tracing/backend/facade/api.py
index f074dd17c821..37ab68d2f872 100644
--- a/products/tracing/backend/facade/api.py
+++ b/products/tracing/backend/facade/api.py
@@ -35,7 +35,8 @@ from posthog.schema import (
)
from products.tracing.backend.ai_events import (
- TraceAiEvent,
+ MAX_AI_EVENTS_PER_TRACE as _MAX_AI_EVENTS_PER_TRACE,
+ TraceAiEvents,
fetch_trace_ai_events as _fetch_trace_ai_events,
)
from products.tracing.backend.attribute_breakdown_query_runner import (
@@ -71,6 +72,9 @@ FACET_COLUMNS = _FACET_COLUMNS
# presentation layer can bound its request serializer without reaching into the lookup module.
MAX_IDS_PER_LOOKUP = _MAX_IDS_PER_LOOKUP
+# Cap on the AI events one trace lookup returns. Re-exported so the response can state it.
+MAX_AI_EVENTS_PER_TRACE = _MAX_AI_EVENTS_PER_TRACE
+
# --- Converters (model -> frozen dataclass) ---
#
@@ -246,9 +250,10 @@ def count_session_exceptions(
return _count_session_exceptions(team=team, session_ids=session_ids, date_from=date_from, date_to=date_to)
-def fetch_trace_ai_events(*, team: "Team", user: "User | None", trace_id: str) -> list[TraceAiEvent]:
+def fetch_trace_ai_events(*, team: "Team", user: "User | None", trace_id: str) -> TraceAiEvents:
"""List the LLM analytics events whose `$ai_trace_id` is the trace id, as lowercase hex or as
- the hyphenated UUID the LLM gateway writes, earliest start first. The events side of the
+ the hyphenated UUID the LLM gateway writes, earliest start first, capped with `has_more` set
+ past the cap. The events side of the
trace-to-AI-events join, which the caller finishes. The user's property access rules apply to
the returned columns.
"""
diff --git a/products/tracing/backend/presentation/views.py b/products/tracing/backend/presentation/views.py
index d131d78459a7..24dc0e37a76c 100644
--- a/products/tracing/backend/presentation/views.py
+++ b/products/tracing/backend/presentation/views.py
@@ -52,6 +52,7 @@ from posthog.permissions import posthog_feature_flag_enabled
from ..facade.api import (
FACET_COLUMNS,
+ MAX_AI_EVENTS_PER_TRACE,
MAX_IDS_PER_LOOKUP,
annotate_self_time,
count_session_exceptions,
@@ -859,7 +860,13 @@ class _TracingTraceAiEventSerializer(serializers.Serializer):
class _TracingTraceAiEventsResponseSerializer(serializers.Serializer):
- results = _TracingTraceAiEventSerializer(many=True, help_text="AI events in the trace, earliest start first.")
+ results = _TracingTraceAiEventSerializer(
+ many=True, help_text="AI events in the trace, earliest start first, up to `limit` of them."
+ )
+ limit = serializers.IntegerField(help_text="The most AI events the lookup returns for one trace.")
+ has_more = serializers.BooleanField(
+ help_text="Whether the trace has more AI events than `results` holds. The full list is in AI observability under the events' `ai_trace_id`."
+ )
class _TracingSparklineRowSerializer(serializers.Serializer):
@@ -1941,11 +1948,17 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)
except ValueError:
return Response(status=status.HTTP_400_BAD_REQUEST)
- events = fetch_trace_ai_events(team=self.team, user=cast(User, request.user), trace_id=trace_id)
+ ai_events = fetch_trace_ai_events(team=self.team, user=cast(User, request.user), trace_id=trace_id)
- self._report_usage(request, "tracing trace ai events fetched", {"ai_events_count": len(events)})
+ self._report_usage(
+ request,
+ "tracing trace ai events fetched",
+ {"ai_events_count": len(ai_events.events), "ai_events_has_more": ai_events.has_more},
+ )
- response = _TracingTraceAiEventsResponseSerializer(instance={"results": events})
+ response = _TracingTraceAiEventsResponseSerializer(
+ instance={"results": ai_events.events, "has_more": ai_events.has_more, "limit": MAX_AI_EVENTS_PER_TRACE}
+ )
return Response(response.data, status=status.HTTP_200_OK)
@extend_schema(
diff --git a/products/tracing/backend/tests/test_trace_ai_events.py b/products/tracing/backend/tests/test_trace_ai_events.py
index 7a67e54e20bc..d29e1f5ca7cf 100644
--- a/products/tracing/backend/tests/test_trace_ai_events.py
+++ b/products/tracing/backend/tests/test_trace_ai_events.py
@@ -97,6 +97,20 @@ class TestTraceAiEvents(ClickhouseTestMixin, APIBaseTest):
"is_error": True,
}
assert results[1]["is_error"] is False
+ assert json.loads(response.content)["has_more"] is False
+
+ @patch("products.tracing.backend.presentation.views.MAX_AI_EVENTS_PER_TRACE", 1)
+ @patch("products.tracing.backend.ai_events.MAX_AI_EVENTS_PER_TRACE", 1)
+ def test_flags_a_trace_past_the_cap(self) -> None:
+ first = self._create_ai_event(TRACE_A, timestamp="2026-06-02T08:00:01Z")
+ self._create_ai_event(TRACE_A, timestamp="2026-06-02T08:00:02Z")
+ flush_persons_and_events()
+
+ body = json.loads(self._get(TRACE_A).content)
+
+ assert [row["uuid"] for row in body["results"]] == [first]
+ assert body["has_more"] is True
+ assert body["limit"] == 1
@parameterized.expand(
[
diff --git a/products/tracing/frontend/aiEventSpans.test.ts b/products/tracing/frontend/aiEventSpans.test.ts
new file mode 100644
index 000000000000..8db039b88e9a
--- /dev/null
+++ b/products/tracing/frontend/aiEventSpans.test.ts
@@ -0,0 +1,144 @@
+import { makeSpan } from './__mocks__/span'
+import { buildAiEventSpans, TraceAiEvent } from './aiEventSpans'
+import type { Span } from './types'
+
+const TRACE_ID = '4BF92F3577B34DA6A3CE929D0E0E4736'
+
+function span(overrides: Partial<Span> & { span_id: string; timestamp: string; duration_nano: number }): Span {
+ return makeSpan({
+ uuid: overrides.span_id,
+ trace_id: TRACE_ID,
+ name: overrides.span_id,
+ is_root_span: false,
+ ...overrides,
+ })
+}
+
+function aiEvent(overrides: Partial<TraceAiEvent> & { uuid: string; started_at: string }): TraceAiEvent {
+ return {
+ event: '$ai_generation',
+ ai_trace_id: TRACE_ID.toLowerCase(),
+ ai_span_id: null,
+ ai_parent_id: null,
+ span_name: null,
+ latency_seconds: 2,
+ model: 'model-x',
+ provider: 'provider-y',
+ input_tokens: 10,
+ output_tokens: 5,
+ total_cost_usd: 0.01,
+ is_error: false,
+ ...overrides,
+ }
+}
+
+// A run root that lasts a minute, one turn inside it, and one tool call inside the turn.
+const ROOT = span({ span_id: 'ROOT', timestamp: '2026-06-02T08:00:00.000Z', duration_nano: 60e9, is_root_span: true })
+const TURN = span({
+ span_id: 'TURN',
+ parent_span_id: 'ROOT',
+ timestamp: '2026-06-02T08:00:01.000Z',
+ duration_nano: 50e9,
+})
+const TOOL = span({
+ span_id: 'TOOL',
+ parent_span_id: 'TURN',
+ timestamp: '2026-06-02T08:00:10.000Z',
+ duration_nano: 1e9,
+})
+const SPANS = [ROOT, TURN, TOOL]
+
+describe('buildAiEventSpans', () => {
+ // A wrong end or a wrong parent puts the row in the wrong place on the waterfall.
+ it('runs the row a latency from its start and parents it to the narrowest containing span', () => {
+ const [result] = buildAiEventSpans([aiEvent({ uuid: 'e1', started_at: '2026-06-02T08:00:03.000Z' })], SPANS)
+
+ expect(result).toMatchObject({
+ span_id: 'ai:e1',
+ parent_span_id: 'TURN',
+ timestamp: '2026-06-02T08:00:03.000Z',
+ end_time: '2026-06-02T08:00:05.000Z',
+ duration_nano: 2e9,
+ name: 'model-x',
+ status_code: 1,
+ attributes: { 'ai.model': 'model-x', 'ai.input_tokens': '10' },
+ })
+ })
+
+ it.each([
+ // An OTel-sourced event names its parent, which wins over time containment.
+ ['a named parent that is loaded', { started_at: '2026-06-02T08:00:03.000Z', ai_parent_id: 'tool' }, 'TOOL'],
+ ['a named parent that is not loaded', { started_at: '2026-06-02T08:00:03.000Z', ai_parent_id: 'gone' }, 'TURN'],
+ // A call that ran past the turn's end is only contained by the root.
+ ['a call the turn does not contain', { started_at: '2026-06-02T08:00:45.000Z', latency_seconds: 10 }, 'ROOT'],
+ ['a call nothing contains', { started_at: '2026-06-02T08:02:00.000Z' }, ''],
+ ])('places %s', (_name, overrides, expectedParent) => {
+ const [result] = buildAiEventSpans([aiEvent({ uuid: 'e1', ...overrides })], SPANS)
+
+ expect(result.parent_span_id).toBe(expectedParent)
+ })
+
+ // OTel AI ingestion writes a wrapper span as an `$ai_span` event that the model call names as its
+ // parent, and a parent loop would make the waterfall drop the rows on it.
+ it.each([
+ [
+ 'under the loaded AI event its parent id names',
+ [
+ { uuid: 'wrap', event: '$ai_span', ai_span_id: 'wrap', latency_seconds: 4 },
+ { uuid: 'gen', ai_parent_id: 'wrap' },
+ ],
+ ['TURN', 'ai:wrap'],
+ ],
+ [
+ 'under the real span when a real span and an AI event share the named id',
+ [
+ { uuid: 'wrap', event: '$ai_span', ai_span_id: 'tool', latency_seconds: 4 },
+ { uuid: 'gen', ai_parent_id: 'tool' },
+ ],
+ ['TURN', 'TOOL'],
+ ],
+ ['a self-parented event by time', [{ uuid: 'a', ai_span_id: 'a', ai_parent_id: 'a' }], ['TURN']],
+ [
+ 'events that name each other by time',
+ [
+ { uuid: 'a', ai_span_id: 'a', ai_parent_id: 'b' },
+ { uuid: 'b', ai_span_id: 'b', ai_parent_id: 'a' },
+ ],
+ ['TURN', 'TURN'],
+ ],
+ ])('places %s', (_name, overrides, expectedParents) => {
+ const results = buildAiEventSpans(
+ overrides.map((override) => aiEvent({ started_at: '2026-06-02T08:00:02.000Z', ...override })),
+ SPANS
+ )
+
+ expect(results.map((r) => r.parent_span_id)).toEqual(expectedParents)
+ })
+
+ it('marks a failed call as an error and names an $ai_span by its span name', () => {
+ const results = buildAiEventSpans(
+ [
+ aiEvent({ uuid: 'e1', started_at: '2026-06-02T08:00:03.000Z', is_error: true }),
+ aiEvent({ uuid: 'e2', started_at: '2026-06-02T08:00:04.000Z', event: '$ai_span', span_name: 'plan' }),
+ ],
+ SPANS
+ )
+
+ expect(results.map((r) => [r.status_code, r.name])).toEqual([
+ [2, 'model-x'],
+ [1, 'plan'],
+ ])
+ })
+
+ // Merging twice must not parent new rows to earlier synthetic rows or emit rows without a trace.
+ it('ignores earlier synthetic rows and returns nothing without real spans', () => {
+ const first = buildAiEventSpans([aiEvent({ uuid: 'e1', started_at: '2026-06-02T08:00:03.000Z' })], SPANS)
+ const second = buildAiEventSpans(
+ [aiEvent({ uuid: 'e2', started_at: '2026-06-02T08:00:04.400Z', latency_seconds: 0.1 })],
+ [...SPANS, ...first]
+ )
+
+ expect(second[0].parent_span_id).toBe('TURN')
+ expect(buildAiEventSpans([aiEvent({ uuid: 'e3', started_at: '2026-06-02T08:00:03.000Z' })], [])).toEqual([])
+ })
+})
diff --git a/products/tracing/frontend/aiEventSpans.ts b/products/tracing/frontend/aiEventSpans.ts
new file mode 100644
index 000000000000..612569af5dc7
--- /dev/null
+++ b/products/tracing/frontend/aiEventSpans.ts
@@ -0,0 +1,172 @@
+import { dayjs } from 'lib/dayjs'
+
+import type { _TracingTraceAiEventApi } from './generated/api.schemas'
+import type { Span } from './types'
+
+export type TraceAiEvent = _TracingTraceAiEventApi
+
+/** The service name synthetic AI rows carry, so they get one color and one label in the waterfall. */
+export const AI_EVENT_SERVICE_NAME = 'llm'
+
+const AI_SPAN_ID_PREFIX = 'ai:'
+const SPAN_KIND_CLIENT = 3
+
+export function isAiEventSpan(span: Span): boolean {
+ return span.span_id.startsWith(AI_SPAN_ID_PREFIX)
+}
+
+interface Interval {
+ startMs: number
+ endMs: number
+}
+
+interface ParentCandidates {
+ byId: Map<string, Span>
+ intervals: (Interval & { span: Span })[]
+}
+
+function spanInterval(span: Span): Interval {
+ const startMs = dayjs(span.timestamp).valueOf()
+ return { startMs, endMs: startMs + span.duration_nano / 1_000_000 }
+}
+
+function aiEventInterval(event: TraceAiEvent): Interval {
+ const startMs = dayjs(event.started_at).valueOf()
+ const latencyMs = Math.max(event.latency_seconds ?? 0, 0) * 1000
+ return { startMs, endMs: startMs + latencyMs }
+}
+
+/**
+ * The real span the AI event belongs under. An OpenTelemetry-sourced event names its parent span,
+ * so that wins when the span is loaded. Otherwise the narrowest real span whose time range
+ * contains the event, so a model call lands under the turn or request that made it.
+ */
+function findParentSpan(event: TraceAiEvent, candidates: ParentCandidates, interval: Interval): Span | null {
+ const parentId = event.ai_parent_id?.toLowerCase()
+ const named = parentId ? candidates.byId.get(parentId) : undefined
+ if (named) {
+ return named
+ }
+ let best: Span | null = null
+ let bestDurationNano = Number.POSITIVE_INFINITY
+ for (const { span, startMs, endMs } of candidates.intervals) {
+ if (startMs <= interval.startMs && endMs >= interval.endMs && span.duration_nano < bestDurationNano) {
+ best = span
+ bestDurationNano = span.duration_nano
+ }
+ }
+ return best
+}
+
+// Parse each span once, not once per AI event, because a trace can load thousands of spans.
+function parentCandidates(spans: Span[]): ParentCandidates {
+ const byId = new Map<string, Span>()
+ for (const span of spans) {
+ const id = span.span_id.toLowerCase()
+ if (!byId.has(id)) {
+ byId.set(id, span)
+ }
+ }
+ return { byId, intervals: spans.map((span) => ({ span, ...spanInterval(span) })) }
+}
+
+/**
+ * Map each AI event to the loaded AI event its `ai_parent_id` names, when no real span has that id.
+ * OpenTelemetry AI ingestion writes a wrapper span such as `ai.generateText` as an `$ai_span`
+ * event, and the model call under it names that event's span id as its parent.
+ */
+function findAiParents(events: TraceAiEvent[], realSpanIds: Set<string>): Map<string, string> {
+ const uuidBySpanId = new Map<string, string>()
+ for (const event of events) {
+ if (event.ai_span_id) {
+ uuidBySpanId.set(event.ai_span_id.toLowerCase(), event.uuid)
+ }
+ }
+ const parents = new Map<string, string>()
+ for (const event of events) {
+ const parentId = event.ai_parent_id?.toLowerCase()
+ const parentUuid = parentId && !realSpanIds.has(parentId) ? uuidBySpanId.get(parentId) : undefined
+ if (parentUuid) {
+ parents.set(event.uuid, parentUuid)
+ }
+ }
+ // The waterfall drops every row on a parent loop, so a self-parented or cyclic event falls back to
+ // time containment instead.
+ return new Map([...parents].filter(([uuid]) => !isOnCycle(uuid, parents)))
+}
+
+function isOnCycle(uuid: string, parents: Map<string, string>): boolean {
+ const seen = new Set<string>()
+ for (let current = parents.get(uuid); current !== undefined && !seen.has(current); current = parents.get(current)) {
+ if (current === uuid) {
+ return true
+ }
+ seen.add(current)
+ }
+ return false
+}
+
+function eventName(event: TraceAiEvent): string {
+ if (event.event === '$ai_span') {
+ return event.span_name ?? 'span'
+ }
+ return event.model ?? event.event
+}
+
+function eventAttributes(event: TraceAiEvent): Record<string, string> {
+ const attributes: Record<string, string> = { 'ai.event': event.event }
+ const optional: Record<string, string | number | null | undefined> = {
+ 'ai.model': event.model,
+ 'ai.provider': event.provider,
+ 'ai.input_tokens': event.input_tokens,
+ 'ai.output_tokens': event.output_tokens,
+ 'ai.total_cost_usd': event.total_cost_usd,
+ 'ai.trace_id': event.ai_trace_id,
+ 'ai.span_id': event.ai_span_id,
+ 'ai.parent_id': event.ai_parent_id,
+ }
+ for (const [key, value] of Object.entries(optional)) {
+ if (value !== null && value !== undefined) {
+ attributes[key] = String(value)
+ }
+ }
+ return attributes
+}
+
+/**
+ * Turn a trace's AI events into spans the waterfall can draw next to the real ones. Each row sits
+ * under the real span or AI event its parent id names, or else under the real span that contains
+ * it in time, because the two datasets share a trace id but often no span ids.
+ */
+export function buildAiEventSpans(events: TraceAiEvent[], spans: Span[]): Span[] {
+ if (events.length === 0 || spans.length === 0) {
+ return []
+ }
+ const traceId = spans[0].trace_id
+ const candidates = parentCandidates(spans.filter((span) => !isAiEventSpan(span)))
+ const aiParents = findAiParents(events, new Set(candidates.byId.keys()))
+ return events.map((event): Span => {
+ const interval = aiEventInterval(event)
+ const aiParentUuid = aiParents.get(event.uuid)
+ const parentSpanId = aiParentUuid
+ ? `${AI_SPAN_ID_PREFIX}${aiParentUuid}`
+ : (findParentSpan(event, candidates, interval)?.span_id ?? '')
+ return {
+ uuid: event.uuid,
+ trace_id: traceId,
+ span_id: `${AI_SPAN_ID_PREFIX}${event.uuid}`,
+ parent_span_id: parentSpanId,
+ name: eventName(event),
+ kind: SPAN_KIND_CLIENT,
+ service_name: AI_EVENT_SERVICE_NAME,
+ status_code: event.is_error ? 2 : 1,
+ timestamp: dayjs(interval.startMs).toISOString(),
+ end_time: dayjs(interval.endMs).toISOString(),
+ duration_nano: (interval.endMs - interval.startMs) * 1_000_000,
+ is_root_span: false,
+ matched_filter: true,
+ attributes: eventAttributes(event),
+ resource_attributes: {},
+ }
+ })
+}
diff --git a/products/tracing/frontend/components/TraceDrawer/SpanLogsTab.test.tsx b/products/tracing/frontend/components/TraceDrawer/SpanLogsTab.test.tsx
index f3e8289d748e..d1335026f3b6 100644
--- a/products/tracing/frontend/components/TraceDrawer/SpanLogsTab.test.tsx
+++ b/products/tracing/frontend/components/TraceDrawer/SpanLogsTab.test.tsx
@@ -1,4 +1,4 @@
-import { render } from '@testing-library/react'
+import { fireEvent, render, within } from '@testing-library/react'
import type { Span } from '../../types'
import { SpanLogsTab } from './SpanLogsTab'
@@ -37,4 +37,15 @@ describe('SpanLogsTab', () => {
expect(second.pinnedFilters).toBe(first.pinnedFilters)
expect(second.initialFilters).toBe(first.initialFilters)
})
+
+ it('keeps an AI row on the trace scope after span scope was picked on a real span', () => {
+ const { container, rerender } = render(<SpanLogsTab span={span} />)
+ fireEvent.click(within(container).getAllByText('This span')[0])
+
+ rerender(<SpanLogsTab span={{ ...span, span_id: 'ai:event-1' }} />)
+
+ expect(capturedProps[capturedProps.length - 1].pinnedFilters).toMatchObject({
+ values: [{ key: 'trace_id', value: ['trace-abc'] }],
+ })
+ })
})
diff --git a/products/tracing/frontend/components/TraceDrawer/SpanLogsTab.tsx b/products/tracing/frontend/components/TraceDrawer/SpanLogsTab.tsx
index a348c375e81e..9978a28c93fe 100644
--- a/products/tracing/frontend/components/TraceDrawer/SpanLogsTab.tsx
+++ b/products/tracing/frontend/components/TraceDrawer/SpanLogsTab.tsx
@@ -7,6 +7,7 @@ import { dayjs } from 'lib/dayjs'
import { LogsViewer } from 'products/logs/frontend/components/LogsViewer/LogsViewer'
+import { isAiEventSpan } from '../../aiEventSpans'
import { traceLookupDateRange } from '../../traceLinks'
import { buildLogScopeFilter, logsDeepLinkUrl, type TraceLogScope } from '../../traceLogScope'
import type { Span } from '../../types'
@@ -17,6 +18,12 @@ import type { Span } from '../../types'
// scope — the viewer's own filters can only narrow within it — and this toggle is the scope control.
export function SpanLogsTab({ span }: { span: Span }): JSX.Element {
const [scope, setScope] = useState<TraceLogScope>('trace')
+ // An AI row has no OTel span id to match logs on, so it stays on the trace even when the
+ // user picked "This span" on a real span. The pick comes back when they select a real span.
+ const spanScopeDisabledReason = isAiEventSpan(span)
+ ? "AI events don't have their own span, so logs show for the whole trace"
+ : undefined
+ const effectiveScope: TraceLogScope = spanScopeDisabledReason ? 'trace' : scope
// `initialFilters` (the date range) is stable across scope changes — recompute only when the
// span timestamp changes. Otherwise a scope toggle would mint a fresh `initialFilters` object;
@@ -32,10 +39,10 @@ export function SpanLogsTab({ span }: { span: Span }): JSX.Element {
const ids = useMemo(() => ({ traceId: span.trace_id, spanId: span.span_id }), [span.trace_id, span.span_id])
const { pinnedFilters, deepLink } = useMemo(
() => ({
- pinnedFilters: buildLogScopeFilter(scope, ids),
- deepLink: logsDeepLinkUrl(scope, ids, dateRange),
+ pinnedFilters: buildLogScopeFilter(effectiveScope, ids),
+ deepLink: logsDeepLinkUrl(effectiveScope, ids, dateRange),
}),
- [scope, ids, dateRange]
+ [effectiveScope, ids, dateRange]
)
return (
@@ -43,11 +50,11 @@ export function SpanLogsTab({ span }: { span: Span }): JSX.Element {
<div className="flex items-center justify-between gap-2">
<LemonSegmentedButton
size="xsmall"
- value={scope}
+ value={effectiveScope}
onChange={setScope}
options={[
{ value: 'trace', label: 'Whole trace' },
- { value: 'span', label: 'This span' },
+ { value: 'span', label: 'This span', disabledReason: spanScopeDisabledReason },
]}
data-attr="tracing-logs-scope"
/>
diff --git a/products/tracing/frontend/components/TraceDrawer/SpanMetricsTab.test.tsx b/products/tracing/frontend/components/TraceDrawer/SpanMetricsTab.test.tsx
index be52e205fee2..6b9eb0b3b47a 100644
--- a/products/tracing/frontend/components/TraceDrawer/SpanMetricsTab.test.tsx
+++ b/products/tracing/frontend/components/TraceDrawer/SpanMetricsTab.test.tsx
@@ -1,6 +1,6 @@
import '@testing-library/jest-dom'
-import { fireEvent, render, screen } from '@testing-library/react'
+import { fireEvent, render, screen, within } from '@testing-library/react'
import { Provider } from 'kea'
import { FEATURE_FLAGS } from 'lib/constants'
@@ -74,6 +74,24 @@ describe('SpanMetricsTab', () => {
expect(props.spanId).toBe('span-xyz')
})
+ it('keeps an AI row on the trace scope and hides its synthetic service link', () => {
+ const { container, rerender } = render(
+ <Provider>
+ <SpanMetricsTab span={span} />
+ </Provider>
+ )
+ fireEvent.click(within(container).getAllByText('This span')[0])
+
+ rerender(
+ <Provider>
+ <SpanMetricsTab span={{ ...span, span_id: 'ai:event-1', service_name: 'llm' }} />
+ </Provider>
+ )
+
+ expect(capturedProps[capturedProps.length - 1].spanId).toBeNull()
+ expect(within(container).queryByText('View metrics')).toBeNull()
+ })
+
it('links to the span service metrics over the trace window', () => {
render(
<Provider>
diff --git a/products/tracing/frontend/components/TraceDrawer/SpanMetricsTab.tsx b/products/tracing/frontend/components/TraceDrawer/SpanMetricsTab.tsx
index b200baffde79..0b557c45ddca 100644
--- a/products/tracing/frontend/components/TraceDrawer/SpanMetricsTab.tsx
+++ b/products/tracing/frontend/components/TraceDrawer/SpanMetricsTab.tsx
@@ -7,6 +7,7 @@ import { dayjs } from 'lib/dayjs'
import { TraceMetricSamples } from 'products/metrics/frontend/components/TraceMetricSamples'
import { ViewServiceMetricsButton } from 'products/metrics/frontend/components/ViewServiceMetricsButton'
+import { isAiEventSpan } from '../../aiEventSpans'
import { traceLookupDateRange } from '../../traceLinks'
import type { Span } from '../../types'
@@ -17,6 +18,10 @@ type TraceMetricScope = 'trace' | 'span'
// its own; narrow to the span with the toggle when needed.
export function SpanMetricsTab({ span }: { span: Span }): JSX.Element {
const [scope, setScope] = useState<TraceMetricScope>('trace')
+ // An AI row has no OTel span id to match exemplars on and no real service to pivot to, so it
+ // stays on the trace and hides the service link.
+ const isAiRow = isAiEventSpan(span)
+ const effectiveScope: TraceMetricScope = isAiRow ? 'trace' : scope
// The samples endpoint needs a concrete ISO window; ±1h around the span covers any of
// its emissions (same window cold trace loads use). Keyed by span timestamp so selecting
@@ -32,11 +37,17 @@ export function SpanMetricsTab({ span }: { span: Span }): JSX.Element {
<div className="flex items-center justify-between gap-2">
<LemonSegmentedButton
size="xsmall"
- value={scope}
+ value={effectiveScope}
onChange={setScope}
options={[
{ value: 'trace', label: 'Whole trace' },
- { value: 'span', label: 'This span' },
+ {
+ value: 'span',
+ label: 'This span',
+ disabledReason: isAiRow
+ ? "AI events don't have their own span, so metrics show for the whole trace"
+ : undefined,
+ },
]}
data-attr="tracing-metrics-scope"
/>
@@ -44,7 +55,7 @@ export function SpanMetricsTab({ span }: { span: Span }): JSX.Element {
answers "what was the host doing" by opening the service's own metric charts
over the same window. */}
<ViewServiceMetricsButton
- serviceName={span.service_name}
+ serviceName={isAiRow ? null : span.service_name}
dateFrom={dateRange.date_from}
dateTo={dateRange.date_to}
size="xsmall"
@@ -54,7 +65,7 @@ export function SpanMetricsTab({ span }: { span: Span }): JSX.Element {
</div>
<TraceMetricSamples
traceId={span.trace_id}
- spanId={scope === 'span' ? span.span_id : null}
+ spanId={effectiveScope === 'span' ? span.span_id : null}
dateFrom={dateRange.date_from}
dateTo={dateRange.date_to}
/>
diff --git a/products/tracing/frontend/components/TraceDrawer/TraceAiEventsCapNotice.stories.tsx b/products/tracing/frontend/components/TraceDrawer/TraceAiEventsCapNotice.stories.tsx
new file mode 100644
index 000000000000..015471715f92
--- /dev/null
+++ b/products/tracing/frontend/components/TraceDrawer/TraceAiEventsCapNotice.stories.tsx
@@ -0,0 +1,48 @@
+import { Meta, StoryObj } from '@storybook/react'
+
+import { TraceAiEventsCapNotice } from './TraceAiEventsCapNotice'
+
+const meta: Meta<typeof TraceAiEventsCapNotice> = {
+ title: 'Products/Tracing/TraceAiEventsCapNotice',
+ component: TraceAiEventsCapNotice,
+ args: {
+ hasMore: true,
+ limit: 500,
+ aiEvents: [
+ {
+ uuid: '0190a1b2-0000-7000-8000-000000000001',
+ event: '$ai_generation',
+ started_at: '2026-06-02T08:00:03.000Z',
+ ai_trace_id: '4bf92f3577b34da6a3ce929d0e0e4736',
+ ai_span_id: null,
+ ai_parent_id: null,
+ span_name: null,
+ latency_seconds: 2,
+ model: 'model-x',
+ provider: 'provider-y',
+ input_tokens: 10,
+ output_tokens: 5,
+ total_cost_usd: 0.01,
+ is_error: false,
+ },
+ ],
+ },
+ decorators: [
+ (Story) => (
+ // The snapshot root shrinks to its content, so a full-width banner needs a set width.
+ <div className="w-[720px]">
+ <Story />
+ </div>
+ ),
+ ],
+ parameters: {
+ layout: 'padded',
+ viewMode: 'story',
+ },
+ tags: ['autodocs'],
+}
+export default meta
+
+type Story = StoryObj<typeof TraceAiEventsCapNotice>
+
+export const PastTheCap: Story = {}
diff --git a/products/tracing/frontend/components/TraceDrawer/TraceAiEventsCapNotice.tsx b/products/tracing/frontend/components/TraceDrawer/TraceAiEventsCapNotice.tsx
new file mode 100644
index 000000000000..d633bb4a0807
--- /dev/null
+++ b/products/tracing/frontend/components/TraceDrawer/TraceAiEventsCapNotice.tsx
@@ -0,0 +1,31 @@
+import { LemonBanner } from '@posthog/lemon-ui'
+
+import { urls } from 'scenes/urls'
+
+import type { TraceAiEvent } from '../../aiEventSpans'
+
+export interface TraceAiEventsCapNoticeProps {
+ aiEvents: TraceAiEvent[]
+ hasMore: boolean
+ limit: number
+}
+
+export function TraceAiEventsCapNotice({ aiEvents, hasMore, limit }: TraceAiEventsCapNoticeProps): JSX.Element | null {
+ if (!hasMore || aiEvents.length === 0) {
+ return null
+ }
+ return (
+ <LemonBanner
+ type="info"
+ className="mb-2"
+ action={{
+ children: 'View all in AI observability',
+ to: urls.aiObservabilityTrace(aiEvents[0].ai_trace_id),
+ targetBlank: true,
+ 'data-attr': 'tracing-ai-events-view-all',
+ }}
+ >
+ This trace has more than {limit} AI events. The waterfall shows the first {limit}.
+ </LemonBanner>
+ )
+}
diff --git a/products/tracing/frontend/components/TraceDrawer/TraceDrawer.tsx b/products/tracing/frontend/components/TraceDrawer/TraceDrawer.tsx
index d404f6e6aebd..6cc13a0f127d 100644
--- a/products/tracing/frontend/components/TraceDrawer/TraceDrawer.tsx
+++ b/products/tracing/frontend/components/TraceDrawer/TraceDrawer.tsx
@@ -16,6 +16,7 @@ import { cn } from 'lib/utils/css-classes'
import { canViewMetrics } from 'products/metrics/frontend/metricsAccess'
+import { buildAiEventSpans, isAiEventSpan } from '../../aiEventSpans'
import type { ErrorScope } from '../../errorCorrelation'
import { useKeepMountedWhileOpen } from '../../hooks/useKeepMountedWhileOpen'
import { getQueryText } from '../../spanSummary'
@@ -27,6 +28,8 @@ import { ExpandedSpanContent } from '../VirtualizedSpanList/ExpandedSpanContent'
import { SpanLogsTab } from './SpanLogsTab'
import { SpanMetricsTab } from './SpanMetricsTab'
import { SpanSummaryHeader } from './SpanSummaryHeader'
+import { TraceAiEventsCapNotice } from './TraceAiEventsCapNotice'
+import { traceAiEventsLogic } from './traceAiEventsLogic'
import { TraceErrorsTab } from './TraceErrorsTab'
import { TraceIdentityChips } from './TraceIdentityChips'
@@ -70,7 +73,7 @@ export function TraceDrawer({
isOpen,
traceId,
ts,
- spans,
+ spans: realSpans,
identity,
sessionId,
showErrorsTab,
@@ -85,6 +88,12 @@ export function TraceDrawer({
onSelectSpan,
onClose,
}: TraceDrawerProps): JSX.Element | null {
+ const { aiEvents, hasMoreAiEvents, aiEventsLimit } = useValues(traceAiEventsLogic({ traceId }))
+ // The waterfall and the inspector read one list, so an AI row selects and inspects like a span.
+ const spans = useMemo(() => {
+ const aiEventSpans = buildAiEventSpans(aiEvents, realSpans)
+ return aiEventSpans.length > 0 ? [...realSpans, ...aiEventSpans] : realSpans
+ }, [realSpans, aiEvents])
// Waterfall|inspector split. Persisted so a user's preferred split sticks across traces;
// desiredSize is null until the first drag, leaving the responsive default (w-2/5) in place.
// One props object feeds both the value-read and the <Resizer>, so the logicKey can't desync.
@@ -167,6 +176,7 @@ export function TraceDrawer({
<div className="relative min-h-32 flex gap-4 items-start">
{loading && <SpinnerOverlay />}
<div className="flex-1 min-w-0">
+ <TraceAiEventsCapNotice aiEvents={aiEvents} hasMore={hasMoreAiEvents} limit={aiEventsLimit} />
{/* Keyed by trace so a new trace resets selection + scroll state. */}
<TraceWaterfallView
key={traceId ?? ''}
@@ -242,7 +252,10 @@ export function TraceDrawer({
<TraceErrorsTab
key={inspectedSpan.span_id}
traceId={inspectedSpan.trace_id}
- spanId={inspectedSpan.span_id}
+ // A synthetic AI row has no OTel span id, so it scopes to the trace.
+ spanId={
+ isAiEventSpan(inspectedSpan) ? null : inspectedSpan.span_id
+ }
timestamp={rootSpan?.timestamp ?? inspectedSpan.timestamp ?? ts}
sessionId={sessionId}
initialScope={errorsScope}
diff --git a/products/tracing/frontend/components/TraceDrawer/traceAiEventsLogic.test.ts b/products/tracing/frontend/components/TraceDrawer/traceAiEventsLogic.test.ts
new file mode 100644
index 000000000000..a82c7a296581
--- /dev/null
+++ b/products/tracing/frontend/components/TraceDrawer/traceAiEventsLogic.test.ts
@@ -0,0 +1,76 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
+import { initKeaTests } from '~/test/init'
+
+import { tracingSpansTraceAiEventsRetrieve } from 'products/tracing/frontend/generated/api'
+
+import { traceAiEventsLogic, TraceAiEventsLogicProps } from './traceAiEventsLogic'
+
+jest.mock('products/tracing/frontend/generated/api', () => ({
+ tracingSpansTraceAiEventsRetrieve: jest.fn(),
+}))
+
+const mockAiEventsRetrieve = tracingSpansTraceAiEventsRetrieve as jest.MockedFunction<
+ typeof tracingSpansTraceAiEventsRetrieve
+>
+
+// Spans read their ids back as uppercase hex, while the SDKs write them lowercase.
+const PROPS: TraceAiEventsLogicProps = {
+ traceId: '4BF92F3577B34DA6A3CE929D0E0E4736',
+}
+
+describe('traceAiEventsLogic', () => {
+ let logic: ReturnType<typeof traceAiEventsLogic.build>
+
+ const mount = async (props: Partial<TraceAiEventsLogicProps> = {}, flagOn = true): Promise<void> => {
+ featureFlagLogic.mount()
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.TRACING_AI_EVENTS]: flagOn })
+ logic = traceAiEventsLogic({ ...PROPS, ...props })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ }
+
+ beforeEach(() => {
+ initKeaTests()
+ mockAiEventsRetrieve.mockReset()
+ mockAiEventsRetrieve.mockResolvedValue({ results: [], has_more: false, limit: 500 })
+ })
+
+ afterEach(() => {
+ logic?.unmount()
+ })
+
+ it('asks for the events of the trace by its lowercase id and keeps the cap marker', async () => {
+ mockAiEventsRetrieve.mockResolvedValue({ results: [], has_more: true, limit: 500 })
+ await mount()
+
+ expect(mockAiEventsRetrieve).toHaveBeenCalledTimes(1)
+ expect(mockAiEventsRetrieve.mock.calls[0][1]).toBe(PROPS.traceId!.toLowerCase())
+ expect(logic.values.hasMoreAiEvents).toBe(true)
+ })
+
+ // On a cold page load the flag can arrive from posthog-js after the trace has loaded.
+ it('fetches once the flag turns on after mount', async () => {
+ await mount({}, false)
+
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.TRACING_AI_EVENTS]: true })
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(mockAiEventsRetrieve).toHaveBeenCalledTimes(1)
+ })
+
+ // The endpoint must stay uncalled while the flag is off, and for an all-zero id, which is
+ // OpenTelemetry's "no id" sentinel.
+ it.each([
+ ['the flag off', {}, false],
+ ['an all-zero trace id', { traceId: '0'.repeat(32) }, true],
+ ])('fetches nothing with %s', async (_name, props, flagOn) => {
+ await mount(props, flagOn)
+
+ expect(mockAiEventsRetrieve).not.toHaveBeenCalled()
+ expect(logic.values.aiEvents).toEqual([])
+ })
+})
diff --git a/products/tracing/frontend/components/TraceDrawer/traceAiEventsLogic.ts b/products/tracing/frontend/components/TraceDrawer/traceAiEventsLogic.ts
new file mode 100644
index 000000000000..7ac7c02a3a92
--- /dev/null
+++ b/products/tracing/frontend/components/TraceDrawer/traceAiEventsLogic.ts
@@ -0,0 +1,123 @@
+import { MakeLogicType, connect, kea, key, path, props, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+import { subscriptions } from 'kea-subscriptions'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { type FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { teamLogic } from 'scenes/teamLogic'
+
+import type { TraceAiEvent } from '../../aiEventSpans'
+import { usableId } from '../../errorCorrelation'
+import { tracingSpansTraceAiEventsRetrieve } from '../../generated/api'
+import type { _TracingTraceAiEventsResponseApi } from '../../generated/api.schemas'
+
+export interface TraceAiEventsLogicProps {
+ traceId: string | null
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface traceAiEventsLogicValues {
+ featureFlags: FeatureFlagsSet // featureFlagLogic
+ currentTeamId: number | null // teamLogic
+ aiEvents: TraceAiEvent[]
+ aiEventsEnabled: boolean
+ aiEventsLimit: number
+ aiEventsResponse: _TracingTraceAiEventsResponseApi
+ aiEventsResponseLoading: boolean
+ hasMoreAiEvents: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface traceAiEventsLogicActions {
+ loadAiEvents: () => any
+ loadAiEventsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadAiEventsSuccess: (
+ aiEventsResponse: _TracingTraceAiEventsResponseApi,
+ payload?: any
+ ) => {
+ aiEventsResponse: _TracingTraceAiEventsResponseApi
+ payload?: any
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface traceAiEventsLogicMeta {
+ key: string
+ __keaTypeGenInternalSelectorTypes: {
+ aiEventsEnabled: (featureFlags: FeatureFlagsSet) => boolean
+ aiEvents: (aiEventsResponse: _TracingTraceAiEventsResponseApi) => TraceAiEvent[]
+ hasMoreAiEvents: (aiEventsResponse: _TracingTraceAiEventsResponseApi) => boolean
+ aiEventsLimit: (aiEventsResponse: _TracingTraceAiEventsResponseApi) => number
+ }
+}
+
+export type traceAiEventsLogicType = MakeLogicType<
+ traceAiEventsLogicValues,
+ traceAiEventsLogicActions,
+ TraceAiEventsLogicProps,
+ traceAiEventsLogicMeta
+>
+
+const EMPTY_RESPONSE: _TracingTraceAiEventsResponseApi = { results: [], has_more: false, limit: 0 }
+
+// The events half of the trace-to-AI-events join. The spans and the AI events sit on different
+// ClickHouse clusters, so the backend cannot join them in one query; this fetches the events by
+// trace id and the drawer places them on the waterfall by time.
+export const traceAiEventsLogic = kea<traceAiEventsLogicType>([
+ props({} as TraceAiEventsLogicProps),
+ key((props) => props.traceId ?? ''),
+ path((key) => ['products', 'tracing', 'frontend', 'components', 'TraceDrawer', 'traceAiEventsLogic', key]),
+
+ connect(() => ({
+ values: [teamLogic, ['currentTeamId'], featureFlagLogic, ['featureFlags']],
+ })),
+
+ loaders(({ props, values }) => ({
+ aiEventsResponse: {
+ __default: EMPTY_RESPONSE,
+ loadAiEvents: async (): Promise<_TracingTraceAiEventsResponseApi> => {
+ const traceId = usableId(props.traceId)
+ const teamId = values.currentTeamId
+ if (!values.featureFlags[FEATURE_FLAGS.TRACING_AI_EVENTS] || !traceId || teamId === null) {
+ return EMPTY_RESPONSE
+ }
+ return await tracingSpansTraceAiEventsRetrieve(String(teamId), traceId)
+ },
+ },
+ })),
+
+ selectors({
+ aiEventsEnabled: [
+ (s) => [s.featureFlags],
+ (featureFlags: FeatureFlagsSet): boolean => !!featureFlags[FEATURE_FLAGS.TRACING_AI_EVENTS],
+ ],
+ aiEvents: [
+ (s) => [s.aiEventsResponse],
+ (response: _TracingTraceAiEventsResponseApi): TraceAiEvent[] => response.results,
+ ],
+ hasMoreAiEvents: [
+ (s) => [s.aiEventsResponse],
+ (response: _TracingTraceAiEventsResponseApi): boolean => response.has_more,
+ ],
+ aiEventsLimit: [
+ (s) => [s.aiEventsResponse],
+ (response: _TracingTraceAiEventsResponseApi): number => response.limit,
+ ],
+ }),
+
+ subscriptions(({ actions }) => ({
+ // Runs on mount and again when the flag turns on, because on a cold page load the flag can
+ // arrive from posthog-js after the trace has loaded.
+ aiEventsEnabled: (enabled: boolean) => {
+ if (enabled) {
+ actions.loadAiEvents()
+ }
+ },
+ })),
+])
diff --git a/products/tracing/frontend/components/VirtualizedSpanList/ExpandedSpanContent.tsx b/products/tracing/frontend/components/VirtualizedSpanList/ExpandedSpanContent.tsx
index e968ec1773f5..6702aaac2f11 100644
--- a/products/tracing/frontend/components/VirtualizedSpanList/ExpandedSpanContent.tsx
+++ b/products/tracing/frontend/components/VirtualizedSpanList/ExpandedSpanContent.tsx
@@ -1,5 +1,6 @@
import { PropertyFilterType } from '~/types'
+import { isAiEventSpan } from '../../aiEventSpans'
import { formatDuration } from '../../TraceWaterfallView'
import { SPAN_KIND_LABELS, STATUS_CODE_LABELS } from '../../types'
import type { Span } from '../../types'
@@ -39,6 +40,9 @@ export function ExpandedSpanContent({ span, showDetails = true }: ExpandedSpanCo
title="Attributes"
attributes={attributes}
emptyLabel="No attributes set on this span"
+ // An AI row's attributes come from LLM analytics events, not trace_spans, so a span
+ // attribute filter built from them matches no span and empties the span list.
+ showFilterActions={!isAiEventSpan(span)}
propertyType={PropertyFilterType.SpanAttribute}
/>
{/* Sibling section after the span attributes — same split the logs detail view uses.
diff --git a/products/tracing/frontend/generated/api.schemas.ts b/products/tracing/frontend/generated/api.schemas.ts
index fa29a149a31d..ad5782e73adc 100644
--- a/products/tracing/frontend/generated/api.schemas.ts
+++ b/products/tracing/frontend/generated/api.schemas.ts
@@ -1028,8 +1028,12 @@ export interface _TracingTraceAiEventApi {
}
export interface _TracingTraceAiEventsResponseApi {
- /** AI events in the trace, earliest start first. */
+ /** AI events in the trace, earliest start first, up to `limit` of them. */
results: _TracingTraceAiEventApi[]
+ /** The most AI events the lookup returns for one trace. */
+ limit: number
+ /** Whether the trace has more AI events than `results` holds. The full list is in AI observability under the events' `ai_trace_id`. */
+ has_more: boolean
}
export interface _TracingTreeQueryBodyApi {
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 54824070f19e..5321817d7f17 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -105807,8 +105807,12 @@ export namespace Schemas {
}
export interface _TracingTraceAiEventsResponse {
- /** AI events in the trace, earliest start first. */
+ /** AI events in the trace, earliest start first, up to `limit` of them. */
results: _TracingTraceAiEvent[];
+ /** The most AI events the lookup returns for one trace. */
+ limit: number;
+ /** Whether the trace has more AI events than `results` holds. The full list is in AI observability under the events' `ai_trace_id`. */
+ has_more: boolean;
}
export interface _TracingTraceRequest {