: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(aio): correct summary error reporting and cancel stale requests (#87703)
Bernat Torresd347ad3e88b9
diff --git a/products/ai_observability/frontend/summary-view/summaryViewLogic.test.ts b/products/ai_observability/frontend/summary-view/summaryViewLogic.test.tsindex 88edca749469..455c24c62b3a 100644--- a/products/ai_observability/frontend/summary-view/summaryViewLogic.test.ts+++ b/products/ai_observability/frontend/summary-view/summaryViewLogic.test.ts@@ -1,7 +1,8 @@import { expectLogic } from 'kea-test-utils'+import posthog from 'posthog-js'-import api from 'lib/api'-import { ApiError } from 'lib/api-error'+import api, { type ApiMethodOptions } from 'lib/api'+import { ApiError, NETWORK_ERROR_MESSAGES, NetworkError } from 'lib/api-error'import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'import type { LLMTrace } from '~/queries/schema/schema-general'@@ -41,6 +42,36 @@ describe('summaryViewLogic', () => {return call?.[1]}+ /** Every `api.create` option object the summarization endpoint was called with, in order. */+ function summarizationOptions(): (ApiMethodOptions | undefined)[] {+ return createSpy.mock.calls.filter(([url]) => url.includes(SUMMARIZATION_PATH)).map((call) => call[2])+ }++ /**+ * A summarization request that settles only when its own signal aborts, the way `handleFetch`+ * rejects an aborted fetch. A shared promise that ignores the signal would let a cancellation+ * test pass without any invocation ever settling.+ */+ function summarizationPendingUntilAborted(): void {+ createSpy.mockImplementation((url: string, _data: unknown, options?: { signal?: AbortSignal }) => {+ if (!url.includes(SUMMARIZATION_PATH)) {+ return Promise.resolve({})+ }+ return new Promise((_resolve, reject) => {+ options?.signal?.addEventListener('abort', () => {+ reject(options.signal?.reason ?? new DOMException('Aborted', 'AbortError'))+ })+ })+ })+ }++ /** Let a rejected request propagate through kea-loaders without waiting on a timer. */+ async function flushMicrotasks(): Promise<void> {+ for (let i = 0; i < 10; i++) {+ await Promise.resolve()+ }+ }+async function generateSummary(): Promise<void> {logic = summaryViewLogic({ trace, tree: [] })logic.mount()@@ -62,7 +93,9 @@ describe('summaryViewLogic', () => {})afterEach(() => {- logic?.unmount()+ if (logic?.isMounted()) {+ logic.unmount()+ }jest.restoreAllMocks()resumeKeaLoadersErrors()})@@ -79,35 +112,94 @@ describe('summaryViewLogic', () => {})})- it('shows a readable message when the response carries no error body', async () => {- mockSummarization(Promise.reject(new ApiError(undefined, 504, undefined, null)))+ test.each([+ [+ 'a bodyless gateway timeout',+ () => new ApiError(undefined, 504, undefined, null),+ 'Generating this summary took too long. Try again in a moment.',+ ],+ [+ 'a bodyless payload-size rejection',+ () => new ApiError('API request failed with status: 413', 413),+ 'This trace is too large to summarize. Open a single generation and summarize that instead.',+ ],+ [+ 'a body the backend sent',+ () => new ApiError('Failed to generate summary', 413, undefined, { detail: 'Failed to generate summary' }),+ 'Failed to generate summary',+ ],+ [+ 'a request the browser never completed',+ () => new NetworkError('offline'),+ 'Lost the connection while generating this summary. Check your connection and try again.',+ ],+ ])('shows a readable message for %s', async (_label, buildError, expected) => {+ mockSummarization(Promise.reject(buildError()))await generateSummary()- expect(logic.values.summaryError).toBe('Generating this summary took too long. Try again in a moment.')+ expect(logic.values.summaryError).toBe(expected)})- it('maps a bodyless payload-size rejection to a readable message, not a bare status', async () => {- mockSummarization(Promise.reject(new ApiError('API request failed with status: 413', 413)))+ it('reports a dropped connection to error tracking as a NetworkError', async () => {+ const captureSpy = jest.spyOn(posthog, 'captureException').mockImplementation(() => undefined as any)+ mockSummarization(Promise.reject(new NetworkError('offline')))await generateSummary()- expect(logic.values.summaryError).not.toContain('413')- expect(logic.values.summaryError).toBe(- 'This trace is too large to summarize. Open a single generation and summarize that instead.'- )+ // `dropUnactionableNetworkExceptions` matches the name and the message, so rewriting either+ // one files an issue for a failure the platform already treats as unactionable.+ // Mounting already asks for a cached summary, so that request fails here too. Assert the+ // call happened rather than a count, so an empty spy fails on the expectation.+ expect(captureSpy).toHaveBeenCalled()+ const reported = captureSpy.mock.calls[0]?.[0] as Error+ expect(reported.name).toBe('NetworkError')+ expect(reported.message).toBe(NETWORK_ERROR_MESSAGES.offline)})- it('keeps a response body the backend sent instead of guessing from the status', async () => {- mockSummarization(- Promise.reject(- new ApiError('Failed to generate summary', 413, undefined, { detail: 'Failed to generate summary' })- )- )+ it('keeps the panel loading when a newer summary replaces an in-flight one', async () => {+ summarizationPendingUntilAborted()+ logic = summaryViewLogic({ trace, tree: [] })+ logic.mount()+ logic.actions.generateSummary({ mode: 'minimal' })+ await flushMicrotasks()+ logic.actions.generateSummary({ mode: 'detailed' })+ await flushMicrotasks()++ // Mounting already asks for a cached summary, so compare the last two requests.+ const [previous, latest] = summarizationOptions().slice(-2)+ expect(previous?.signal?.aborted).toBe(true)+ expect(latest?.signal?.aborted).toBe(false)+ // The cancelled request must not settle the loader. SummaryViewDisplay shows its empty+ // state on `!summaryData && !summaryDataLoading && !summaryError`, so a cleared flag+ // replaces the running summary with "Generate an AI-powered summary of this trace".+ expect(logic.values.summaryDataLoading).toBe(true)+ expect(logic.values.summaryError).toBeNull()+ })++ it('keeps the cancellation reason out of the panel', async () => {await generateSummary()- expect(logic.values.summaryError).toBe('Failed to generate summary')+ // A cancellation that reaches the reducer carries the internal sentinel as its message.+ // Only the breakpoint keeps a superseded request from getting here, so the guard is what+ // stops that sentinel reaching the panel for any other cancellation.+ const cancellation = new DOMException('a newer summary request started', 'AbortError')+ logic.actions.generateSummaryFailure(cancellation.message, cancellation)++ expect(logic.values.summaryError).toBeNull()+ })++ it('cancels an in-flight request when the trace view closes', async () => {+ summarizationPendingUntilAborted()+ logic = summaryViewLogic({ trace, tree: [] })+ logic.mount()+ logic.actions.generateSummary({ mode: 'minimal' })+ await flushMicrotasks()++ logic.unmount()++ expect(summarizationOptions().at(-1)?.signal?.aborted).toBe(true)})it('clears a stale summary when regeneration fails', async () => {diff --git a/products/ai_observability/frontend/summary-view/summaryViewLogic.ts b/products/ai_observability/frontend/summary-view/summaryViewLogic.tsindex ebab4bdf4ef0..a163cb314fac 100644--- a/products/ai_observability/frontend/summary-view/summaryViewLogic.ts+++ b/products/ai_observability/frontend/summary-view/summaryViewLogic.ts@@ -1,7 +1,8 @@import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'-import { ApiError, isTransientServerError } from 'lib/api-error'+import { isAbortError } from 'lib/api'+import { ApiError, NetworkError, isTransientServerError } from 'lib/api-error'import { maxGlobalLogic } from 'scenes/max/maxGlobalLogic'import { teamLogic } from 'scenes/teamLogic'@@ -106,6 +107,11 @@ export type summaryViewLogicType = MakeLogicType<const GENERIC_SUMMARY_ERROR = "Couldn't generate a summary. Try again, and if it keeps happening contact support."+const NETWORK_SUMMARY_ERROR = 'Lost the connection while generating this summary. Check your connection and try again.'++/** Aborting with an `AbortError` keeps the cancellation out of toasts and error tracking. */+const SUPERSEDED_SUMMARY_REQUEST = 'a newer summary request started'+function bodylessStatusMessage(error: ApiError): string {if (error.status === 413) {return 'This trace is too large to summarize. Open a single generation and summarize that instead.'@@ -120,17 +126,22 @@ function bodylessStatusMessage(error: ApiError): string {}/**- * Keep a raw status code out of the toast and inline error. `ApiError` falls back to its own- * `API request failed with status: 413` string when the response carries no body, so replace that- * with a readable sentence. A response that does carry a `detail` is left alone, since it says- * more than any status-keyed guess. The status is carried over so transient gateway errors stay out of- * error tracking.+ * Build the sentence the panel shows, rather than rewriting the rejected error into a new one.+ * The error object continues to error tracking, and a `NetworkError` carries its failure reason in+ * its own `name` and message, which is all `dropUnactionableNetworkExceptions` can match on.+ * Rebuilding it as a plain `ApiError` erased both, so a request the browser dropped filed an issue+ * that read as though summarization itself had broken.*/-function toReadableError(error: unknown): unknown {- if (!(error instanceof ApiError) || error.detail) {- return error+function summaryErrorMessage(errorObject: unknown, fallback: string | null): string {+ if (errorObject instanceof NetworkError) {+ return NETWORK_SUMMARY_ERROR}- return new ApiError(bodylessStatusMessage(error), error.status, error.headers, error.data)+ // `ApiError` falls back to `API request failed with status: 413` when the response carries no+ // body. A response that does carry a `detail` says more than any status-keyed guess.+ if (errorObject instanceof ApiError && !errorObject.detail) {+ return bodylessStatusMessage(errorObject)+ }+ return fallback || GENERIC_SUMMARY_ERROR}export const summaryViewLogic = kea<summaryViewLogicType>([@@ -195,8 +206,10 @@ export const summaryViewLogic = kea<summaryViewLogicType>([{generateSummary: () => null,generateSummarySuccess: () => null,- generateSummaryFailure: (_, { error }) =>- error || "Couldn't generate a summary. Try again, and if it keeps happening contact support.",+ // A cancelled request is expected control flow, so it leaves the panel as the+ // request that replaced it found it.+ generateSummaryFailure: (state, { error, errorObject }) =>+ isAbortError(errorObject) ? state : summaryErrorMessage(errorObject, error),},],}),@@ -214,9 +227,12 @@ export const summaryViewLogic = kea<summaryViewLogicType>([},],}),- loaders(({ props, values }) => ({+ loaders(({ props, values, cache }) => ({summaryData: {- generateSummary: async ({ mode, forceRefresh }: { mode: SummaryMode; forceRefresh?: boolean }) => {+ generateSummary: async (+ { mode, forceRefresh }: { mode: SummaryMode; forceRefresh?: boolean },+ breakpoint+ ) => {// Initialize here rather than in the function signature to avoid TS2371// Kea should be fixed to avoid including the default value in the function signatureif (forceRefresh === undefined) {@@ -246,9 +262,33 @@ export const summaryViewLogic = kea<summaryViewLogicType>([...getSummarizationLookupDateRange(entity.createdAt),}- const data = await llmAnalyticsSummarizationCreate(String(teamId), request).catch((error: unknown) => {- throw toReadableError(error)+ // Summarizing runs a model call, so the request outlives the tab strip: someone can+ // switch modes or leave the trace long before it answers. Registering the controller+ // as a disposable cancels it on unmount, and re-adding the key cancels the request+ // the new one replaces, instead of leaving both to finish and race.+ const abortController = new AbortController()+ cache.disposables.add(+ () => () => abortController.abort(new DOMException(SUPERSEDED_SUMMARY_REQUEST, 'AbortError')),+ 'summaryRequest',+ // A hidden tab must not cancel a summary the user is waiting on.+ { pauseOnPageHidden: false }+ )++ const data = await llmAnalyticsSummarizationCreate(String(teamId), request, {+ signal: abortController.signal,+ }).catch((error: unknown) => {+ // The request that replaced this one owns the outcome now. kea-loaders keeps+ // one loading flag per loader, so settling this invocation as a failure would+ // clear the flag the replacement just set, and the panel would fall back to its+ // empty state for the rest of the model call. The breakpoint drops this+ // invocation instead of reporting it.+ if (isAbortError(error)) {+ breakpoint()+ }+ throw error})+ // Discard a response the user has already moved past.+ breakpoint()// The endpoint can resolve to an empty body (e.g. no summary available yet),// so guard before reading fields to avoid a null dereference.