: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(api): stop reporting transient body-read failures as noise (#102536)
Carlos Marchalb890dc65200b
diff --git a/frontend/src/lib/api-error.test.ts b/frontend/src/lib/api-error.test.tsindex eb3a22107198..ceadfac23dcd 100644--- a/frontend/src/lib/api-error.test.ts+++ b/frontend/src/lib/api-error.test.ts@@ -1,6 +1,7 @@import {ApiError,NetworkError,+ ResponseBodyReadError,isScopeNotFoundError,isTransientServerError,shouldReportApiFailure,@@ -133,6 +134,19 @@ describe('api-error', () => {// The residual `network` reason can be an ad blocker, a proxy, or our own edge, so it// stays reportable rather than being folded into the suppression above.['a classified NetworkError', new NetworkError('network'), true],+ // The server answered 2xx and the body stream broke on the wire afterwards. Grouping is+ // stack-based, so one flaky connection would otherwise open an issue per endpoint.+ [+ 'a body-read failure on a 2xx',+ new ResponseBodyReadError('Failed to read response body [GET /api/foo] (status 200)'),+ false,+ ],+ // A body that arrived whole but would not parse can be a real backend bug, so it stays.+ [+ 'a malformed JSON body on a 2xx',+ new ApiError('Malformed JSON response [GET /api/foo] (status 200)'),+ true,+ ],// No HTTP response to excuse the failure.['an error with no status', { message: 'boom' }, true],['a thrown string', 'went wrong', true],diff --git a/frontend/src/lib/api-error.ts b/frontend/src/lib/api-error.tsindex 68dd0190b92c..f15b637a11b7 100644--- a/frontend/src/lib/api-error.ts+++ b/frontend/src/lib/api-error.ts@@ -173,6 +173,11 @@ export function isBrowserNetworkFailure(error: unknown): boolean {* the user is told by whatever the caller renders for an empty result. Reporting these is what* floods the project: grouping is stack-based, so every loader that meets the same connectivity* blip opens an issue of its own, and one bad minute on a user's network manufactures dozens.+ * - a 2xx response whose body stream failed mid-read. The server already answered successfully, so+ * the truncation happened on the wire, not in application code. These group the same stack-based+ * way, so one flaky connection opens an issue per endpoint it touched. `api.ts` captures each one+ * as a `client_request_failure` with `failure_reason: 'response_body_read'`, so a persistent+ * truncation regression is still visible in aggregate without an issue per endpoint.** Each of these still toasts wherever it did before, and `client_request_failure` still records* every non-OK response with its status and pathname, so failure rates stay queryable even where@@ -188,6 +193,9 @@ export function shouldReportApiFailure(error: unknown): boolean {if (isBrowserNetworkFailure(error)) {return false}+ if (error instanceof ResponseBodyReadError) {+ return false+ }if (error === null || typeof error !== 'object') {return true}@@ -339,3 +347,17 @@ export class NetworkError extends ApiError {this.cause = cause}}++/**+ * A 2xx response whose body stream failed part way through, after the server had already answered+ * successfully: a dropped connection or a proxy hiccup truncating a chunked response, not an+ * application defect. It extends `ApiError` so that every existing catch path degrades as before.+ */+export class ResponseBodyReadError extends ApiError {+ constructor(message: string) {+ super(message)+ // Sets the `type` posthog-js reports in `$exception_list`, which error tracking grouping+ // rules match on.+ this.name = 'ResponseBodyReadError'+ }+}diff --git a/frontend/src/lib/api.test.ts b/frontend/src/lib/api.test.tsindex 5e84058d6f0f..61adffdbdfa4 100644--- a/frontend/src/lib/api.test.ts+++ b/frontend/src/lib/api.test.ts@@ -1,7 +1,8 @@import * as fetchEventSourceModule from '@microsoft/fetch-event-source'import posthog from 'posthog-js'-import api, { ApiConfig, ApiError, ApiRequest, NetworkError } from 'lib/api'+import api, { ApiConfig, ApiError, ApiRequest, NetworkError, ResponseBodyReadError } from 'lib/api'+import { shouldReportApiFailure } from 'lib/api-error'import { apiStatusLogic } from 'lib/logic/apiStatusLogic'import { NodeKind } from '~/queries/schema/schema-general'@@ -359,11 +360,34 @@ describe('API helper', () => {expect(error.message).toContain('[POST /api/environments/2/insights]')})- it('surfaces a body stream that fails mid-read as an ApiError instead of null', async () => {+ it('surfaces a body stream that fails mid-read as a ResponseBodyReadError instead of null', async () => {fakeFetch.mockResolvedValue(fakeResponse({ text: () => Promise.reject(new TypeError('network error')) }))const error = await api.get('api/environments/2/insights').catch((e) => e)+ // Still an ApiError, so every existing catch path degrades exactly as it did before.expect(error).toBeInstanceOf(ApiError)+ expect(error).toBeInstanceOf(ResponseBodyReadError)expect(error.status).toBeUndefined()+ expect(shouldReportApiFailure(error)).toBe(false)+ // Error tracking drops this shape, so the aggregate event is what keeps a persistent+ // truncation regression visible.+ expect(posthog.capture).toHaveBeenCalledWith(+ 'client_request_failure',+ expect.objectContaining({+ pathname: '/api/environments/2/insights/',+ method: 'GET',+ status: 200,+ failure_reason: 'response_body_read',+ })+ )+ })++ it('keeps a fully-read but unparsable body reportable', async () => {+ fakeFetch.mockResolvedValue(fakeResponse({ text: bodyOf('<html></html>') }))+ const error = await api.get('api/environments/2/insights').catch((e) => e)+ expect(error).toBeInstanceOf(ApiError)+ expect(error).not.toBeInstanceOf(ResponseBodyReadError)+ expect(shouldReportApiFailure(error)).toBe(true)+ expect(posthog.capture).not.toHaveBeenCalledWith('client_request_failure', expect.anything())})it.each([diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 03399c259cc2..ac44c28e3963 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -13,6 +13,7 @@ import {NetworkError,type NetworkFailureReason,readableErrorMessage,+ ResponseBodyReadError,} from 'lib/api-error'import { ActivityLogProps } from 'lib/components/ActivityLog/ActivityLog'import { ActivityLogItem } from 'lib/components/ActivityLog/humanizeActivity'@@ -333,7 +334,7 @@ export interface ApiUploadOptions extends ApiMethodOptions {onUploadProgress?: (progress: ApiUploadProgress) => void}-export { ApiError, NetworkError }+export { ApiError, NetworkError, ResponseBodyReadError }export class RateLimitError extends Error {constructor(public retryAfterSeconds: number) {@@ -404,7 +405,9 @@ function apiErrorFallback(response: Response, method: string, url: string): stri* must still surface as a failure. The thrown ApiError deliberately carries no `status`: the* HTTP status was 2xx, and recovery paths keyed on `status === undefined || status >= 500`* should classify a garbled body like the fetch-level network failure it effectively is. The- * real status stays in the message for triage.+ * real status stays in the message for triage. A read that fails mid-stream (rather than completing+ * with unparsable content) throws `ResponseBodyReadError`, so it can be recognized as wire-level+ * noise and left out of error tracking.*/async function getJSONFromSuccessResponse(response: Response, method: string, url: string): Promise<any> {const requestContext = (): string =>@@ -423,7 +426,18 @@ async function getJSONFromSuccessResponse(response: Response, method: string, ur}// The body stream failed mid-read (e.g. a network drop truncating a chunked response) —// the response is unusable, so surface it instead of handing callers a null.- throw new ApiError(`Failed to read response body ${requestContext()}`)+ // Error tracking excludes this shape, so this event is the only remaining signal that can+ // tell a persistent truncation regression from one user's bad connection. The URL is+ // normalized first, because `handleFetch` records the prepared one and an endpoint that+ // splits across two pathnames is not aggregatable.+ captureClientRequestFailure({+ pathname: requestPathname(normalizeUrl(url)),+ method,+ status: response.status,+ is_shared_view: isSharedView(),+ failure_reason: 'response_body_read',+ })+ throw new ResponseBodyReadError(`Failed to read response body ${requestContext()}`)}if (!text.trim()) {return null@@ -2530,8 +2544,9 @@ const api = {// return a non-array, which would break callers that iterate over the result.return Array.isArray(response) ? response : []},- async create(data: { ref?: string; type?: string }): Promise<FileSystemEntry> {- return await new ApiRequest().fileSystemLogView().create({ data })+ // The backend answers 204 No Content, so there is no entry to hand back.+ async create(data: { ref?: string; type?: string }): Promise<void> {+ await new ApiRequest().fileSystemLogView().create({ data })},},@@ -7466,14 +7481,21 @@ function classifyNetworkFailure(): NetworkFailureReason {return 'network'}+/**+ * `response_body_read` is not a `NetworkError` reason: the request completed and the server+ * answered, so only the read of the body failed.+ */+type ClientRequestFailureReason = NetworkFailureReason | 'response_body_read'+function captureClientRequestFailure(properties: {pathname: stringmethod: string- duration: number+ /** Absent when the failure surfaced after the response, outside the timed request. */+ duration?: number/** 0 for a request that never reached the server, so network failures are separable from HTTP ones. */status: numberis_shared_view: boolean- failure_reason?: NetworkFailureReason+ failure_reason?: ClientRequestFailureReason}): void {// when used inside the posthog toolbar, `posthog.capture` isn't loaded// check if the function is available before calling it.diff --git a/frontend/src/lib/hooks/useFileSystemLogView.ts b/frontend/src/lib/hooks/useFileSystemLogView.tsindex 00c4a5888ce6..9ba99678e460 100644--- a/frontend/src/lib/hooks/useFileSystemLogView.ts+++ b/frontend/src/lib/hooks/useFileSystemLogView.ts@@ -39,7 +39,9 @@ export function trackFileSystemLogView({ type, ref, enabled = true }: TrackFileS}recentItemsModel.findMounted()?.actions.recordView(type, String(ref))- void api.fileSystemLogView.create({ type, ref: String(ref) })+ // Fire-and-forget view tracking: nothing renders off it, so a failure must not surface as an+ // unhandled rejection.+ api.fileSystemLogView.create({ type, ref: String(ref) }).catch(() => {})}export function useFileSystemLogView({ type, ref, enabled = true }: TrackFileSystemLogViewOptions): void {