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): report blob render timing instead of nulls (#88479)

Carlos Marchal745d36ecf87e
diff --git a/products/ai_observability/frontend/aiBlob.test.ts b/products/ai_observability/frontend/aiBlob.test.ts
index b0ab8e93ec91..73e55ce8b6d2 100644
--- a/products/ai_observability/frontend/aiBlob.test.ts
+++ b/products/ai_observability/frontend/aiBlob.test.ts
@@ -1,6 +1,4 @@
-import posthog from 'posthog-js'
-
-import { aiBlobRenderHandlers, parseAiBlobPointer, resolveAiBlobUrl, resolveDataUri } from './aiBlob'
+import { parseAiBlobPointer, resolveAiBlobUrl, resolveDataUri } from './aiBlob'
jest.mock('posthog-js', () => ({ __esModule: true, default: { capture: jest.fn() } }))
@@ -55,8 +53,61 @@ describe('aiBlob', () => {
})
describe('aiBlobRenderHandlers', () => {
+ // jsdom implements neither PerformanceObserver nor the resource timeline, so the timing path
+ // only runs against a stand-in observer that the test feeds entries to by hand.
+ let aiBlob: typeof import('./aiBlob')
+ let capture: jest.Mock
+ let deliver: (entries: PerformanceEntry[]) => void
+
+ function installFakeObserver(): (entries: PerformanceEntry[]) => void {
+ type EntryList = { getEntries: () => PerformanceEntry[] }
+ const callbacks: ((list: EntryList) => void)[] = []
+ class FakePerformanceObserver {
+ callback: (list: EntryList) => void
+ constructor(callback: (list: EntryList) => void) {
+ this.callback = callback
+ }
+ observe(): void {
+ callbacks.push(this.callback)
+ }
+ disconnect(): void {}
+ }
+ Object.defineProperty(globalThis, 'PerformanceObserver', {
+ value: FakePerformanceObserver,
+ configurable: true,
+ writable: true,
+ })
+ return (entries) => callbacks.forEach((callback) => callback({ getEntries: () => entries }))
+ }
+
+ function resourceEntry(url: string, transferSize: number, decodedBodySize: number): PerformanceEntry {
+ const entry = {
+ name: new URL(url, window.location.origin).toString(),
+ entryType: 'resource',
+ startTime: 0,
+ duration: 0,
+ transferSize,
+ decodedBodySize,
+ toJSON: () => ({}),
+ }
+ return entry
+ }
+
+ async function settle(): Promise<void> {
+ await new Promise<void>((resolve) => setTimeout(resolve, 0))
+ }
+
beforeEach(() => {
- jest.mocked(posthog.capture).mockClear()
+ deliver = installFakeObserver()
+ jest.resetModules()
+ const posthogModule: { default: { capture: jest.Mock } } = require('posthog-js')
+ capture = posthogModule.default.capture
+ aiBlob = require('./aiBlob')
+ })
+
+ afterEach(() => {
+ jest.useRealTimers()
+ Reflect.deleteProperty(globalThis, 'PerformanceObserver')
})
it.each([
@@ -64,25 +115,67 @@ describe('aiBlob', () => {
['an external url', 'https://example.com/a.png'],
['an unresolved pointer', POINTER],
])('attaches no handlers for %s', (_name, src) => {
- expect(aiBlobRenderHandlers(src, 'image')).toEqual({})
+ expect(aiBlob.aiBlobRenderHandlers(src, 'image')).toEqual({})
})
- it('captures success and error once per src, deduping repeat renders', () => {
- const src = `/api/projects/1/ai_blob/v1/sha256/${'b'.repeat(64)}`
- const handlers = aiBlobRenderHandlers(src, 'image')
- handlers.onLoad!()
- handlers.onLoad!()
- handlers.onError!()
- expect(posthog.capture).toHaveBeenCalledTimes(2)
- expect(posthog.capture).toHaveBeenCalledWith('llma ai blob render', {
+ it.each<[string, 'before' | 'after', number, number, boolean]>([
+ ['a network fetch whose entry lands after the load event', 'after', 2048, 4096, false],
+ ['a cache hit, where a body is decoded but nothing crossed the network', 'after', 0, 4096, true],
+ ['an entry the observer had already buffered before the load event', 'before', 1024, 2048, false],
+ ])('reports the size and cache status of %s', async (_name, arrival, transfer, decoded, fromCache) => {
+ const src = `/api/projects/1/ai_blob/v1/sha256/${'e'.repeat(64)}`
+ const handlers = aiBlob.aiBlobRenderHandlers(src, 'image')
+ const entries = [resourceEntry(src, transfer, decoded)]
+
+ if (arrival === 'before') {
+ deliver(entries)
+ handlers.onLoad!()
+ } else {
+ handlers.onLoad!()
+ deliver(entries)
+ }
+ await settle()
+
+ expect(capture).toHaveBeenCalledWith('llma ai blob render', {
outcome: 'success',
media_kind: 'image',
- transfer_size_bytes: null,
- decoded_body_bytes: null,
- from_browser_cache: null,
+ transfer_size_bytes: transfer,
+ decoded_body_bytes: decoded,
+ from_browser_cache: fromCache,
})
- expect(posthog.capture).toHaveBeenCalledWith('llma ai blob render', {
- outcome: 'error',
+ })
+
+ it('reports the second render of a blob from its own entry, not the retained first one', async () => {
+ const src = `/api/projects/1/ai_blob/v1/sha256/${'9'.repeat(64)}`
+ const handlers = aiBlob.aiBlobRenderHandlers(src, 'image')
+
+ deliver([resourceEntry(src, 2048, 4096)])
+ handlers.onLoad!()
+ await settle()
+
+ handlers.onError!()
+ deliver([resourceEntry(src, 0, 0)])
+ await settle()
+
+ expect(capture).toHaveBeenCalledWith(
+ 'llma ai blob render',
+ expect.objectContaining({ outcome: 'error', transfer_size_bytes: 0, decoded_body_bytes: 0 })
+ )
+ })
+
+ it('falls back to null timing when no entry arrives for the rendered blob', async () => {
+ jest.useFakeTimers()
+ const src = `/api/projects/1/ai_blob/v1/sha256/${'f'.repeat(64)}`
+ const otherSrc = `/api/projects/1/ai_blob/v1/sha256/${'0'.repeat(64)}`
+
+ aiBlob.aiBlobRenderHandlers(src, 'image').onLoad!()
+ deliver([resourceEntry(otherSrc, 2048, 4096)])
+ await jest.advanceTimersByTimeAsync(999)
+ expect(capture).not.toHaveBeenCalled()
+
+ await jest.advanceTimersByTimeAsync(1)
+ expect(capture).toHaveBeenCalledWith('llma ai blob render', {
+ outcome: 'success',
media_kind: 'image',
transfer_size_bytes: null,
decoded_body_bytes: null,
@@ -90,30 +183,56 @@ describe('aiBlob', () => {
})
})
- it('keeps capturing new srcs after the dedup cache fills up', () => {
+ it('captures success and error once per src, deduping repeat renders', async () => {
+ const src = `/api/projects/1/ai_blob/v1/sha256/${'b'.repeat(64)}`
+ const handlers = aiBlob.aiBlobRenderHandlers(src, 'image')
+ handlers.onLoad!()
+ handlers.onLoad!()
+ handlers.onError!()
+ deliver([resourceEntry(src, 2048, 4096)])
+ await settle()
+
+ expect(capture).toHaveBeenCalledTimes(2)
+ expect(capture).toHaveBeenCalledWith(
+ 'llma ai blob render',
+ expect.objectContaining({ outcome: 'success', transfer_size_bytes: 2048 })
+ )
+ expect(capture).toHaveBeenCalledWith(
+ 'llma ai blob render',
+ expect.objectContaining({ outcome: 'error', transfer_size_bytes: 2048 })
+ )
+ })
+
+ it('keeps capturing new srcs after the dedup cache fills up', async () => {
+ jest.useFakeTimers()
for (let i = 0; i < 1000; i++) {
const src = `/api/projects/1/ai_blob/v1/sha256/${i.toString().padStart(64, '0')}`
- aiBlobRenderHandlers(src, 'image').onLoad!()
+ aiBlob.aiBlobRenderHandlers(src, 'image').onLoad!()
}
- jest.mocked(posthog.capture).mockClear()
+ await jest.advanceTimersByTimeAsync(1000)
+ capture.mockClear()
const src = `/api/projects/1/ai_blob/v1/sha256/${'d'.repeat(64)}`
- aiBlobRenderHandlers(src, 'image').onLoad!()
+ aiBlob.aiBlobRenderHandlers(src, 'image').onLoad!()
+ await jest.advanceTimersByTimeAsync(1000)
- expect(posthog.capture).toHaveBeenCalledWith(
+ expect(capture).toHaveBeenCalledWith(
'llma ai blob render',
expect.objectContaining({ outcome: 'success', media_kind: 'image' })
)
})
- it('signals audio success via canplay, which media elements fire instead of load', () => {
+ it('signals audio success via canplay, which media elements fire instead of load', async () => {
const src = `/api/projects/1/ai_blob/v1/sha256/${'c'.repeat(64)}`
- const handlers = aiBlobRenderHandlers(src, 'audio')
+ const handlers = aiBlob.aiBlobRenderHandlers(src, 'audio')
expect(handlers.onLoad).toBeUndefined()
handlers.onCanPlay!()
- expect(posthog.capture).toHaveBeenCalledWith(
+ deliver([resourceEntry(src, 512, 1024)])
+ await settle()
+
+ expect(capture).toHaveBeenCalledWith(
'llma ai blob render',
- expect.objectContaining({ outcome: 'success', media_kind: 'audio' })
+ expect.objectContaining({ outcome: 'success', media_kind: 'audio', decoded_body_bytes: 1024 })
)
})
})
diff --git a/products/ai_observability/frontend/aiBlob.ts b/products/ai_observability/frontend/aiBlob.ts
index a4c5d99fcdea..bf3d6b9274e7 100644
--- a/products/ai_observability/frontend/aiBlob.ts
+++ b/products/ai_observability/frontend/aiBlob.ts
@@ -56,7 +56,98 @@ const BLOB_ENDPOINT_RE = /\/ai_blob\/v1\/sha256\/[0-9a-f]{64}$/
const reportedRenders = new Map<string, true>()
const MAX_REPORTED_RENDERS = 1000
-function captureBlobRender(src: string, mediaKind: 'image' | 'audio', outcome: 'success' | 'error'): void {
+type TimingWaiter = (timing?: PerformanceResourceTiming) => void
+
+const blobTimings = new Map<string, PerformanceResourceTiming>()
+const MAX_TRACKED_TIMINGS = 200
+const waitersByUrl = new Map<string, Set<TimingWaiter>>()
+const TIMING_WAIT_MS = 1000
+
+function isResourceTiming(entry: PerformanceEntry): entry is PerformanceResourceTiming {
+ return entry.entryType === 'resource'
+}
+
+function forgetWaiter(url: string, waiter: TimingWaiter): void {
+ const waiting = waitersByUrl.get(url)
+ if (!waiting) {
+ return
+ }
+ waiting.delete(waiter)
+ if (waiting.size === 0) {
+ waitersByUrl.delete(url)
+ }
+}
+
+function rememberBlobTiming(entry: PerformanceResourceTiming): void {
+ if (!BLOB_ENDPOINT_RE.test(entry.name)) {
+ return
+ }
+ if (!blobTimings.has(entry.name) && blobTimings.size >= MAX_TRACKED_TIMINGS) {
+ const oldestUrl = blobTimings.keys().next().value
+ if (oldestUrl !== undefined) {
+ blobTimings.delete(oldestUrl)
+ }
+ }
+ blobTimings.set(entry.name, entry)
+ const waiting = waitersByUrl.get(entry.name)
+ if (waiting) {
+ waitersByUrl.delete(entry.name)
+ waiting.forEach((waiter) => waiter(entry))
+ }
+}
+
+/**
+ * The browser keeps only 250 resource entries, and the app fills that buffer long before anyone opens a
+ * trace, so performance.getEntriesByName() finds nothing for a blob that just rendered. An observer
+ * receives every entry from registration onward, which does not depend on the buffer.
+ */
+function observeBlobTimings(): void {
+ if (typeof PerformanceObserver === 'undefined') {
+ return
+ }
+ try {
+ new PerformanceObserver((list) => {
+ list.getEntries().filter(isResourceTiming).forEach(rememberBlobTiming)
+ }).observe({ type: 'resource', buffered: true })
+ } catch {
+ // A browser that does not report resource entries leaves the timing properties null.
+ }
+}
+
+observeBlobTimings()
+
+/**
+ * Resource entries reach the observer on a queued task, so a load handler can run before the entry for
+ * its own request lands. Waiting closes that gap. The timeout keeps a render whose entry never arrives
+ * reporting null timing instead of never reporting at all.
+ */
+function awaitBlobTiming(url: string): Promise<PerformanceResourceTiming | undefined> {
+ const known = blobTimings.get(url)
+ blobTimings.delete(url)
+ if (known || typeof PerformanceObserver === 'undefined') {
+ return Promise.resolve(known)
+ }
+ return new Promise((resolve) => {
+ const waiter = (timing?: PerformanceResourceTiming): void => {
+ clearTimeout(timeout)
+ forgetWaiter(url, waiter)
+ resolve(timing)
+ }
+ const timeout = setTimeout(waiter, TIMING_WAIT_MS)
+ const waiting = waitersByUrl.get(url)
+ if (waiting) {
+ waiting.add(waiter)
+ } else {
+ waitersByUrl.set(url, new Set([waiter]))
+ }
+ })
+}
+
+async function captureBlobRender(
+ src: string,
+ mediaKind: 'image' | 'audio',
+ outcome: 'success' | 'error'
+): Promise<void> {
const key = `${outcome}:${src}`
if (reportedRenders.has(key)) {
return
@@ -68,12 +159,7 @@ function captureBlobRender(src: string, mediaKind: 'image' | 'audio', outcome: '
}
}
reportedRenders.set(key, true)
- const entries =
- typeof performance.getEntriesByName === 'function'
- ? performance.getEntriesByName(new URL(src, window.location.origin).toString())
- : []
- const last = entries[entries.length - 1]
- const timing = last && 'transferSize' in last ? (last as PerformanceResourceTiming) : undefined
+ const timing = await awaitBlobTiming(new URL(src, window.location.origin).toString())
posthog.capture('llma ai blob render', {
outcome,
media_kind: mediaKind,
@@ -90,9 +176,11 @@ export function aiBlobRenderHandlers(
if (!BLOB_ENDPOINT_RE.test(src)) {
return {}
}
- const success = (): void => captureBlobRender(src, mediaKind, 'success')
+ const report = (outcome: 'success' | 'error') => (): void => {
+ void captureBlobRender(src, mediaKind, outcome)
+ }
return {
- ...(mediaKind === 'image' ? { onLoad: success } : { onCanPlay: success }),
- onError: (): void => captureBlobRender(src, mediaKind, 'error'),
+ ...(mediaKind === 'image' ? { onLoad: report('success') } : { onCanPlay: report('success') }),
+ onError: report('error'),
}
}