:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(session-replay): explain unmeasurable sizes and broken requests in network inspector (#92283)
posthog[bot]692c96a8295f
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex cd81290ad7cb..76556d0c5682 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -1292,6 +1292,14 @@ snapshots:hash: v1.k794b7964.868caa7623ec9c4b1675cfb19f4cab893c4de645ce9d557b98d955c003dd741e.Rf8-ZIb5gy4vbo9vmyZ6YxI7B1LSxxNkG5ONyk7YQUkcomponents-itemperformanceevent--no-performance-observer-captured-data--light:hash: v1.k794b7964.bfe32c7d513222270317b40c3e5721c5f9f968bd9bcda1026c8ccde52c86295e.iXYO1V2JKWEJGnB10yUKqSxoVCMbCaaDEpQImac6r3I+ components-itemperformanceevent--no-response-recorded--dark:+ hash: v1.k794b7964.d25643a9785e6ae04ac2a7f8c73393692abfaf4f8fbb9bc57f0125e9428e0da5.G4aWYn5d1xdoNpX0mJincAKnc7ofCWTsNAfZR5rzOxw+ components-itemperformanceevent--no-response-recorded--light:+ hash: v1.k794b7964.a4621b27841d2dce2bb7d20798ed6f9c7dd3e48e1695743f9065a75ba0552cc5.kWMI3AIXx-DYWUuTsmaiqG7T9DK8Wevu9VzcTJBbyoY+ components-itemperformanceevent--timed-out-body-display--dark:+ hash: v1.k794b7964.8558b680a337aff8beac6a2af6c9a2664f27c3c00a950cbf90681bc4bd97351c.OKknzco6mhDt_Q1dAVpp2gG7pqZbdxif2b5S5Tq7dOk+ components-itemperformanceevent--timed-out-body-display--light:+ hash: v1.k794b7964.4c0a64785d3a9f20db8cfd594e5a44ff7c05a3d9d6ea5ee3f20010f5c38e975a.q5lMkH4L2ZG9W4fO6WHCjJ6WTdiJTTlJktU2DSQQMK8components-markdown-editor-inline--bubble-menu-and-slash-commands--dark:hash: v1.k794b7964.a2c70c465689c5fbcb781e3748805a3411d8312a3b6fb512bb662273bfa8a6ed.L3RvOOkAyB_85uLzfdti9I2h96tS45LTWamutDYIMoEcomponents-markdown-editor-inline--bubble-menu-and-slash-commands--light:diff --git a/frontend/src/scenes/session-recordings/apm/performance-event-utils.test.ts b/frontend/src/scenes/session-recordings/apm/performance-event-utils.test.tsindex 586c9b7a109b..53129e167bbc 100644--- a/frontend/src/scenes/session-recordings/apm/performance-event-utils.test.ts+++ b/frontend/src/scenes/session-recordings/apm/performance-event-utils.test.ts@@ -1,4 +1,6 @@-import { getPerformanceEvents } from 'scenes/session-recordings/apm/performance-event-utils'+import { getPerformanceEvents, itemSizeInfo } from 'scenes/session-recordings/apm/performance-event-utils'++import { PerformanceEvent } from '~/types'const aSingleSnapshotWithNetworkPayloads = {windowId: '018d5247-079c-7126-8e43-464605576a62',@@ -301,6 +303,66 @@ describe('performance-event-utils', () => {expect(result).toEqual([])})+ it.each([+ // browser reports a literal 0 for an unmeasurable request (cross-origin, opaque, blocked)+ [+ 'unmeasurable 0 is treated as unknown',+ { transfer_size: 0, encoded_body_size: 0, decoded_body_size: 0 },+ null,+ ],+ // a cached request has no transfer size but keeps its decoded body size+ ['cached request reports its decoded size', { transfer_size: 0, decoded_body_size: 5120 }, 5120],+ ['transfer size wins when present', { transfer_size: 3311, decoded_body_size: 3011 }, 3311],+ // the SDK stores a diagnostic string as the body when it cannot read the real one;+ // it must not be measured as the response size (a "too large" body would invert to a few bytes)+ [+ 'diagnostic body is not measured as a size',+ { transfer_size: 0, response_body: '[SessionReplay] Timeout while trying to read body' },+ null,+ ],+ // the SDK writes these without the "[SessionReplay] " prefix+ [+ 'unprefixed content-type diagnostic is not measured',+ { transfer_size: 0, response_body: 'Content-Type video/mp4 is not supported' },+ null,+ ],+ [+ 'deny list diagnostic is not measured',+ { transfer_size: 0, response_body: 'api.company.com is in deny list' },+ null,+ ],+ [+ 'a redacted body is not measured',+ { transfer_size: 0, response_body: '[SessionRecording] content redacted' },+ null,+ ],+ // a real captured body is still estimated when no measured size is available+ [+ 'real body falls back to its estimated size',+ { transfer_size: 0, response_body: 'hello', response_headers: {} },+ 7,+ ],+ ])('itemSizeInfo bytes: %s', (_name, item, expectedBytes) => {+ const sizeInfo = itemSizeInfo(item as PerformanceEvent)+ expect(sizeInfo.bytes).toEqual(expectedBytes)+ if (expectedBytes === null) {+ expect(sizeInfo.formattedBytes).toEqual('')+ }+ })++ it.each([+ // the detail view prefers formattedDecodedBodySize; an unknown 0 must not become "0 bytes",+ // or it contradicts the "size not available" row+ [+ 'an unknown (0) body size is not formatted',+ { transfer_size: 0, encoded_body_size: 0, decoded_body_size: 0 },+ null,+ ],+ ['a measured body size is formatted', { transfer_size: 0, decoded_body_size: 5120 }, '5.00 kB'],+ ])('itemSizeInfo formattedDecodedBodySize: %s', (_name, item, expected) => {+ expect(itemSizeInfo(item as PerformanceEvent).formattedDecodedBodySize).toEqual(expected)+ })+it('skips malformed entries in rrweb/network@1 requests instead of crashing', () => {const snapshot = {windowId: '018d5247-079c-7126-8e43-464605576a62',diff --git a/frontend/src/scenes/session-recordings/apm/performance-event-utils.ts b/frontend/src/scenes/session-recordings/apm/performance-event-utils.tsindex 5e59846be254..92e3d58f7585 100644--- a/frontend/src/scenes/session-recordings/apm/performance-event-utils.ts+++ b/frontend/src/scenes/session-recordings/apm/performance-event-utils.ts@@ -311,21 +311,83 @@ function isPositiveNumber(value: any): value is number {return typeof value === 'number' && value >= 0}+function hasMeasuredSize(value: any): value is number {+ return typeof value === 'number' && value > 0+}++// The SDK writes a diagnostic string into the body when it cannot record the real one,+// for example a read timeout or a body over the record limit. Some of those messages carry a+// "[SessionReplay] " prefix and some do not, so match both shapes here. Returns a reader-facing+// explanation, or null when the body is a real one.+export function unreadableBodyExplanation(body: unknown): string | null {+ if (typeof body !== 'string') {+ return null+ }++ const prefix = '[SessionReplay] '+ if (body.startsWith(prefix)) {+ const message = body.slice(prefix.length)+ if (message.startsWith('Timeout')) {+ return 'PostHog stopped reading this body because it took too long.'+ }+ if (message.startsWith('Body too large')) {+ return "PostHog didn't record this body because it was too large."+ }+ if (message.startsWith('Cannot read body of type')) {+ return "PostHog couldn't record this body because its type isn't supported."+ }+ if (message.startsWith('Failed to stringify')) {+ return "PostHog couldn't record this body because it couldn't be converted to text."+ }+ if (message.startsWith('Failed to read body')) {+ return "PostHog couldn't read this body."+ }+ return "PostHog couldn't record this body."+ }++ // these three are written without the prefix+ if (body === 'Chunked Transfer-Encoding is not supported') {+ return "PostHog doesn't record bodies sent with chunked transfer encoding."+ }+ if (/^Content-Type \S.* is not supported$/.test(body)) {+ return "PostHog doesn't record bodies of this content type."+ }+ if (/^\S+ is in deny list$/.test(body)) {+ return "PostHog didn't record this body because its host is on your deny list."+ }++ return null+}++export function isAutoRedactedBody(body: unknown): boolean {+ return typeof body === 'string' && /(\[SessionRecording].*redacted)/.test(body)+}++// A placeholder is not a body, so measuring it would report the placeholder's length as the+// response size: a "too large to record" body would invert into a few dozen bytes.+export function isBodyPlaceholder(body: unknown): boolean {+ return unreadableBodyExplanation(body) !== null || isAutoRedactedBody(body)+}+function bytesFrom(item: PerformanceEvent): number | null {+ // The browser reports a literal 0 for a request it cannot measure: cross-origin,+ // opaque, blocked, or served from cache. A 0 here is "unknown", not "no data", so+ // skip it and try the next source before falling back to null.+// encoded body + header- if (isPositiveNumber(item.transfer_size)) {+ if (hasMeasuredSize(item.transfer_size)) {return item.transfer_size}// body while encoded e.g. gzipped- if (isPositiveNumber(item.encoded_body_size)) {+ if (hasMeasuredSize(item.encoded_body_size)) {return item.encoded_body_size}// body after being decoded e.g. unzipped- if (isPositiveNumber(item.decoded_body_size)) {+ if (hasMeasuredSize(item.decoded_body_size)) {return item.decoded_body_size}- if (item.response_body && typeof item.response_body === 'string') {+ if (item.response_body && typeof item.response_body === 'string' && !isBodyPlaceholder(item.response_body)) {const bodySize = new Blob([item.response_body]).sizeconst headerSize = new Blob([JSON.stringify(item.response_headers)]).sizereturn bodySize + headerSize@@ -350,12 +412,15 @@ export interface PerformanceEventSizeInfo {export function itemSizeInfo(item: PerformanceEvent): PerformanceEventSizeInfo {const bytes = bytesFrom(item)const formattedBytes = humanizeBytes(bytes)- const decodedBodySize = isPositiveNumber(item.decoded_body_size) ? item.decoded_body_size : null- const formattedDecodedBodySize = isPositiveNumber(decodedBodySize) ? humanizeBytes(decodedBodySize) : null- const encodedBodySize = isPositiveNumber(item.encoded_body_size) ? item.encoded_body_size : null- const formattedEncodedBodySize = isPositiveNumber(encodedBodySize) ? humanizeBytes(encodedBodySize) : null+ // A body size of 0 means "unknown", not "empty" (cross-origin, opaque, blocked), the same+ // as in bytesFrom. Treat it as unknown so the detail view does not say "to load 0 bytes of+ // data" where the row shows "size not available".+ const decodedBodySize = hasMeasuredSize(item.decoded_body_size) ? item.decoded_body_size : null+ const formattedDecodedBodySize = hasMeasuredSize(decodedBodySize) ? humanizeBytes(decodedBodySize) : null+ const encodedBodySize = hasMeasuredSize(item.encoded_body_size) ? item.encoded_body_size : null+ const formattedEncodedBodySize = hasMeasuredSize(encodedBodySize) ? humanizeBytes(encodedBodySize) : nullconst compressionPercentage =- isPositiveNumber(item.decoded_body_size) && isPositiveNumber(item.encoded_body_size)+ hasMeasuredSize(item.decoded_body_size) && hasMeasuredSize(item.encoded_body_size)? ((item.decoded_body_size - item.encoded_body_size) / item.decoded_body_size) * 100: nullconst formattedCompressionPercentage = isPositiveNumber(compressionPercentage)diff --git a/frontend/src/scenes/session-recordings/apm/playerInspector/ItemPerformanceEvent.stories.tsx b/frontend/src/scenes/session-recordings/apm/playerInspector/ItemPerformanceEvent.stories.tsxindex e41bf77e3141..d9bbe95036dc 100644--- a/frontend/src/scenes/session-recordings/apm/playerInspector/ItemPerformanceEvent.stories.tsx+++ b/frontend/src/scenes/session-recordings/apm/playerInspector/ItemPerformanceEvent.stories.tsx@@ -136,6 +136,33 @@ export const NoPerformanceObserverCapturedData: Story = {},}+// A fetch that recorded no response (blocked, network error, or cancelled) has a method but no+// status, and the browser cannot measure its size. It should read as "no response", not a success.+export const NoResponseRecorded: Story = {+ args: {+ item: {+ entry_type: 'resource',+ initiator_type: 'fetch',+ method: 'GET',+ name: 'https://api.company.com/v1/counts',+ start_time: 858859,+ end_time: 859613,+ duration: 754,+ time_origin: '1726567602079',+ timestamp: 1726568460938,+ } as unknown as PerformanceEvent,+ },+}++export function TimedOutBodyDisplay(): JSX.Element {+ return (+ <BodyDisplay+ content="[SessionReplay] Timeout while trying to read body"+ headers={{ 'content-type': 'application/json' }}+ />+ )+}+export function InitialHeadersDisplay(): JSX.Element {return <HeadersDisplay request={undefined} response={undefined} isInitial={true} />}diff --git a/frontend/src/scenes/session-recordings/apm/playerInspector/ItemPerformanceEvent.test.tsx b/frontend/src/scenes/session-recordings/apm/playerInspector/ItemPerformanceEvent.test.tsxnew file mode 100644index 000000000000..0efb422107cb--- /dev/null+++ b/frontend/src/scenes/session-recordings/apm/playerInspector/ItemPerformanceEvent.test.tsx@@ -0,0 +1,84 @@+import { render } from '@testing-library/react'++import {+ BodyDisplay,+ hasNoRecordedResponse,+ StatusTag,+} from 'scenes/session-recordings/apm/playerInspector/ItemPerformanceEvent'++import { PerformanceEvent } from '~/types'++describe('ItemPerformanceEvent', () => {+ it.each([+ ['[SessionReplay] Timeout while trying to read body', 'took too long'],+ ['[SessionReplay] Body too large to record (> 1000000 bytes)', 'too large'],+ ['[SessionReplay] Cannot read body of type Blob', "type isn't supported"],+ ['[SessionReplay] Failed to stringify response object', "couldn't be converted to text"],+ ['[SessionReplay] Failed to read body: AbortError', "couldn't read this body"],+ ['[SessionReplay] Some new message we do not map yet', "couldn't record this body"],+ // the SDK writes these three without a prefix+ ['Chunked Transfer-Encoding is not supported', 'chunked transfer encoding'],+ ['Content-Type video/mp4 is not supported', 'this content type'],+ ['api.company.com is in deny list', 'on your deny list'],+ ])('BodyDisplay explains the SDK diagnostic %s', (content, expectedExplanation) => {+ const { container } = render(<BodyDisplay content={content} headers={undefined} />)+ expect(container.textContent).toContain(expectedExplanation)+ // the raw SDK string stays visible for anyone who needs it+ expect(container.textContent).toContain(content)+ })++ it.each([+ [+ 'a fetch that threw or was aborted has no status',+ { initiator_type: 'fetch', response_status: undefined },+ true,+ ],+ [+ 'a successful opaque cross-origin fetch reports status 0',+ { initiator_type: 'fetch', response_status: 0 },+ false,+ ],+ ['an XHR with no response reports status 0', { initiator_type: 'xmlhttprequest', response_status: 0 }, true],+ ['a successful XHR keeps its real status', { initiator_type: 'xmlhttprequest', response_status: 200 }, false],+ ['a navigation never counts', { entry_type: 'navigation', response_status: undefined }, false],+ [+ 'a request captured before PostHog started is skipped',+ { is_initial: true, response_status: undefined },+ false,+ ],+ [+ 'a resource-timing entry without a method is skipped',+ { method: undefined, response_status: undefined },+ false,+ ],+ ])('hasNoRecordedResponse: %s', (_desc, overrides, expected) => {+ const item = { entry_type: 'resource', method: 'GET', ...overrides } as PerformanceEvent+ expect(hasNoRecordedResponse(item)).toBe(expected)+ })++ it.each([+ ['a fetch with no status', { initiator_type: 'fetch', response_status: undefined }],+ ['an XHR with status 0', { initiator_type: 'xmlhttprequest', response_status: 0 }],+ ])('StatusTag marks %s so the waterfall shows it too', (_desc, overrides) => {+ const item = { entry_type: 'resource', method: 'GET', ...overrides } as PerformanceEvent+ const { container } = render(<StatusTag item={item} detailed={false} />)+ expect(container.textContent).toContain('No response')+ })++ it.each([+ ['a 200 response', { initiator_type: 'fetch', response_status: 200 }],+ ['an opaque cross-origin fetch with status 0', { initiator_type: 'fetch', response_status: 0 }],+ ])('StatusTag does not mark %s', (_desc, overrides) => {+ const item = { entry_type: 'resource', method: 'GET', ...overrides } as PerformanceEvent+ const { container } = render(<StatusTag item={item} detailed={false} />)+ expect(container.textContent).not.toContain('No response')+ })++ // an abort and a block are indistinguishable here, so the tag must not declare a failure+ it('hedges the cause when no response was recorded', () => {+ const item = { entry_type: 'resource', method: 'GET', initiator_type: 'fetch' } as PerformanceEvent+ const { container } = render(<StatusTag item={item} detailed={true} />)+ expect(container.querySelector('.LemonTag')?.textContent).toEqual('No response')+ expect(container.textContent).toContain('blocked, failed, or cancelled')+ })+})diff --git a/frontend/src/scenes/session-recordings/apm/playerInspector/ItemPerformanceEvent.tsx b/frontend/src/scenes/session-recordings/apm/playerInspector/ItemPerformanceEvent.tsxindex 2f3a62b6705d..7841f670ef00 100644--- a/frontend/src/scenes/session-recordings/apm/playerInspector/ItemPerformanceEvent.tsx+++ b/frontend/src/scenes/session-recordings/apm/playerInspector/ItemPerformanceEvent.tsx@@ -10,7 +10,12 @@ import { Dayjs, dayjs } from 'lib/dayjs'import { humanFriendlyMilliseconds } from 'lib/utils/durations'import { isKeyOf } from 'lib/utils/guards'import { isURL } from 'lib/utils/url'-import { PerformanceEventSizeInfo, itemSizeInfo } from 'scenes/session-recordings/apm/performance-event-utils'+import {+ isAutoRedactedBody,+ itemSizeInfo,+ PerformanceEventSizeInfo,+ unreadableBodyExplanation,+} from 'scenes/session-recordings/apm/performance-event-utils'import { NavigationItem } from 'scenes/session-recordings/player/inspector/components/NavigationItem'import { PerformanceEventLabel } from 'scenes/session-recordings/player/inspector/components/PerformanceEventLabel'import { NetworkRequestTiming } from 'scenes/session-recordings/player/inspector/components/Timing/NetworkRequestTiming'@@ -110,6 +115,23 @@ function StartedAt({ item }: { item: PerformanceEvent }): JSX.Element | null {) : null}+export function hasNoRecordedResponse(item: PerformanceEvent): boolean {+ // A captured fetch/XHR (method present) that recorded no response. Skip navigations and+ // requests captured before PostHog started. A fetch that throws records no status, while a+ // successful opaque cross-origin fetch records 0, so for fetch only an absent status means+ // no response. An XHR cannot be opaque, so it reports status 0 when it recorded none.+ //+ // The cause is not knowable from here: a firewall block, CORS, and a network error look the+ // same as an abort, and aborts are routine in an app that cancels in-flight requests. So this+ // reports only that no response was recorded, and never calls the request failed.+ return (+ item.entry_type !== 'navigation' &&+ !item.is_initial &&+ item.method !== undefined &&+ (item.response_status === undefined || (item.response_status === 0 && item.initiator_type === 'xmlhttprequest'))+ )+}+function durationMillisecondsFrom(item: PerformanceEvent): number | null {let duration = item.durationif (duration === undefined && item.end_time !== undefined && item.start_time !== undefined) {@@ -202,22 +224,22 @@ export function ItemPerformanceEvent({ item, finalTimestamp }: ItemPerformanceEv<div className="flex gap-2 p-2 text-xs cursor-pointer items-center"><MethodTag item={item} /><PerformanceEventLabel name={item.name} expanded={false} />- {/* We only show the status if it exists and is an error status */}+ {/* Highlight the request when it returned an error status, or when no+ response was recorded for it at all */}{otherProps.response_status && otherProps.response_status >= 400 ? (<spanclassName={clsx('font-semibold',- otherProps.response_status >= 400 &&- otherProps.response_status < 500 &&- 'text-warning-dark',- otherProps.response_status >= 500 && 'text-danger-dark'+ otherProps.response_status < 500 ? 'text-warning-dark' : 'text-danger-dark')}>{otherProps.response_status}</span>+ ) : hasNoRecordedResponse(item) ? (+ <span className="font-semibold text-warning-dark">no response</span>) : null}{renderTimeBenchmark(duration)}- <span className={clsx('font-semibold')}>{sizeInfo.formattedBytes}</span>+ <span className={clsx('font-semibold')}>{sizeInfo.formattedBytes || 'size not available'}</span></div>)}</div>@@ -389,9 +411,17 @@ export function BodyDisplay({language = Language.JSON}- const isAutoRedaction = /(\[SessionRecording].*redacted)/.test(displayContent)+ const bodyDiagnostic = unreadableBodyExplanation(displayContent)+ if (bodyDiagnostic) {+ return (+ <>+ <p>{bodyDiagnostic}</p>+ <pre>received: {displayContent}</pre>+ </>+ )+ }- return isAutoRedaction ? (+ return isAutoRedactedBody(displayContent) ? (<><p>This content was redacted by PostHog to protect sensitive data.{' '}@@ -453,6 +483,22 @@ export function HeadersDisplay({export function StatusTag({ item, detailed }: { item: PerformanceEvent; detailed: boolean }): JSX.Element | null {const { response_status: responseStatus, transfer_size: transferSize, response_body: responseBody } = item+ if (hasNoRecordedResponse(item)) {+ // Render this here so every renderer that shares StatusTag marks it, including the+ // network waterfall, not just the inspector list.+ return (+ <div className="flex gap-4 items-center justify-between overflow-hidden">+ {detailed ? <div className="font-semibold">Status code</div> : null}+ <div>+ <LemonTag type="warning">No response</LemonTag>+ {detailed ? (+ <span className="text-secondary"> the request was blocked, failed, or cancelled</span>+ ) : null}+ </div>+ </div>+ )+ }+if (responseStatus === undefined) {return null}@@ -465,10 +511,10 @@ export function StatusTag({ item, detailed }: { item: PerformanceEvent; detailedconst statusDescription = `${responseStatus} ${isKeyOf(responseStatus, FriendlyHttpStatus) ? FriendlyHttpStatus[responseStatus] : ''}`let statusType: LemonTagType = 'success'- if (responseStatus >= 400 || responseStatus < 100) {- statusType = 'warning'- } else if (responseStatus >= 500) {+ if (responseStatus >= 500) {statusType = 'danger'+ } else if (responseStatus >= 400 || responseStatus < 100) {+ statusType = 'warning'}return (@@ -498,7 +544,7 @@ function StatusRow({ item }: { item: PerformanceEvent }): JSX.Element | null {let statusRow = nulllet methodRow = null- if (item.response_status) {+ if (item.response_status || hasNoRecordedResponse(item)) {statusRow = <StatusTag item={item} detailed={true} />}