Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(aio): stop generations table columns loading forever (#90482)

posthog[bot]c6aeffccb621
diff --git a/products/ai_observability/frontend/aiObservabilityAIDataLogic.test.ts b/products/ai_observability/frontend/aiObservabilityAIDataLogic.test.ts
index 4996e8ac2b0b..29a7d06b4f70 100644
--- a/products/ai_observability/frontend/aiObservabilityAIDataLogic.test.ts
+++ b/products/ai_observability/frontend/aiObservabilityAIDataLogic.test.ts
@@ -1,5 +1,3 @@
-import { expectLogic } from 'kea-test-utils'
-
import api from '~/lib/api'
import { initKeaTests } from '~/test/init'
@@ -9,38 +7,52 @@ jest.mock('~/lib/api')
const mockApi = api as jest.Mocked<typeof api>
+// A row as the heavy-prop query returns it:
+// [uuid, input, output, output_choices, input_state, output_state, tools].
+type Row = [string, unknown, unknown, unknown, unknown, unknown, unknown]
+
+// Let the listener's setTimeout(0) batch timer fire, then take one more macrotask turn so the
+// query + merge chain settles regardless of its await depth.
+async function settle(): Promise<void> {
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ await new Promise((resolve) => setTimeout(resolve, 0))
+}
+
describe('aiObservabilityAIDataLogic', () => {
+ let logic: ReturnType<typeof aiObservabilityAIDataLogic.build>
+
beforeEach(() => {
jest.resetAllMocks()
initKeaTests()
+ logic = aiObservabilityAIDataLogic()
+ logic.mount()
})
- it('passes through when both input and output are already present — no heavy-prop lookup', async () => {
- const logic = aiObservabilityAIDataLogic()
- logic.mount()
+ afterEach(() => {
+ logic.unmount()
+ })
- await expectLogic(logic, () => {
- logic.actions.loadAIDataForEvent({
+ it('passes through when both input and output are already present — no heavy-prop lookup', async () => {
+ logic.actions.ensureAIDataLoaded([
+ {
eventId: 'event-1',
input: [{ role: 'user', content: 'hi' }],
output: [{ role: 'assistant', content: 'hello' }],
tools: undefined,
traceId: 'trace-1',
timestamp: '2026-04-30T10:00:00Z',
- })
- })
- .toFinishAllListeners()
- .toMatchValues({
- aiDataCache: {
- 'event-1': {
- input: [{ role: 'user', content: 'hi' }],
- output: [{ role: 'assistant', content: 'hello' }],
- tools: undefined,
- },
- },
- })
+ },
+ ])
+ await settle()
- expect(mockApi.query).not.toHaveBeenCalled()
+ expect(logic.values.aiDataCache).toEqual({
+ 'event-1': {
+ input: [{ role: 'user', content: 'hi' }],
+ output: [{ role: 'assistant', content: 'hello' }],
+ tools: undefined,
+ },
+ })
+ expect(logic.values.isEventLoading('event-1')).toBe(false)
expect(mockApi.queryHogQL).not.toHaveBeenCalled()
})
@@ -48,43 +60,36 @@ describe('aiObservabilityAIDataLogic', () => {
jest.spyOn(mockApi, 'queryHogQL').mockResolvedValue({
results: [
[
+ 'event-1',
JSON.stringify([{ role: 'user', content: 'post-strip hi' }]),
null,
JSON.stringify([{ role: 'assistant', content: 'post-strip hello' }]),
null,
null,
JSON.stringify([{ function: { name: 'search' } }]),
- ],
+ ] as Row,
],
} as any)
- const logic = aiObservabilityAIDataLogic()
- logic.mount()
-
- await expectLogic(logic, () => {
- logic.actions.loadAIDataForEvent({
+ logic.actions.ensureAIDataLoaded([
+ {
eventId: 'event-1',
input: undefined,
output: undefined,
tools: undefined,
traceId: 'trace-1',
timestamp: '2026-04-30T10:00:00Z',
- })
- })
- .toFinishAllListeners()
- .toMatchValues({
- aiDataCache: {
- 'event-1': {
- input: [{ role: 'user', content: 'post-strip hi' }],
- output: [{ role: 'assistant', content: 'post-strip hello' }],
- tools: [{ function: { name: 'search' } }],
- },
- },
- })
+ },
+ ])
+ await settle()
+ expect(logic.values.aiDataCache['event-1']).toEqual({
+ input: [{ role: 'user', content: 'post-strip hi' }],
+ output: [{ role: 'assistant', content: 'post-strip hello' }],
+ tools: [{ function: { name: 'search' } }],
+ })
expect(mockApi.queryHogQL).toHaveBeenCalledTimes(1)
expect(mockApi.queryHogQL.mock.calls[0][0]).toContain('FROM posthog.ai_events AS ai_events')
- expect(mockApi.query).not.toHaveBeenCalled()
})
it('falls back to events when ai_events has no heavy props row', async () => {
@@ -93,40 +98,34 @@ describe('aiObservabilityAIDataLogic', () => {
.mockResolvedValueOnce({
results: [
[
+ 'event-1',
[{ role: 'user', content: 'events hi' }],
null,
[{ role: 'assistant', content: 'events hello' }],
null,
null,
[{ function: { name: 'events-search' } }],
- ],
+ ] as Row,
],
} as any)
- const logic = aiObservabilityAIDataLogic()
- logic.mount()
-
- await expectLogic(logic, () => {
- logic.actions.loadAIDataForEvent({
+ logic.actions.ensureAIDataLoaded([
+ {
eventId: 'event-1',
input: undefined,
output: undefined,
tools: undefined,
traceId: 'trace-1',
timestamp: '2026-04-30T10:00:00Z',
- })
- })
- .toFinishAllListeners()
- .toMatchValues({
- aiDataCache: {
- 'event-1': {
- input: [{ role: 'user', content: 'events hi' }],
- output: [{ role: 'assistant', content: 'events hello' }],
- tools: [{ function: { name: 'events-search' } }],
- },
- },
- })
+ },
+ ])
+ await settle()
+ expect(logic.values.aiDataCache['event-1']).toEqual({
+ input: [{ role: 'user', content: 'events hi' }],
+ output: [{ role: 'assistant', content: 'events hello' }],
+ tools: [{ function: { name: 'events-search' } }],
+ })
expect(mockApi.queryHogQL).toHaveBeenCalledTimes(2)
expect(mockApi.queryHogQL.mock.calls[0][0]).toContain('FROM posthog.ai_events AS ai_events')
expect(mockApi.queryHogQL.mock.calls[1][0]).toContain('FROM events')
@@ -136,40 +135,34 @@ describe('aiObservabilityAIDataLogic', () => {
jest.spyOn(mockApi, 'queryHogQL').mockResolvedValue({
results: [
[
+ 'event-1',
'[]',
null,
'[]',
JSON.stringify({ messages: [{ type: 'human', content: 'state input' }] }),
null,
null,
- ],
+ ] as Row,
],
} as any)
- const logic = aiObservabilityAIDataLogic()
- logic.mount()
-
- await expectLogic(logic, () => {
- logic.actions.loadAIDataForEvent({
+ logic.actions.ensureAIDataLoaded([
+ {
eventId: 'event-1',
input: undefined,
output: undefined,
tools: undefined,
traceId: 'trace-1',
timestamp: '2026-04-30T10:00:00Z',
- })
- })
- .toFinishAllListeners()
- .toMatchValues({
- aiDataCache: {
- 'event-1': {
- input: { messages: [{ type: 'human', content: 'state input' }] },
- output: [],
- tools: undefined,
- },
- },
- })
+ },
+ ])
+ await settle()
+ expect(logic.values.aiDataCache['event-1']).toEqual({
+ input: { messages: [{ type: 'human', content: 'state input' }] },
+ output: [],
+ tools: undefined,
+ })
expect(mockApi.queryHogQL).toHaveBeenCalledTimes(1)
})
@@ -179,64 +172,78 @@ describe('aiObservabilityAIDataLogic', () => {
{ role: 'user', content: 'analyze this page' },
]
jest.spyOn(mockApi, 'queryHogQL').mockResolvedValue({
- results: [[JSON.stringify(fullInput), null, null, null, null, null]],
+ results: [['event-1', JSON.stringify(fullInput), null, null, null, null, null] as Row],
} as any)
- const logic = aiObservabilityAIDataLogic()
- logic.mount()
-
- await expectLogic(logic, () => {
- logic.actions.loadAIDataForEvent({
+ logic.actions.ensureAIDataLoaded([
+ {
eventId: 'event-1',
input: fullInput,
output: undefined,
tools: undefined,
traceId: 'trace-1',
timestamp: '2026-04-30T10:00:00Z',
- })
+ },
+ ])
+ await settle()
+
+ expect(logic.values.aiDataCache['event-1']).toEqual({
+ input: fullInput,
+ output: undefined,
+ tools: undefined,
})
- .toFinishAllListeners()
- .toMatchValues({
- aiDataCache: {
- 'event-1': {
- input: fullInput,
- output: undefined,
- tools: undefined,
- },
- },
- })
})
- it('degrades gracefully to the passed-in values when the lookup throws', async () => {
+ it('resolves the cell and clears loading when the lookup finds nothing', async () => {
+ // Regression: an unresolved row must not stay pinned in the loading set forever.
+ jest.spyOn(mockApi, 'queryHogQL').mockResolvedValue({ results: [] } as any)
+
+ logic.actions.ensureAIDataLoaded([
+ {
+ eventId: 'event-1',
+ input: 'fallback-input',
+ output: undefined,
+ tools: undefined,
+ traceId: 'trace-1',
+ timestamp: '2026-04-30T10:00:00Z',
+ },
+ ])
+ await settle()
+
+ expect(logic.values.aiDataCache).toHaveProperty('event-1')
+ expect(logic.values.aiDataCache['event-1']).toEqual({
+ input: 'fallback-input',
+ output: undefined,
+ tools: undefined,
+ })
+ expect(logic.values.isEventLoading('event-1')).toBe(false)
+ })
+
+ it('degrades gracefully and clears loading when both sources throw', async () => {
+ // Regression: the failure path used to read the event id from the thrown error, so the
+ // row was never removed from the loading set and the cell loaded forever.
jest.spyOn(mockApi, 'queryHogQL').mockRejectedValue(new Error('network down'))
- // The logic warns (by design) once per failed source before falling back.
const warnSpy = jest.spyOn(console, 'warn').mockImplementation()
try {
- const logic = aiObservabilityAIDataLogic()
- logic.mount()
-
- await expectLogic(logic, () => {
- logic.actions.loadAIDataForEvent({
+ logic.actions.ensureAIDataLoaded([
+ {
eventId: 'event-1',
input: 'fallback-input',
output: undefined,
tools: undefined,
traceId: 'trace-1',
timestamp: '2026-04-30T10:00:00Z',
- })
- })
- .toFinishAllListeners()
- .toMatchValues({
- aiDataCache: {
- 'event-1': {
- input: 'fallback-input',
- output: undefined,
- tools: undefined,
- },
- },
- })
+ },
+ ])
+ await settle()
+ expect(logic.values.aiDataCache['event-1']).toEqual({
+ input: 'fallback-input',
+ output: undefined,
+ tools: undefined,
+ })
+ expect(logic.values.isEventLoading('event-1')).toBe(false)
expect(warnSpy).toHaveBeenCalledWith(
'[aiObservabilityAIDataLogic] failed to load heavy AI props from ai_events',
expect.any(Error)
@@ -250,6 +257,40 @@ describe('aiObservabilityAIDataLogic', () => {
}
})
+ it('loads many rows with a single query per source instead of one query per row', async () => {
+ // Regression: the previous implementation fired one HogQL query per visible row.
+ jest.spyOn(mockApi, 'queryHogQL').mockResolvedValue({
+ results: [
+ ['event-1', JSON.stringify(['in-1']), JSON.stringify(['out-1']), null, null, null, null] as Row,
+ ['event-2', JSON.stringify(['in-2']), JSON.stringify(['out-2']), null, null, null, null] as Row,
+ ],
+ } as any)
+
+ logic.actions.ensureAIDataLoaded([
+ {
+ eventId: 'event-1',
+ input: undefined,
+ output: undefined,
+ tools: undefined,
+ traceId: 'trace-1',
+ timestamp: '2026-04-30T10:00:00Z',
+ },
+ {
+ eventId: 'event-2',
+ input: undefined,
+ output: undefined,
+ tools: undefined,
+ traceId: 'trace-1',
+ timestamp: '2026-04-30T10:05:00Z',
+ },
+ ])
+ await settle()
+
+ expect(mockApi.queryHogQL).toHaveBeenCalledTimes(1)
+ expect(logic.values.aiDataCache['event-1']).toEqual({ input: ['in-1'], output: ['out-1'], tools: undefined })
+ expect(logic.values.aiDataCache['event-2']).toEqual({ input: ['in-2'], output: ['out-2'], tools: undefined })
+ })
+
it.each([
['traceId missing', { traceId: undefined, timestamp: '2026-04-30T10:00:00Z' }],
['timestamp missing', { traceId: 'trace-1', timestamp: undefined }],
@@ -257,19 +298,20 @@ describe('aiObservabilityAIDataLogic', () => {
])('skips the fetch when trace coordinates are incomplete (%s)', async (_label, coords) => {
const querySpy = jest.spyOn(mockApi, 'queryHogQL')
- const logic = aiObservabilityAIDataLogic()
- logic.mount()
-
- await expectLogic(logic, () => {
- logic.actions.loadAIDataForEvent({
+ logic.actions.ensureAIDataLoaded([
+ {
eventId: 'event-1',
input: undefined,
output: undefined,
tools: undefined,
...coords,
- })
- }).toFinishAllListeners()
+ },
+ ])
+ await settle()
expect(querySpy).not.toHaveBeenCalled()
+ // Still resolved, so the cell stops loading and falls back to the main-query values.
+ expect(logic.values.aiDataCache).toHaveProperty('event-1')
+ expect(logic.values.isEventLoading('event-1')).toBe(false)
})
})
diff --git a/products/ai_observability/frontend/aiObservabilityAIDataLogic.ts b/products/ai_observability/frontend/aiObservabilityAIDataLogic.ts
index 2c317c15bfd4..a12af1839d30 100644
--- a/products/ai_observability/frontend/aiObservabilityAIDataLogic.ts
+++ b/products/ai_observability/frontend/aiObservabilityAIDataLogic.ts
@@ -1,8 +1,8 @@
-import { MakeLogicType, actions, kea, path, reducers, selectors } from 'kea'
-import { loaders } from 'kea-loaders'
+import { MakeLogicType, actions, events, kea, listeners, path, reducers, selectors } from 'kea'
import api from 'lib/api'
-import { dayjs } from 'lib/dayjs'
+import { Dayjs, dayjs } from 'lib/dayjs'
+import { chunk } from 'lib/utils/arrays'
import { ProductKey } from '~/queries/schema/schema-general'
import { hogql } from '~/queries/utils'
@@ -15,8 +15,10 @@ const AI_DATA_QUERY_TAGS = {
}
const EVENT_TIMESTAMP_WINDOW_MINUTES = 10
+const BATCH_MAX_SIZE = 100
+const BATCH_DEBOUNCE_MS = 0
-type AIDataQueryRow = [unknown, unknown, unknown, unknown, unknown, unknown]
+type AIDataQueryRow = [unknown, unknown, unknown, unknown, unknown, unknown, unknown]
interface AIDataQuerySource {
from: string
@@ -57,7 +59,7 @@ export interface AIData {
tools: unknown
}
-export interface LoadAIDataParams {
+export interface AIDataLookup {
eventId: string
input: unknown
output: unknown
@@ -96,7 +98,7 @@ function selectHeavyValue(...values: unknown[]): unknown {
}
function mapAIDataQueryRow(row: AIDataQueryRow): AIData {
- const [input, output, outputChoices, inputState, outputState, tools] = row
+ const [, input, output, outputChoices, inputState, outputState, tools] = row
return {
input: selectHeavyValue(input, inputState),
output: selectHeavyValue(outputChoices, outputState, output),
@@ -123,21 +125,41 @@ function mergeAIData(base: AIData, loaded: AIData | null): AIData {
}
}
-async function queryAIDataForEvent(params: LoadAIDataParams, source: AIDataQuerySource): Promise<AIData | null> {
- if (!params.traceId || !params.timestamp) {
- return null
+function uniqueNonEmpty(values: (string | undefined)[]): string[] {
+ return Array.from(new Set(values.filter((value): value is string => !!value)))
+}
+
+// One query per source across the whole batch, keyed by event uuid. The scan window is the union
+// of every event's ±window, so it stays narrow when the batch's rows are clustered in time.
+async function queryAIDataBatch(lookups: AIDataLookup[], source: AIDataQuerySource): Promise<Map<string, AIData>> {
+ const traceIds = uniqueNonEmpty(lookups.map((lookup) => lookup.traceId))
+ const eventIds = uniqueNonEmpty(lookups.map((lookup) => lookup.eventId))
+
+ const timestamps = lookups
+ .map((lookup) => (lookup.timestamp ? dayjs(lookup.timestamp) : null))
+ .filter((timestamp): timestamp is Dayjs => !!timestamp && timestamp.isValid())
+
+ if (traceIds.length === 0 || eventIds.length === 0 || timestamps.length === 0) {
+ return new Map()
}
- const eventTimestamp = dayjs(params.timestamp)
- if (!eventTimestamp.isValid()) {
- return null
+ let earliest = timestamps[0]
+ let latest = timestamps[0]
+ for (const timestamp of timestamps) {
+ if (timestamp.isBefore(earliest)) {
+ earliest = timestamp
+ }
+ if (timestamp.isAfter(latest)) {
+ latest = timestamp
+ }
}
+ const dateFrom = earliest.subtract(EVENT_TIMESTAMP_WINDOW_MINUTES, 'minute').toISOString()
+ const dateTo = latest.add(EVENT_TIMESTAMP_WINDOW_MINUTES, 'minute').toISOString()
- const dateFrom = eventTimestamp.subtract(EVENT_TIMESTAMP_WINDOW_MINUTES, 'minute').toISOString()
- const dateTo = eventTimestamp.add(EVENT_TIMESTAMP_WINDOW_MINUTES, 'minute').toISOString()
const response = await api.queryHogQL<AIDataQueryRow[]>(
hogql`
SELECT
+ uuid,
argMax(ai_input, timestamp) AS ai_input,
argMax(ai_output, timestamp) AS ai_output,
argMax(ai_output_choices, timestamp) AS ai_output_choices,
@@ -155,108 +177,102 @@ async function queryAIDataForEvent(params: LoadAIDataParams, source: AIDataQuery
${hogql.raw(source.outputStateExpression)} AS ai_output_state,
${hogql.raw(source.toolsExpression)} AS ai_tools
FROM ${hogql.raw(source.from)}
- WHERE ${hogql.raw(source.traceIdExpression)} = ${params.traceId}
- AND toString(uuid) = ${params.eventId}
+ WHERE ${hogql.raw(source.traceIdExpression)} IN ${traceIds}
+ AND toString(uuid) IN ${eventIds}
AND timestamp >= toDateTime(${dateFrom})
AND timestamp <= toDateTime(${dateTo})
)
GROUP BY uuid
- LIMIT 1
+ LIMIT ${eventIds.length}
`,
{ ...AI_DATA_QUERY_TAGS, name: 'ai_observability_event_heavy_props_lookup' }
)
- const row = response.results?.[0]
- if (!row) {
- return null
+ const dataByEventId = new Map<string, AIData>()
+ for (const row of response.results ?? []) {
+ const eventId = row[0] == null ? '' : String(row[0])
+ if (!eventId) {
+ continue
+ }
+ const data = mapAIDataQueryRow(row)
+ if (hasLoadedAIData(data)) {
+ dataByEventId.set(eventId, data)
+ }
}
-
- const data = mapAIDataQueryRow(row)
- return hasLoadedAIData(data) ? data : null
+ return dataByEventId
}
-async function loadAIDataAsync(params: LoadAIDataParams): Promise<AIData> {
- const { input, output, tools, traceId, timestamp } = params
- let loadedData: AIData = { input, output, tools }
+// Resolves every lookup in the batch. Each result starts from the values the main query already
+// handed us, then merges anything the heavy-prop lookups add. A lookup that resolves to nothing
+// keeps its base values, so the cell stops loading and falls back to what the main query returned.
+async function fetchAIDataBatch(lookups: AIDataLookup[]): Promise<Record<string, AIData>> {
+ const results: Record<string, AIData> = {}
+ const pending: AIDataLookup[] = []
+
+ for (const lookup of lookups) {
+ results[lookup.eventId] = { input: lookup.input, output: lookup.output, tools: lookup.tools }
- // Passthrough: caller already has both sides of the conversation (e.g. the trace page
- // hydrates rows from the TraceQuery that has heavy props merged back). No fetch needed.
- if (input != null && output != null) {
- return { input, output, tools }
+ // Both sides already present, or no trace coordinates to query with — nothing to fetch.
+ if (hasInputAndOutput(results[lookup.eventId]) || !lookup.traceId || !lookup.timestamp) {
+ continue
+ }
+ pending.push(lookup)
}
- // Can't fetch without trace coordinates — fall back to whatever we were handed.
- // This includes events without $ai_trace_id, which predate the SDK's auto-assignment.
- if (!traceId || !timestamp) {
- return { input, output, tools }
+ if (pending.length === 0) {
+ return results
}
- // Query the dedicated table directly first. TraceQuery still has a rollout gate, so
- // using it here can repeat the original `events` read and miss stripped heavy props.
+ // Query the dedicated table first. TraceQuery still has a rollout gate, so using it here can
+ // repeat the original `events` read and miss stripped heavy props.
try {
- const aiEventsData = await queryAIDataForEvent(params, AI_EVENTS_SOURCE)
- loadedData = mergeAIData(loadedData, aiEventsData)
- if (hasInputAndOutput(loadedData)) {
- return loadedData
+ const aiEventsData = await queryAIDataBatch(pending, AI_EVENTS_SOURCE)
+ for (const lookup of pending) {
+ results[lookup.eventId] = mergeAIData(results[lookup.eventId], aiEventsData.get(lookup.eventId) ?? null)
}
} catch (error) {
console.warn('[aiObservabilityAIDataLogic] failed to load heavy AI props from ai_events', error)
}
- try {
- const eventsData = await queryAIDataForEvent(params, EVENTS_SOURCE)
- return mergeAIData(loadedData, eventsData)
- } catch (error) {
- console.warn('[aiObservabilityAIDataLogic] failed to load heavy AI props from events', error)
- return loadedData
+ const fallback = pending.filter((lookup) => !hasInputAndOutput(results[lookup.eventId]))
+ if (fallback.length > 0) {
+ try {
+ const eventsData = await queryAIDataBatch(fallback, EVENTS_SOURCE)
+ for (const lookup of fallback) {
+ results[lookup.eventId] = mergeAIData(results[lookup.eventId], eventsData.get(lookup.eventId) ?? null)
+ }
+ } catch (error) {
+ console.warn('[aiObservabilityAIDataLogic] failed to load heavy AI props from events', error)
+ }
}
+
+ return results
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface aiObservabilityAIDataLogicValues {
- aiDataCache: Record<string, AIData>
- aiDataForEvent:
- | (AIData & {
- eventId: string
- })
- | null
- aiDataForEventLoading: boolean
+ aiDataCache: Record<string, AIData | null>
isEventLoading: (eventId: string) => boolean
loadingEventIds: Set<string>
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface aiObservabilityAIDataLogicActions {
- clearAIDataForEvent: (eventId: string) => {
- eventId: string
+ ensureAIDataLoaded: (lookups: AIDataLookup[]) => {
+ lookups: AIDataLookup[]
}
- clearAllAIData: () => {
- value: true
+ loadAIDataBatchFailure: (requestedEventIds: string[]) => {
+ requestedEventIds: string[]
}
- loadAIDataForEvent: (params: LoadAIDataParams) => LoadAIDataParams
- loadAIDataForEventFailure: (
- error: string,
- errorObject?: any
+ loadAIDataBatchSuccess: (
+ results: Record<string, AIData>,
+ requestedEventIds: string[]
) => {
- error: string
- errorObject?: any
+ requestedEventIds: string[]
+ results: Record<string, AIData>
}
- loadAIDataForEventSuccess: (
- aiDataForEvent: {
- eventId: string
- input: unknown
- output: unknown
- tools: unknown
- },
- payload?: LoadAIDataParams
- ) => {
- aiDataForEvent: {
- eventId: string
- input: unknown
- output: unknown
- tools: unknown
- }
- payload?: LoadAIDataParams
+ markEventIdsLoading: (eventIds: string[]) => {
+ eventIds: string[]
}
}
@@ -278,48 +294,60 @@ export const aiObservabilityAIDataLogic = kea<aiObservabilityAIDataLogicType>([
path(['products', 'ai_observability', 'frontend', 'aiObservabilityAIDataLogic']),
actions({
- loadAIDataForEvent: (params: LoadAIDataParams) => params,
- clearAIDataForEvent: (eventId: string) => ({ eventId }),
- clearAllAIData: true,
+ ensureAIDataLoaded: (lookups: AIDataLookup[]) => ({ lookups }),
+ markEventIdsLoading: (eventIds: string[]) => ({ eventIds }),
+ loadAIDataBatchSuccess: (results: Record<string, AIData>, requestedEventIds: string[]) => ({
+ results,
+ requestedEventIds,
+ }),
+ loadAIDataBatchFailure: (requestedEventIds: string[]) => ({ requestedEventIds }),
}),
reducers({
aiDataCache: [
- {} as Record<string, AIData>,
+ {} as Record<string, AIData | null>,
{
- loadAIDataForEventSuccess: (state, { aiDataForEvent }) => ({
- ...state,
- [aiDataForEvent.eventId]: {
- input: aiDataForEvent.input,
- output: aiDataForEvent.output,
- tools: aiDataForEvent.tools,
- },
- }),
- clearAIDataForEvent: (state, { eventId }) => {
- const { [eventId]: _, ...rest } = state
- return rest
+ loadAIDataBatchSuccess: (state, { results, requestedEventIds }) => {
+ const next = { ...state }
+ for (const eventId of requestedEventIds) {
+ next[eventId] = results[eventId] ?? null
+ }
+ return next
+ },
+ loadAIDataBatchFailure: (state, { requestedEventIds }) => {
+ const next = { ...state }
+ for (const eventId of requestedEventIds) {
+ next[eventId] = null
+ }
+ return next
},
- clearAllAIData: () => ({}),
},
],
loadingEventIds: [
new Set<string>(),
{
- loadAIDataForEvent: (state, params) => {
- const newSet = new Set(state)
- newSet.add(params.eventId)
- return newSet
+ markEventIdsLoading: (state, { eventIds }) => {
+ const next = new Set(state)
+ for (const eventId of eventIds) {
+ if (eventId) {
+ next.add(eventId)
+ }
+ }
+ return next
},
- loadAIDataForEventSuccess: (state, { aiDataForEvent }) => {
- const newSet = new Set(state)
- newSet.delete(aiDataForEvent.eventId)
- return newSet
+ loadAIDataBatchSuccess: (state, { requestedEventIds }) => {
+ const next = new Set(state)
+ for (const eventId of requestedEventIds) {
+ next.delete(eventId)
+ }
+ return next
},
- loadAIDataForEventFailure: (state, params) => {
- const newSet = new Set(state)
- const { eventId } = params.errorObject
- newSet.delete(eventId)
- return newSet
+ loadAIDataBatchFailure: (state, { requestedEventIds }) => {
+ const next = new Set(state)
+ for (const eventId of requestedEventIds) {
+ next.delete(eventId)
+ }
+ return next
},
},
],
@@ -334,18 +362,68 @@ export const aiObservabilityAIDataLogic = kea<aiObservabilityAIDataLogicType>([
],
}),
- loaders(() => ({
- aiDataForEvent: [
- null as (AIData & { eventId: string }) | null,
- {
- loadAIDataForEvent: async (params: LoadAIDataParams) => {
- const data = await loadAIDataAsync(params)
- return {
- ...data,
- eventId: params.eventId,
- }
- },
- },
- ],
+ listeners(({ actions, values, cache }) => ({
+ ensureAIDataLoaded: ({ lookups }) => {
+ const uncached = lookups.filter(
+ (lookup) =>
+ lookup.eventId &&
+ values.aiDataCache[lookup.eventId] === undefined &&
+ !values.loadingEventIds.has(lookup.eventId)
+ )
+
+ if (uncached.length === 0) {
+ return
+ }
+
+ actions.markEventIdsLoading(uncached.map((lookup) => lookup.eventId))
+
+ const pendingLookups = cache.pendingLookups as Map<string, AIDataLookup>
+ for (const lookup of uncached) {
+ pendingLookups.set(lookup.eventId, lookup)
+ }
+
+ if (cache.batchTimer) {
+ return
+ }
+
+ cache.batchTimer = setTimeout(async () => {
+ const allLookups = Array.from(pendingLookups.values())
+ pendingLookups.clear()
+ cache.batchTimer = null
+
+ if (allLookups.length === 0) {
+ return
+ }
+
+ const chunks = chunk(allLookups, BATCH_MAX_SIZE)
+
+ await Promise.allSettled(
+ chunks.map(async (batch) => {
+ const requestedEventIds = batch.map((lookup) => lookup.eventId)
+ try {
+ const results = await fetchAIDataBatch(batch)
+ actions.loadAIDataBatchSuccess(results, requestedEventIds)
+ } catch (error) {
+ console.warn('[aiObservabilityAIDataLogic] failed to load AI data batch', error)
+ actions.loadAIDataBatchFailure(requestedEventIds)
+ }
+ })
+ )
+ }, BATCH_DEBOUNCE_MS)
+ },
+ })),
+
+ events(({ cache }) => ({
+ afterMount: () => {
+ cache.pendingLookups = new Map<string, AIDataLookup>()
+ cache.batchTimer = null
+ },
+ beforeUnmount: () => {
+ if (cache.batchTimer) {
+ clearTimeout(cache.batchTimer)
+ cache.batchTimer = null
+ }
+ cache.pendingLookups?.clear?.()
+ },
})),
])
diff --git a/products/ai_observability/frontend/aiObservabilityColumnRenderers.test.ts b/products/ai_observability/frontend/aiObservabilityColumnRenderers.test.ts
index ee45c3cbccac..c88f9bf876f2 100644
--- a/products/ai_observability/frontend/aiObservabilityColumnRenderers.test.ts
+++ b/products/ai_observability/frontend/aiObservabilityColumnRenderers.test.ts
@@ -1,14 +1,68 @@
+import { DataTableNode, NodeKind } from '~/queries/schema/schema-general'
import { PropertyFilterType, PropertyOperator } from '~/types'
import {
FilterIdentifier,
PersonData,
createPersonFilter,
+ getEventData,
getFilterIdentifier,
getTracesUrlWithPersonFilter,
} from './aiObservabilityColumnRenderers'
describe('aiObservabilityColumnRenderers', () => {
+ describe('getEventData', () => {
+ // Regression: without traceId + timestamp, useAIData can never fetch stripped heavy props,
+ // so Input/Output cells fall back to empty instead of loading the full payload.
+ it('extracts trace coordinates from object-format records', () => {
+ const eventData = getEventData({
+ uuid: 'event-1',
+ timestamp: '2026-04-30T10:00:00Z',
+ properties: {
+ $ai_trace_id: 'trace-1',
+ $ai_input: [{ role: 'user', content: 'hi' }],
+ $ai_output_choices: [{ role: 'assistant', content: 'hello' }],
+ },
+ })
+
+ expect(eventData).toEqual({
+ uuid: 'event-1',
+ input: [{ role: 'user', content: 'hi' }],
+ output: [{ role: 'assistant', content: 'hello' }],
+ traceId: 'trace-1',
+ timestamp: '2026-04-30T10:00:00Z',
+ })
+ })
+
+ it('extracts trace coordinates from array-format records by select column position', () => {
+ const query: DataTableNode = {
+ kind: NodeKind.DataTableNode,
+ source: {
+ kind: NodeKind.EventsQuery,
+ select: [
+ 'uuid',
+ 'properties.$ai_input[-1]',
+ 'properties.$ai_output_choices',
+ 'properties.$ai_trace_id',
+ 'timestamp',
+ ],
+ },
+ }
+ const eventData = getEventData(
+ ['event-1', 'stripped-input', 'stripped-output', 'trace-1', '2026-04-30T10:00:00Z'],
+ query
+ )
+
+ expect(eventData).toEqual({
+ uuid: 'event-1',
+ input: 'stripped-input',
+ output: 'stripped-output',
+ traceId: 'trace-1',
+ timestamp: '2026-04-30T10:00:00Z',
+ })
+ })
+ })
+
describe('getFilterIdentifier', () => {
it.each<[string, PersonData | null | undefined, FilterIdentifier | null]>([
['returns null when person is null', null, null],
diff --git a/products/ai_observability/frontend/aiObservabilityColumnRenderers.tsx b/products/ai_observability/frontend/aiObservabilityColumnRenderers.tsx
index 57e05c05ec50..8d82f37b6feb 100644
--- a/products/ai_observability/frontend/aiObservabilityColumnRenderers.tsx
+++ b/products/ai_observability/frontend/aiObservabilityColumnRenderers.tsx
@@ -365,7 +365,7 @@ function AIOutputCell({ eventData }: { eventData: EventData }): JSX.Element {
)
}
-const getEventData = (record: unknown, query?: DataTableNode | DataVisualizationNode): EventData | undefined => {
+export const getEventData = (record: unknown, query?: DataTableNode | DataVisualizationNode): EventData | undefined => {
// Object format (TracesQuery results)
if (record && typeof record === 'object' && !Array.isArray(record) && 'uuid' in record) {
const uuid = record.uuid
@@ -373,10 +373,14 @@ const getEventData = (record: unknown, query?: DataTableNode | DataVisualization
return undefined
}
const props = 'properties' in record && typeof record.properties === 'object' ? record.properties : null
+ const traceId = (props as Record<string, unknown> | null)?.$ai_trace_id
+ const timestamp = 'timestamp' in record ? record.timestamp : undefined
return {
uuid,
input: (props as Record<string, unknown> | null)?.$ai_input,
output: (props as Record<string, unknown> | null)?.$ai_output_choices,
+ traceId: typeof traceId === 'string' ? traceId : undefined,
+ timestamp: typeof timestamp === 'string' ? timestamp : undefined,
}
}
@@ -386,16 +390,22 @@ const getEventData = (record: unknown, query?: DataTableNode | DataVisualization
const uuidIdx = select.findIndex((c) => c === 'uuid')
const inputIdx = select.findIndex((c) => c === 'properties.$ai_input' || c === 'properties.$ai_input[-1]')
const outputIdx = select.findIndex((c) => c === 'properties.$ai_output_choices')
+ const traceIdIdx = select.findIndex((c) => c === 'properties.$ai_trace_id')
+ const timestampIdx = select.findIndex((c) => c === 'timestamp')
const uuid = record[uuidIdx]
if (typeof uuid !== 'string') {
return undefined
}
+ const traceId = traceIdIdx >= 0 ? record[traceIdIdx] : undefined
+ const timestamp = timestampIdx >= 0 ? record[timestampIdx] : undefined
return {
uuid,
input: inputIdx >= 0 ? record[inputIdx] : undefined,
output: outputIdx >= 0 ? record[outputIdx] : undefined,
+ traceId: typeof traceId === 'string' ? traceId : undefined,
+ timestamp: typeof timestamp === 'string' ? timestamp : undefined,
}
}
diff --git a/products/ai_observability/frontend/hooks/useAIData.ts b/products/ai_observability/frontend/hooks/useAIData.ts
index 4fa4ad15d36c..f758ba1610bc 100644
--- a/products/ai_observability/frontend/hooks/useAIData.ts
+++ b/products/ai_observability/frontend/hooks/useAIData.ts
@@ -20,8 +20,8 @@ export interface EventData {
}
export function useAIData(eventData: EventData | undefined): UseAIDataResult {
- const { aiDataCache, isEventLoading } = useValues(aiObservabilityAIDataLogic)
- const { loadAIDataForEvent } = useActions(aiObservabilityAIDataLogic)
+ const { aiDataCache } = useValues(aiObservabilityAIDataLogic)
+ const { ensureAIDataLoaded } = useActions(aiObservabilityAIDataLogic)
const eventId = eventData?.uuid
const input = eventData?.input
@@ -29,27 +29,21 @@ export function useAIData(eventData: EventData | undefined): UseAIDataResult {
const tools = eventData?.tools
const traceId = eventData?.traceId
const timestamp = eventData?.timestamp
+ // A resolved lookup caches an AIData object, or `null` when it found nothing. Both mean done.
const cached = eventId ? aiDataCache[eventId] : undefined
- const loading = eventId ? isEventLoading(eventId) : false
+ const resolved = !!eventId && cached !== undefined
// Only fire the loader when a real fetch is possible and a heavy prop is missing.
const canFetch = !!traceId && !!timestamp
const shouldFetch = canFetch && (input == null || output == null)
useEffect(() => {
- if (!eventId || cached || loading || !shouldFetch) {
+ if (!eventId || resolved || !shouldFetch) {
return
}
- loadAIDataForEvent({
- eventId,
- input,
- output,
- tools,
- traceId,
- timestamp,
- })
- }, [cached, loading, canFetch, loadAIDataForEvent, eventId, input, output, tools, traceId, timestamp, shouldFetch])
+ ensureAIDataLoaded([{ eventId, input, output, tools, traceId, timestamp }])
+ }, [resolved, canFetch, ensureAIDataLoaded, eventId, input, output, tools, traceId, timestamp, shouldFetch])
if (!eventId) {
return {
@@ -65,6 +59,6 @@ export function useAIData(eventData: EventData | undefined): UseAIDataResult {
input: cached?.input ?? input,
output: cached?.output ?? output,
tools: cached?.tools ?? tools,
- isLoading: shouldFetch && (loading || !cached),
+ isLoading: shouldFetch && !resolved,
}
}