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(insights): retry transient query failures and show cooldowns (#105726)

posthog[bot]0c716b7050d9
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index f037fb7cf333..ef35544f82d1 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -460,6 +460,14 @@ snapshots:
hash: v1.k794b7964.5f3e7c9a9923ca547abac285ccd1d4e220df5132c95f96a25d4e71418ab595e0.mVhI7r6cz_F9H3wZ4y7DaEGsVhVzj1MD2mK539UwvJc
components-cards-insight-card--access-control-viewer-access--light:
hash: v1.k794b7964.bf2be6132e7d881f5648da794c30b861a8970b30aad98024e1470afa20fb1184.QjEzM0TKMP1UfPhiAgRyZW3hsOIKbNn5o8Un7s1Yswc
+ components-cards-insight-card--capacity-cooldown--medium--dark:
+ hash: v1.k794b7964.f1f23f29992ce43001fbc773629d6850285d3cbc9a234f66b30e21be8d4d2f5f.Es6aDswFYvx82yk7f3j4RwLHlYAqF0aaO4XRkOp0QH0
+ components-cards-insight-card--capacity-cooldown--medium--light:
+ hash: v1.k794b7964.7464f22a5d98705e763d26dece33c66eb95c892ef38d95a632aac188bfc22726.IS9DIlMe5hPP4Ukgnfbc20iNHSI-zgA_SbGxAP-X_a8
+ components-cards-insight-card--capacity-cooldown--narrow--dark:
+ hash: v1.k794b7964.7e206075878d618ba32721bbe8231f34ee774bb8f4f169b5410015779386b3e6.YXpAuy8cawNj_2PdEhATFg1_bxz5L2KHPsDmZ_R6G5M
+ components-cards-insight-card--capacity-cooldown--narrow--light:
+ hash: v1.k794b7964.c79d5e095dca03b4d0c640a4fdd6bbfce9a4c611d4dfcf54118b012688073920.kbucWQpmGl5l1HtxNnrrkN544BGhjh0Jn4DhhufGG8U
components-cards-insight-card--error-states--dark:
hash: v1.k794b7964.dca2213d0a2f6dc232e1b2ac1505aa4a5b97b1dc9b9f2ac09dab969ed1eb12dd.O8WWpdu2VcmOz94y1p3UhIYwWZxSBZKZYOTJZNnO9qI
components-cards-insight-card--error-states--light:
@@ -10135,13 +10143,13 @@ snapshots:
scenes-app-errortracking--group-page-releases-stacked--light:
hash: v1.k794b7964.bcda9410935407d6bebba2664a7623239144efd1c2572adbd14f1504f30be695.c7q4lo3ZHBJlP4187kCTO3ast1noiEce1kRQFogt5ms
scenes-app-errortracking--group-page-with-many-self-driving-reports--dark:
- hash: v1.k794b7964.0bf000742db3f9dc86e80fa360b83ec818324603103ab52d9d45ce0607631ee7.tkXTYQiPmTNrhpePaKOsVYoyoMT_Dx0clzaZqOjkcTw
+ hash: v1.k794b7964.3eae78db2136c1300bf579f8cc0e202c4c67a82073b116035a7a7f63a65ae07b.FVXVPYj2qDzQsgtY7ynrrO_AZFd7Tc3glFPLM3EHfJ4
scenes-app-errortracking--group-page-with-many-self-driving-reports--light:
- hash: v1.k794b7964.2037306c41f112214785618f556933ec91e95cabf187d87ba45528cf99e3252e.B8EvQBDMPa24k40ZZN-4eATHq2mgE-kxe6AAVCkZDI8
+ hash: v1.k794b7964.aec5b990cfa519ee8d8d40acf501629c06e0cb0e9a9b85414ce5cbfa849e36a5.XT1pMVQ14H09EAjCXCFxOag58SX0O_P6--vQpURE2vk
scenes-app-errortracking--group-page-with-self-driving--dark:
- hash: v1.k794b7964.9b65251bcd4677987856d5856c908b4824dabc16727f74bef08997b28b511ae5.6KjiNo3mj5O1m9NHP9MjApuJCzZGaU6ENGFp5J6oI-A
+ hash: v1.k794b7964.3ed34a9765956027cd4ef465b6fed776dcd1c42c40d32eddd00570768dfe040f.o3eWrjfExshyTaw2HbdRaYr2q_4edvY8PPwqI99Xsyg
scenes-app-errortracking--group-page-with-self-driving--light:
- hash: v1.k794b7964.7163253868938e0d915a6a9a896531f5262e52a658135391569fb4dc2b0887a5.pdiZKwe3cMksN4hEXYQerkKZtPbr8_KNihl6M2aSgNg
+ hash: v1.k794b7964.59535160229dce259d10969fab1281a28359bf3f2cf53b37c76d72b4e0201aff.8avZpQyawkdryfF5mp5mx2CrSyKfQKrLJmQCx7GkGaw
scenes-app-errortracking--insights-page--dark:
hash: v1.k794b7964.547ba7d50edff3d4fd57c33937b1536edb9837c5c34fd57543b29a5fb257e848.V99ai7csLzzA-J4mPePBh5GIyIie_ulJCWMMU7bfioE
scenes-app-errortracking--insights-page--light:
@@ -11825,11 +11833,11 @@ snapshots:
scenes-app-insights-error-empty-states--query-server-error--dark:
hash: v1.k794b7964.8e86d1d4ab6af6159804e2801298842f1d086cbbb796c91fb60de816ab1abf5f.H93T__KkhRkfdLXG-mls00Kg7VOvi1uPJRzKchhICco
scenes-app-insights-error-empty-states--query-server-error--light:
- hash: v1.k794b7964.d8a09489dec3ccafe72938195eab9d2205c4f94c1d3d2921b37b4019bb2a10c3.h_DDpFNJx1Si9ffnyxJi-NhpWbSWzRFPekIqDSz71Iw
+ hash: v1.k794b7964.1da6d8ff318554274dfcf23f2bd5e467c57e41a8636811ff7b414a9febb00939.4QptNtnaVprfFvdPzXqDJ1tFsrS7gMdRBjpp0tId-m4
scenes-app-insights-error-empty-states--server-error--dark:
hash: v1.k794b7964.8e86d1d4ab6af6159804e2801298842f1d086cbbb796c91fb60de816ab1abf5f.J7QYlsp_PAgkdRCMRB8buDteS7Gdpd4_tVO1BjQ_q8U
scenes-app-insights-error-empty-states--server-error--light:
- hash: v1.k794b7964.d8a09489dec3ccafe72938195eab9d2205c4f94c1d3d2921b37b4019bb2a10c3.tUHjsrFGt5D8TGMnQm1yjO8zFex-m83mZFRfNh8Hmhs
+ hash: v1.k794b7964.1da6d8ff318554274dfcf23f2bd5e467c57e41a8636811ff7b414a9febb00939.4ZjVo7gmmFa9ccPeg0xuvfci3cQ1OCyVOj4d2dKh-ks
scenes-app-insights-error-empty-states--validation-error--dark:
hash: v1.k794b7964.78c398feb22adb44344fad6c155ad42ecdbd9d77d80e4e0a60227b4a32abf14f.wmWI9S-nFvoZ5tNpxol33U3eINboLyZM9cggyHqv8hU
scenes-app-insights-error-empty-states--validation-error--light:
diff --git a/frontend/src/lib/api-error.test.ts b/frontend/src/lib/api-error.test.ts
index a9e64a24c318..c472d664a6f3 100644
--- a/frontend/src/lib/api-error.test.ts
+++ b/frontend/src/lib/api-error.test.ts
@@ -8,6 +8,54 @@ import {
} from './api-error'
describe('api-error', () => {
+ describe('capacity retry deadlines', () => {
+ afterEach(() => {
+ jest.useRealTimers()
+ })
+
+ it.each([
+ { status: 503, seconds: 0, expected: 0 },
+ { status: 503, seconds: 5, expected: 5 },
+ { status: 503, seconds: 45, expected: 45 },
+ { status: 500, seconds: 45, expected: null },
+ ])(
+ 'anchors a numeric capacity hint to receipt time only for 503 (status=$status, seconds=$seconds)',
+ ({ status, seconds, expected }) => {
+ jest.useFakeTimers()
+ const receivedAt = Date.now()
+ const error = new ApiError('', status, new Headers({ 'Retry-After': String(seconds) }))
+
+ jest.advanceTimersByTime(1000)
+
+ expect(error.retryAfterSeconds).toBe(expected)
+ expect(error.retryAfterTimestamp).toBe(expected === null ? null : receivedAt + expected * 1000)
+ }
+ )
+
+ it('ignores HTTP-date capacity hints even with a server Date header', () => {
+ const error = new ApiError(
+ '',
+ 503,
+ new Headers({
+ Date: 'Mon, 05 Oct 2026 12:00:00 GMT',
+ 'Retry-After': 'Mon, 05 Oct 2026 12:00:45 GMT',
+ })
+ )
+
+ expect(error.retryAfterTimestamp).toBeNull()
+ expect(error.retryAfterSeconds).toBeNull()
+ })
+
+ it.each([undefined, '', '-1', '1.5', '1e3', 'unknown', 'Infinity', '9'.repeat(400)])(
+ 'ignores an invalid Retry-After header: %s',
+ (retryAfter) => {
+ const headers = new Headers(retryAfter === undefined ? {} : { 'Retry-After': retryAfter })
+ const error = new ApiError('', 503, headers)
+ expect(error.retryAfterTimestamp).toBeNull()
+ expect(error.retryAfterSeconds).toBeNull()
+ }
+ )
+ })
describe('ApiError.fromResponse', () => {
it.each([
['error', { error: 'error message' }, 'error message'],
diff --git a/frontend/src/lib/api-error.ts b/frontend/src/lib/api-error.ts
index 7129ff741973..08c7fe0103c2 100644
--- a/frontend/src/lib/api-error.ts
+++ b/frontend/src/lib/api-error.ts
@@ -32,7 +32,7 @@ export function isApprovalRequiredError(error: { status?: number; data?: any } |
return error?.status === 409 && Boolean(error?.data?.change_request_id)
}
-/** Infrastructure-level failures where the gateway couldn't reach the backend. */
+/** Potentially transient failures; a gateway error does not prove that the backend did no work. */
const TRANSIENT_GATEWAY_STATUSES: ReadonlySet<number> = new Set([502, 503, 504])
function isTransientGatewayStatus(status: number | undefined): boolean {
@@ -171,7 +171,7 @@ export function isBrowserNetworkFailure(error: unknown): boolean {
* - 404 `Project not found.` / `Organization not found.` — the scope in the URL is gone, so every
* request under it fails the same way. The scene routing takes the user off that URL, and until
* it does, a poll on the dead scope would otherwise file one exception per tick.
- * - 502/503/504 — the gateway couldn't reach the backend, so application code is not at fault.
+ * - 502/503/504 are gateway or upstream failures. The backend may already have started the request.
*
* Left unreported for a second reason, that there is nothing to fix:
* - a `fetch` the browser never completed. No request reached us, so no code of ours failed, and
@@ -246,6 +246,10 @@ export function readableErrorMessage(error: unknown): string | undefined {
}
export class ApiError extends Error {
+ /** Numeric capacity hints can be used for automatic retries without relying on server or device clocks. */
+ readonly retryAfterSeconds: number | null
+ /** An absolute deadline keeps rerenders and remounts from restarting a capacity cooldown. */
+ readonly retryAfterTimestamp: number | null
/** Django REST Framework `detail` - used in downstream error handling. */
detail: string | null
/** Django REST Framework `code` - used in downstream error handling. */
@@ -271,6 +275,11 @@ export class ApiError extends Error {
this.code = data?.code || null
this.link = data?.link || null
this.attr = data?.attr || null
+ const retryAfter = status === 503 ? headers?.get('Retry-After') : null
+ const seconds = retryAfter && /^\d+$/.test(retryAfter) ? Number(retryAfter) : NaN
+ this.retryAfterSeconds = Number.isSafeInteger(seconds) ? seconds : null
+ const retryAfterTimestamp = this.retryAfterSeconds !== null ? Date.now() + this.retryAfterSeconds * 1000 : NaN
+ this.retryAfterTimestamp = Number.isSafeInteger(retryAfterTimestamp) ? retryAfterTimestamp : null
}
static async fromResponse(response: Response, fallbackMessage?: string): Promise<ApiError> {
diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightCard.stories.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightCard.stories.tsx
index a37d5a4edea8..9276b4b6f96f 100644
--- a/frontend/src/lib/components/Cards/InsightCard/InsightCard.stories.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/InsightCard.stories.tsx
@@ -283,6 +283,32 @@ export const ErrorStates: Story = {
},
}
+export const CapacityCooldown: Story = {
+ parameters: {
+ mockDate: '2026-01-01T12:00:00Z',
+ testOptions: { viewportWidths: ['narrow', 'medium'] },
+ },
+ render: () => {
+ const [error] = useState(
+ () => new ApiError('', 503, new Headers({ 'Retry-After': '45' }), { queryId: 'capacity-example-query' })
+ )
+ return (
+ <div className="w-full max-w-160">
+ <InsightCardComponent
+ tile={defaultTile}
+ insight={{ ...EXAMPLE_TRENDS, name: 'Page views', result: null } as unknown as InsightModel}
+ apiErrored
+ apiError={error}
+ refresh={() => {}}
+ rename={() => {}}
+ duplicate={() => {}}
+ placement="SavedInsightGrid"
+ />
+ </div>
+ )
+ },
+}
+
// Access Control Stories
export const AccessControlNoAccess: Story = {
render: () => {
diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightCard.test.ts b/frontend/src/lib/components/Cards/InsightCard/InsightCard.test.ts
deleted file mode 100644
index 8c91c52bafaf..000000000000
--- a/frontend/src/lib/components/Cards/InsightCard/InsightCard.test.ts
+++ /dev/null
@@ -1,87 +0,0 @@
-import { NodeKind } from '~/queries/schema/schema-general'
-import { ChartDisplayType, DashboardPlacement, InsightModel } from '~/types'
-
-import { shouldRenderInsightCardViz } from './InsightCard'
-
-const tableQuery = { kind: NodeKind.DataTableNode } as InsightModel['query']
-const autoSqlQuery = {
- kind: NodeKind.DataVisualizationNode,
- display: ChartDisplayType.Auto,
-} as InsightModel['query']
-const canvasQuery = {
- kind: NodeKind.DataVisualizationNode,
- display: ChartDisplayType.ActionsLineGraph,
-} as InsightModel['query']
-
-describe('InsightCard', () => {
- it.each([
- {
- name: 'keeps a visible table mounted when the page is hidden',
- input: {
- isStorybook: false,
- placement: DashboardPlacement.Dashboard,
- inView: true,
- isPageVisible: false,
- query: tableQuery,
- },
- expected: true,
- },
- {
- name: 'keeps an auto SQL visualization mounted because it may render a table',
- input: {
- isStorybook: false,
- placement: DashboardPlacement.Dashboard,
- inView: true,
- isPageVisible: false,
- query: autoSqlQuery,
- },
- expected: true,
- },
- {
- name: 'unmounts a visible canvas chart when the page is hidden',
- input: {
- isStorybook: false,
- placement: DashboardPlacement.Dashboard,
- inView: true,
- isPageVisible: false,
- query: canvasQuery,
- },
- expected: false,
- },
- {
- name: 'unmounts an offscreen table',
- input: {
- isStorybook: false,
- placement: DashboardPlacement.Dashboard,
- inView: false,
- isPageVisible: true,
- query: tableQuery,
- },
- expected: false,
- },
- {
- name: 'renders a visible canvas chart on a visible page',
- input: {
- isStorybook: false,
- placement: DashboardPlacement.Dashboard,
- inView: true,
- isPageVisible: true,
- query: canvasQuery,
- },
- expected: true,
- },
- {
- name: 'renders exports regardless of visibility',
- input: {
- isStorybook: false,
- placement: DashboardPlacement.Export,
- inView: false,
- isPageVisible: false,
- query: canvasQuery,
- },
- expected: true,
- },
- ])('$name', ({ input, expected }) => {
- expect(shouldRenderInsightCardViz(input)).toBe(expected)
- })
-})
diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightCard.test.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightCard.test.tsx
new file mode 100644
index 000000000000..510df9bb4399
--- /dev/null
+++ b/frontend/src/lib/components/Cards/InsightCard/InsightCard.test.tsx
@@ -0,0 +1,199 @@
+import '@testing-library/jest-dom'
+
+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { mockAllIsIntersecting } from 'react-intersection-observer/test-utils'
+
+import { ApiError } from 'lib/api-error'
+import { insightDataLogic } from 'scenes/insights/insightDataLogic'
+
+import EXAMPLE_TRENDS from '~/mocks/fixtures/api/projects/team_id/insights/trendsLine.json'
+import { useMocks } from '~/mocks/jest'
+import { NodeKind } from '~/queries/schema/schema-general'
+import { initKeaTests } from '~/test/init'
+import { ChartDisplayType, DashboardPlacement, InsightModel } from '~/types'
+
+import { InsightCard, shouldRenderInsightCardViz } from './InsightCard'
+
+const tableQuery = { kind: NodeKind.DataTableNode } as InsightModel['query']
+const autoSqlQuery = {
+ kind: NodeKind.DataVisualizationNode,
+ display: ChartDisplayType.Auto,
+} as InsightModel['query']
+const canvasQuery = {
+ kind: NodeKind.DataVisualizationNode,
+ display: ChartDisplayType.ActionsLineGraph,
+} as InsightModel['query']
+
+describe('InsightCard', () => {
+ describe('failed tiles', () => {
+ const insight = { ...EXAMPLE_TRENDS, result: null } as unknown as InsightModel
+
+ beforeEach(() => {
+ useMocks({})
+ initKeaTests()
+ jest.useFakeTimers()
+ })
+
+ afterEach(() => {
+ cleanup()
+ jest.useRealTimers()
+ })
+
+ it('shows a query failure while another attempt is queued', () => {
+ render(
+ <InsightCard
+ insight={insight}
+ placement="SavedInsightGrid"
+ doNotLoad
+ apiErrored
+ apiError={new ApiError('', 503)}
+ loadingQueued
+ />
+ )
+ act(() => mockAllIsIntersecting(true))
+
+ expect(screen.getByText("This query couldn't run right now")).toBeVisible()
+ })
+
+ it.each([
+ { source: 'card', cardStatus: 503, cardWait: 45, embeddedWait: null },
+ { source: 'embedded query', cardStatus: null, cardWait: null, embeddedWait: 45 },
+ { source: 'longer card wait', cardStatus: 503, cardWait: 45, embeddedWait: 30 },
+ { source: 'longer embedded wait', cardStatus: 503, cardWait: 30, embeddedWait: 45 },
+ { source: 'embedded wait with a 502 card error', cardStatus: 502, cardWait: null, embeddedWait: 45 },
+ { source: 'embedded wait with a 500 card error', cardStatus: 500, cardWait: null, embeddedWait: 45 },
+ ])('holds refresh controls until the $source cooldown ends', ({ cardStatus, cardWait, embeddedWait }) => {
+ const refresh = jest.fn()
+ const { container } = render(
+ <InsightCard
+ insight={insight}
+ placement="SavedInsightGrid"
+ doNotLoad
+ apiErrored={cardStatus !== null}
+ apiError={
+ cardStatus === null
+ ? undefined
+ : new ApiError(
+ '',
+ cardStatus,
+ cardWait === null ? undefined : new Headers({ 'Retry-After': String(cardWait) })
+ )
+ }
+ refresh={refresh}
+ />
+ )
+ act(() => mockAllIsIntersecting(true))
+ if (embeddedWait !== null) {
+ act(() => {
+ insightDataLogic({ dashboardItemId: insight.short_id }).actions.loadDataFailure(
+ 'Capacity rejected',
+ new ApiError('', 503, new Headers({ 'Retry-After': String(embeddedWait) }))
+ )
+ })
+ }
+ const headerRefresh = container.querySelector('[data-attr="insight-card-refresh"]')!
+ expect(headerRefresh).toHaveAttribute('aria-disabled', 'true')
+ fireEvent.click(headerRefresh)
+ expect(refresh).not.toHaveBeenCalled()
+
+ fireEvent.click(screen.getByLabelText('more'))
+ const menuRefresh = screen.getByTestId('dashboard-tile-refresh-data')
+ expect(menuRefresh).toHaveAttribute('aria-disabled', 'true')
+ fireEvent.click(menuRefresh)
+ expect(refresh).not.toHaveBeenCalled()
+
+ act(() => jest.advanceTimersByTime(30_000))
+ if (cardStatus !== null) {
+ expect(screen.getByText('PostHog is busy. You can retry in 15 seconds.')).toBeVisible()
+ expect(screen.getByTestId('insight-retry-button')).toHaveAttribute('aria-disabled', 'true')
+ }
+ expect(headerRefresh).toHaveAttribute('aria-disabled', 'true')
+ fireEvent.click(headerRefresh)
+ expect(refresh).not.toHaveBeenCalled()
+ act(() => jest.advanceTimersByTime(15_000))
+ expect(headerRefresh).toHaveAttribute('aria-disabled', 'false')
+ fireEvent.click(screen.getByLabelText('more'))
+ expect(screen.getByTestId('dashboard-tile-refresh-data')).toHaveAttribute('aria-disabled', 'false')
+ expect(refresh).not.toHaveBeenCalled()
+ fireEvent.click(screen.getByTestId('dashboard-tile-refresh-data'))
+ expect(refresh).toHaveBeenCalledTimes(1)
+ if (cardStatus !== null) {
+ expect(screen.getByText('You can try this query again now.')).toBeVisible()
+ expect(screen.getByTestId('insight-retry-button')).toHaveAttribute('aria-disabled', 'false')
+ fireEvent.click(screen.getByTestId('insight-retry-button'))
+ expect(refresh).toHaveBeenCalledTimes(2)
+ }
+ })
+ })
+
+ it.each([
+ {
+ name: 'keeps a visible table mounted when the page is hidden',
+ input: {
+ isStorybook: false,
+ placement: DashboardPlacement.Dashboard,
+ inView: true,
+ isPageVisible: false,
+ query: tableQuery,
+ },
+ expected: true,
+ },
+ {
+ name: 'keeps an auto SQL visualization mounted because it may render a table',
+ input: {
+ isStorybook: false,
+ placement: DashboardPlacement.Dashboard,
+ inView: true,
+ isPageVisible: false,
+ query: autoSqlQuery,
+ },
+ expected: true,
+ },
+ {
+ name: 'unmounts a visible canvas chart when the page is hidden',
+ input: {
+ isStorybook: false,
+ placement: DashboardPlacement.Dashboard,
+ inView: true,
+ isPageVisible: false,
+ query: canvasQuery,
+ },
+ expected: false,
+ },
+ {
+ name: 'unmounts an offscreen table',
+ input: {
+ isStorybook: false,
+ placement: DashboardPlacement.Dashboard,
+ inView: false,
+ isPageVisible: true,
+ query: tableQuery,
+ },
+ expected: false,
+ },
+ {
+ name: 'renders a visible canvas chart on a visible page',
+ input: {
+ isStorybook: false,
+ placement: DashboardPlacement.Dashboard,
+ inView: true,
+ isPageVisible: true,
+ query: canvasQuery,
+ },
+ expected: true,
+ },
+ {
+ name: 'renders exports regardless of visibility',
+ input: {
+ isStorybook: false,
+ placement: DashboardPlacement.Export,
+ inView: false,
+ isPageVisible: false,
+ query: canvasQuery,
+ },
+ expected: true,
+ },
+ ])('$name', ({ input, expected }) => {
+ expect(shouldRenderInsightCardViz(input)).toBe(expected)
+ })
+})
diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx
index 94de9d84005d..22b36339ddfe 100644
--- a/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx
@@ -9,6 +9,7 @@ import { useInView } from 'react-intersection-observer'
import { ApiError } from 'lib/api'
import { Resizeable } from 'lib/components/Cards/CardMeta'
+import { useInterval } from 'lib/hooks/useInterval'
import { usePageVisibility } from 'lib/hooks/usePageVisibility'
import { SpinnerOverlay } from 'lib/lemon-ui/Spinner/Spinner'
import { themeLogic } from 'lib/logic/themeLogic'
@@ -24,6 +25,7 @@ import {
} from 'scenes/insights/EmptyStates'
import { insightDataLogic } from 'scenes/insights/insightDataLogic'
import { insightLogic } from 'scenes/insights/insightLogic'
+import { getCapacityRetryAt, getRetryCooldown } from 'scenes/insights/sharedUtils'
import { isSharedView } from '~/exporter/exporterViewLogic'
import { ErrorBoundary } from '~/layout/ErrorBoundary'
@@ -349,7 +351,18 @@ function InsightCardInternal(
)
const { insightLoading } = useValues(insightLogic(insightLogicProps))
- const { insightDataLoading } = useValues(insightDataLogic(insightLogicProps))
+ const { insightDataLoading, insightDataError } = useValues(insightDataLogic(insightLogicProps))
+
+ const [, setCooldownTick] = useState(0)
+ // The embedded query stores its own failure in insightDataLogic and does not set the apiError prop.
+ const capacityRetryAt = getCapacityRetryAt(apiErrored ? apiError : null, insightDataError)
+ const { secondsLeft: retrySecondsLeft, disabledReason: refreshDisabledReason } = getRetryCooldown(capacityRetryAt)
+ useInterval(() => setCooldownTick((tick) => tick + 1), retrySecondsLeft > 0 ? 1000 : null)
+ const refreshAfterCooldown = useCallback((): void => {
+ if (!capacityRetryAt || Date.now() >= capacityRetryAt) {
+ refresh?.()
+ }
+ }, [refresh, capacityRetryAt])
if (insightLoading || insightDataLoading) {
loading = true
@@ -393,10 +406,6 @@ function InsightCardInternal(
)
}
- if (!hasResults && loadingQueued) {
- return <InsightLoadingState insightProps={insightLogicProps} />
- }
-
if (apiErrored) {
const validationError = extractValidationError(apiError)
if (validationError) {
@@ -416,17 +425,25 @@ function InsightCardInternal(
titleStatus={apiError.status}
queryId={apiError.data?.queryId ?? queryId}
retryAfter={apiError.formattedRetryAfter}
- retryLoading={loading}
+ retryAfterTimestamp={capacityRetryAt}
+ retryLoading={loading || !!loadingQueued}
query={insight.query}
excludeActions={sharedView}
placement={placement}
- onRetry={sharedView ? undefined : refresh}
+ onRetry={sharedView || !refresh ? undefined : refreshAfterCooldown}
/>
)
}
return <InsightErrorState />
}
+ // Below the failure branch on purpose: a tile whose query is known to have failed must show
+ // that, even while the next attempt is already queued. The other way round, the spinner wins
+ // for as long as the retries run and the user cannot tell a dead tile from a slow one.
+ if (!hasResults && loadingQueued) {
+ return <InsightLoadingState insightProps={insightLogicProps} />
+ }
+
if (timedOut) {
return <InsightTimeoutState />
}
@@ -494,7 +511,8 @@ function InsightCardInternal(
toggleShowDescription={toggleShowDescription}
removeFromDashboard={removeFromDashboard}
deleteWithUndo={deleteWithUndo}
- refresh={refresh}
+ refresh={refresh ? refreshAfterCooldown : undefined}
+ refreshDisabledReason={refreshDisabledReason}
loadingQueued={loadingQueued}
loading={loading}
rename={rename}
diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx
index 1723aa454adb..5f19a60d6bc9 100644
--- a/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx
@@ -127,6 +127,7 @@ interface InsightMetaProps extends Pick<
onDragHandleMouseDown?: React.MouseEventHandler<HTMLDivElement>
tile?: DashboardTile
insight: InsightModel
+ refreshDisabledReason?: string
areDetailsShown?: boolean
setAreDetailsShown?: React.Dispatch<React.SetStateAction<boolean>>
persistDisplayOptions?: (node: Node) => void
@@ -148,6 +149,7 @@ export function InsightMeta({
removeFromDashboard,
deleteWithUndo,
refresh,
+ refreshDisabledReason: capacityDisabledReason,
refreshAfterDisplayOptionsChange,
loading,
loadingQueued,
@@ -384,9 +386,11 @@ export function InsightMeta({
nextAllowedClientRefresh && dayjs(nextAllowedClientRefresh).isAfter(dayjs())
? dayjs(nextAllowedClientRefresh).fromNow()
: null
- const refreshDisabledReason = nextRefreshFromNow
- ? `These results are already up to date. The next refresh is available ${nextRefreshFromNow}.`
- : undefined
+ const refreshDisabledReason =
+ capacityDisabledReason ??
+ (nextRefreshFromNow
+ ? `These results are already up to date. The next refresh is available ${nextRefreshFromNow}.`
+ : undefined)
// The always-visible "⋯" menu keeps refresh reachable on touch/keyboard. Unlike the hover
// icon (which hides while this tile refreshes) the menu item stays but disables.
const refreshMenuDisabledReason = tileRefreshing ? 'Refreshing…' : refreshDisabledReason
diff --git a/frontend/src/lib/utils/async.test.ts b/frontend/src/lib/utils/async.test.ts
index fe3f3b39c8c0..a5343dcdc659 100644
--- a/frontend/src/lib/utils/async.test.ts
+++ b/frontend/src/lib/utils/async.test.ts
@@ -155,6 +155,39 @@ describe('async utils', () => {
}
})
+ it('waits the delay getDelayMs gives, and the backoff when it gives none', async () => {
+ jest.useFakeTimers()
+ try {
+ const fn = jest
+ .fn()
+ .mockRejectedValueOnce(new Error('wait 5000'))
+ .mockRejectedValueOnce(new Error('no wait given'))
+ .mockResolvedValue('success')
+
+ const promise = retryWithBackoff(fn, {
+ maxAttempts: 3,
+ initialDelayMs: 1000,
+ backoffMultiplier: 2,
+ getDelayMs: (error) => ((error as Error).message === 'wait 5000' ? 5000 : undefined),
+ })
+
+ await jest.advanceTimersByTimeAsync(4999)
+ expect(fn).toHaveBeenCalledTimes(1)
+ await jest.advanceTimersByTimeAsync(1)
+ expect(fn).toHaveBeenCalledTimes(2)
+
+ // initialDelayMs * 2^1 after the second failure
+ await jest.advanceTimersByTimeAsync(1999)
+ expect(fn).toHaveBeenCalledTimes(2)
+ await jest.advanceTimersByTimeAsync(1)
+ expect(fn).toHaveBeenCalledTimes(3)
+
+ await expect(promise).resolves.toBe('success')
+ } finally {
+ jest.useRealTimers()
+ }
+ })
+
it('uses default options when none provided', async () => {
const errors = [new Error('fail'), new Error('fail'), new Error('fail')]
let callCount = 0
diff --git a/frontend/src/lib/utils/async.ts b/frontend/src/lib/utils/async.ts
index 643ff933081a..4cd49e36c532 100644
--- a/frontend/src/lib/utils/async.ts
+++ b/frontend/src/lib/utils/async.ts
@@ -46,8 +46,18 @@ export interface RetryOptions {
* }
*/
shouldRetry?: (error: unknown) => boolean
+ /**
+ * Milliseconds to wait before the next attempt, read from the error that ended this one.
+ * Return undefined to wait the backoff that `initialDelayMs` and `backoffMultiplier` give.
+ * Use it when the server says how long to wait, for example in a `Retry-After` header.
+ */
+ getDelayMs?: (error: unknown) => number | undefined
+ /** Retry-start budget from the first retryable failure. Does not cancel an in-flight attempt. */
+ maxRetryTimeMs?: number
}
+const RETRY_TIMER_TOLERANCE_MS = 100
+
/**
* Retries a function with exponential backoff on failure.
*
@@ -65,7 +75,15 @@ export interface RetryOptions {
* // Delays: 1000ms after 1st failure, 1500ms after 2nd failure
*/
export async function retryWithBackoff<T>(fn: () => Promise<T>, options: RetryOptions = {}): Promise<T> {
- const { maxAttempts = 3, initialDelayMs = 1000, backoffMultiplier = 1.5, signal, shouldRetry } = options
+ const {
+ maxAttempts = 3,
+ initialDelayMs = 1000,
+ backoffMultiplier = 1.5,
+ signal,
+ shouldRetry,
+ getDelayMs,
+ maxRetryTimeMs,
+ } = options
if (signal?.aborted) {
throw new DOMException('Aborted', 'AbortError')
@@ -74,6 +92,7 @@ export async function retryWithBackoff<T>(fn: () => Promise<T>, options: RetryOp
const attempts = Math.max(maxAttempts, 1)
let lastError: unknown
+ let retryDeadline: number | undefined
for (let attempt = 0; attempt < attempts; attempt++) {
try {
return await fn()
@@ -87,8 +106,17 @@ export async function retryWithBackoff<T>(fn: () => Promise<T>, options: RetryOp
if (isLastAttempt || !canRetry) {
throw e
}
- const delayMs = initialDelayMs * Math.pow(backoffMultiplier, attempt)
+ const delayMs = getDelayMs?.(e) ?? initialDelayMs * Math.pow(backoffMultiplier, attempt)
+ const now = performance.now()
+ retryDeadline ??= now + (maxRetryTimeMs ?? Infinity)
+ if (now + delayMs > retryDeadline) {
+ throw e
+ }
await delay(delayMs, signal)
+ // Allow timer jitter at the deadline, but reject retries delayed by a suspended tab.
+ if (performance.now() > retryDeadline + RETRY_TIMER_TOLERANCE_MS) {
+ throw e
+ }
}
}
throw lastError
diff --git a/frontend/src/queries/nodes/DataNode/dataNodeLogic.test.ts b/frontend/src/queries/nodes/DataNode/dataNodeLogic.test.ts
index a5dcfe223ab0..e21edc8873ac 100644
--- a/frontend/src/queries/nodes/DataNode/dataNodeLogic.test.ts
+++ b/frontend/src/queries/nodes/DataNode/dataNodeLogic.test.ts
@@ -1,5 +1,7 @@
import { expectLogic, partial } from 'kea-test-utils'
+import api, { ApiError } from 'lib/api'
+
import { useMocks } from '~/mocks/jest'
import { dataNodeCollectionLogic } from '~/queries/nodes/DataNode/dataNodeCollectionLogic'
import {
@@ -67,6 +69,33 @@ describe('dataNodeLogic', () => {
})
afterEach(() => logic?.unmount())
+ it('does not resubmit a capacity-limited query after unmount', async () => {
+ jest.useFakeTimers()
+ const submit = jest
+ .spyOn(api, 'query')
+ .mockRejectedValueOnce(new ApiError('', 503, new Headers({ 'Retry-After': '5' })))
+ .mockResolvedValue({ results: [] })
+ mockedQuery.mockImplementationOnce(jest.requireActual('~/queries/query').performQuery)
+ try {
+ logic = dataNodeLogic({
+ key: testUniqueKey,
+ query: setLatestVersionsOnQuery({ kind: NodeKind.HogQLQuery, query: 'SELECT 1' }),
+ })
+ logic.mount()
+ await jest.advanceTimersByTimeAsync(0)
+ expect(submit).toHaveBeenCalledTimes(1)
+ expect(logic.values.dataLoading).toBe(true)
+
+ logic.unmount()
+ await jest.advanceTimersByTimeAsync(20000)
+
+ expect(submit).toHaveBeenCalledTimes(1)
+ } finally {
+ submit.mockRestore()
+ jest.useRealTimers()
+ }
+ })
+
it('calls query to fetch data', async () => {
const results = {}
mockedQuery.mockResolvedValueOnce({ results })
diff --git a/frontend/src/queries/nodes/DataNode/dataNodeLogic.ts b/frontend/src/queries/nodes/DataNode/dataNodeLogic.ts
index 9777f848ac26..02d48950bc75 100644
--- a/frontend/src/queries/nodes/DataNode/dataNodeLogic.ts
+++ b/frontend/src/queries/nodes/DataNode/dataNodeLogic.ts
@@ -1091,9 +1091,9 @@ export const dataNodeLogic = kea<dataNodeLogicType>([
actions.abortAnyRunningQuery()
actions.setPollResponse(null)
const abortController = new AbortController()
- cache.abortController = abortController
+ cache.disposables.add(() => () => abortController.abort(), 'query', { pauseOnPageHidden: false })
const methodOptions: ApiMethodOptions = {
- signal: cache.abortController.signal,
+ signal: abortController.signal,
}
try {
// For shared contexts, create a minimal team object if needed
@@ -2097,10 +2097,7 @@ export const dataNodeLogic = kea<dataNodeLogicType>([
})),
listeners(({ actions, values, cache, props }) => ({
abortAnyRunningQuery: () => {
- if (cache.abortController) {
- cache.abortController.abort()
- cache.abortController = null
- }
+ cache.disposables.dispose('query')
},
abortQuery: async ({ queryId }) => {
try {
@@ -2239,10 +2236,6 @@ export const dataNodeLogic = kea<dataNodeLogicType>([
if (values.autoLoadRunning) {
actions.stopAutoLoad()
}
- if (values.dataLoading) {
- actions.abortAnyRunningQuery()
- }
-
actions.unmountDataNode(props.key)
// Disposables plugin handles timer cleanup automatically
}),
diff --git a/frontend/src/queries/nodes/DataTable/DataTable.tsx b/frontend/src/queries/nodes/DataTable/DataTable.tsx
index bf2b4b6fe109..62ba39651493 100644
--- a/frontend/src/queries/nodes/DataTable/DataTable.tsx
+++ b/frontend/src/queries/nodes/DataTable/DataTable.tsx
@@ -1100,6 +1100,7 @@ export function DataTable({
query={query}
queryId={responseErrorObject?.queryId ?? queryId}
titleStatus={responseErrorObject?.status}
+ retryAfterTimestamp={responseErrorObject?.retryAfterTimestamp}
// A cancel is the user's own action: no apology or bug-report guidance
excludeDetail={queryCancelled}
onRetry={() => loadData('force_blocking')}
@@ -1114,6 +1115,8 @@ export function DataTable({
) : (
<InsightErrorState
query={query}
+ titleStatus={responseErrorObject?.status}
+ retryAfterTimestamp={responseErrorObject?.retryAfterTimestamp}
onRetry={() => loadData('force_blocking')}
/>
)
diff --git a/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsx b/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsx
index f7b775d5f20d..4f4d665f1382 100644
--- a/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsx
+++ b/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsx
@@ -220,7 +220,7 @@ export function InsightVizDisplay({
theme,
} = useValues(insightVizDataLogic(insightProps))
const { loadData, updateQuerySource } = useActions(insightVizDataLogic(insightProps))
- const { exportContext, queryId } = useValues(insightDataLogic(insightProps))
+ const { exportContext, queryId, insightDataError } = useValues(insightDataLogic(insightProps))
const { funnelVizType, hasFunnelResults, isFunnelWithEnoughSteps, isFunnelWithIncompleteDataWarehouseStep } =
useValues(funnelDataLogic(insightProps))
@@ -325,6 +325,8 @@ export function InsightVizDisplay({
<InsightErrorState
query={query}
queryId={erroredQueryId}
+ titleStatus={insightDataError?.status}
+ retryAfterTimestamp={insightDataError?.retryAfterTimestamp}
onRetry={() => {
loadData(query && shouldQueryBeAsync(query) ? 'force_async' : 'force_blocking')
}}
diff --git a/frontend/src/queries/query.test.ts b/frontend/src/queries/query.test.ts
index 3a0ffb0b5b4c..9c86eb7d6ef4 100644
--- a/frontend/src/queries/query.test.ts
+++ b/frontend/src/queries/query.test.ts
@@ -4,7 +4,7 @@ import api, { ApiError } from 'lib/api'
import { useMocks } from '~/mocks/jest'
import { performQuery, pollForResults, queryExportContext, waitForPageVisible } from '~/queries/query'
-import { EventsQuery, HogQLQuery, NodeKind, WebStatsBreakdown } from '~/queries/schema/schema-general'
+import { EventsQuery, HogQLQuery, NodeKind, RefreshType, WebStatsBreakdown } from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
import { PropertyFilterType, PropertyOperator } from '~/types'
@@ -91,6 +91,7 @@ describe('query', () => {
it('emits an event when a query is run', async () => {
const captureSpy = jest.spyOn(posthog, 'capture')
+ const querySpy = jest.spyOn(api, 'query')
const q: EventsQuery = setLatestVersionsOnQuery({
kind: NodeKind.EventsQuery,
select: ['timestamp'],
@@ -100,7 +101,15 @@ describe('query', () => {
await performQuery(q)
const queryCompletedCalls = captureSpy.mock.calls.filter((call) => call[0] === 'query completed')
expect(queryCompletedCalls).toHaveLength(1)
- expect(queryCompletedCalls[0][1]).toMatchObject({ query: q, duration: expect.any(Number) })
+ expect(queryCompletedCalls[0][1]).toMatchObject({
+ query: q,
+ duration: expect.any(Number),
+ client_query_id: querySpy.mock.calls.at(-1)?.[1]?.clientQueryId,
+ submit_attempts: 1,
+ retry_wait_ms: expect.any(Number),
+ retry_status: null,
+ retry_recovered: false,
+ })
})
it('emits a specific event on a HogQLQuery', async () => {
@@ -295,6 +304,7 @@ describe('query', () => {
})
it('runs the query again when its status has expired', async () => {
+ const captureSpy = jest.spyOn(posthog, 'capture').mockClear()
const querySpy = jest
.spyOn(api, 'query')
.mockResolvedValueOnce(submitted('gone'))
@@ -308,6 +318,12 @@ describe('query', () => {
expect(querySpy).toHaveBeenCalledTimes(2)
// Same ID, so anything holding it still points at the run the user is waiting for.
expect(querySpy.mock.calls[1][1]?.clientQueryId).toBe('gone')
+ expect(captureSpy.mock.calls.find(([event]) => event === 'query completed')?.[1]).toMatchObject({
+ client_query_id: 'gone',
+ submit_attempts: 2,
+ retry_status: 404,
+ retry_recovered: true,
+ })
})
it('reads the cache on the retry rather than forcing the same work twice', async () => {
@@ -381,6 +397,274 @@ describe('query', () => {
})
})
+ describe('transient query submission failures', () => {
+ const query = { kind: NodeKind.EventsQuery, select: ['*'] } as EventsQuery
+ const refused = (): ApiError => new ApiError('', 503, undefined, {})
+ const badGateway = (): ApiError => new ApiError('', 502, undefined, {})
+ const shortCapacityWait = (): ApiError => new ApiError('', 503, new Headers({ 'Retry-After': '5' }), {})
+
+ afterEach(() => {
+ jest.useRealTimers()
+ jest.restoreAllMocks()
+ })
+
+ it.each([
+ ['a 502 bad gateway', badGateway, 600, ['ok'], true],
+ ['a capacity 503 asked for a short wait', shortCapacityWait, 5000, ['ok'], true],
+ [
+ 'a capacity 503 at the total retry budget',
+ () => new ApiError('', 503, new Headers({ 'Retry-After': '20' })),
+ 20000,
+ ['ok'],
+ true,
+ ],
+ ['a capacity retry returns an empty result', shortCapacityWait, 5000, [], true],
+ ['a capacity retry returns no result', shortCapacityWait, 5000, null, false],
+ ])(
+ 'submits the same run again once the wait ends after %s, and returns what the retry gets',
+ async (_name, makeError, waitMs, results, recovered) => {
+ jest.useFakeTimers()
+ const captureSpy = jest.spyOn(posthog, 'capture').mockClear()
+ const error = makeError()
+ const querySpy = jest
+ .spyOn(api, 'query')
+ .mockRejectedValueOnce(error)
+ .mockResolvedValueOnce({ results } as any)
+
+ const promise = performQuery(query, undefined, 'blocking')
+ await jest.advanceTimersByTimeAsync(waitMs - 1)
+ expect(querySpy).toHaveBeenCalledTimes(1)
+ await jest.advanceTimersByTimeAsync(1)
+
+ await expect(promise).resolves.toMatchObject({ results })
+ expect(querySpy).toHaveBeenCalledTimes(2)
+ const firstId = querySpy.mock.calls[0][1]?.clientQueryId
+ expect(firstId).toBeTruthy()
+ expect(querySpy.mock.calls[1][1]?.clientQueryId).toBe(firstId)
+ const completed = captureSpy.mock.calls.filter(([event]) => event === 'query completed')
+ expect(completed).toHaveLength(1)
+ expect(completed[0][1]).toMatchObject({
+ client_query_id: firstId,
+ submit_attempts: 2,
+ retry_wait_ms: waitMs,
+ retry_status: error.status,
+ retry_recovered: recovered,
+ })
+ expect(captureSpy.mock.calls.filter(([event]) => event === 'query failed')).toHaveLength(0)
+ }
+ )
+
+ it('does not resubmit when the query is aborted during the capacity wait', async () => {
+ jest.useFakeTimers()
+ const captureSpy = jest.spyOn(posthog, 'capture').mockClear()
+ const controller = new AbortController()
+ const querySpy = jest
+ .spyOn(api, 'query')
+ .mockRejectedValueOnce(shortCapacityWait())
+ .mockResolvedValueOnce({ results: ['ok'] } as any)
+
+ const outcome = Promise.allSettled([performQuery(query, { signal: controller.signal }, 'blocking')])
+ await jest.advanceTimersByTimeAsync(1000)
+ expect(querySpy).toHaveBeenCalledTimes(1)
+
+ controller.abort()
+ await jest.advanceTimersByTimeAsync(5000)
+
+ await expect(outcome).resolves.toMatchObject([{ status: 'rejected', reason: { name: 'AbortError' } }])
+ expect(querySpy).toHaveBeenCalledTimes(1)
+ expect(
+ captureSpy.mock.calls.filter(([event]) => event === 'query completed' || event === 'query failed')
+ ).toHaveLength(0)
+ })
+
+ it.each([
+ { name: 'empty result', error: false, results: { results: [] }, recovered: true },
+ { name: 'error stub', error: true, results: undefined, recovered: false },
+ { name: 'errored result', error: true, results: { results: [] }, recovered: false },
+ ])('records async recovery only after a usable result ($name)', async ({ error, results, recovered }) => {
+ jest.useFakeTimers()
+ const captureSpy = jest.spyOn(posthog, 'capture').mockClear()
+ jest.spyOn(api, 'query')
+ .mockRejectedValueOnce(shortCapacityWait())
+ .mockResolvedValueOnce({ query_status: { id: 'retry-query', complete: false } } as any)
+ jest.spyOn(api.queryStatus, 'get').mockResolvedValueOnce({
+ query_status: { id: 'retry-query', complete: true, error, results },
+ } as any)
+
+ const promise = performQuery(query, undefined, 'async', 'retry-query')
+ await jest.advanceTimersByTimeAsync(5000)
+ expect(captureSpy.mock.calls.filter(([event]) => event === 'query completed')).toHaveLength(0)
+ await jest.advanceTimersByTimeAsync(300)
+ await expect(promise).resolves.toEqual(results)
+
+ const completed = captureSpy.mock.calls.filter(([event]) => event === 'query completed')
+ expect(completed).toHaveLength(1)
+ expect(completed[0][1]).toMatchObject({
+ client_query_id: 'retry-query',
+ submit_attempts: 2,
+ retry_wait_ms: 5000,
+ retry_status: 503,
+ retry_recovered: recovered,
+ })
+ })
+
+ it.each([
+ ['the gateway refuses every attempt', badGateway, 1800, 502],
+ ['every attempt gets a short capacity wait', shortCapacityWait, 10000, 503],
+ [
+ 'both capacity waits fit the total budget exactly',
+ () => new ApiError('', 503, new Headers({ 'Retry-After': '10' })),
+ 20000,
+ 503,
+ ],
+ ])('reports the failure once %s', async (_name, makeError, elapsedMs, status) => {
+ jest.useFakeTimers()
+ const captureSpy = jest.spyOn(posthog, 'capture').mockClear()
+ const querySpy = jest.spyOn(api, 'query').mockRejectedValue(makeError())
+
+ const outcome = Promise.allSettled([performQuery(query, undefined, 'blocking')])
+ await jest.advanceTimersByTimeAsync(elapsedMs - 1)
+ expect(querySpy).toHaveBeenCalledTimes(2)
+ await jest.advanceTimersByTimeAsync(1)
+
+ await expect(outcome).resolves.toMatchObject([{ status: 'rejected', reason: { status } }])
+ expect(querySpy).toHaveBeenCalledTimes(3)
+ const failed = captureSpy.mock.calls.filter(([event]) => event === 'query failed')
+ expect(failed).toHaveLength(1)
+ expect(failed[0][1]).toMatchObject({
+ client_query_id: querySpy.mock.calls[0][1]?.clientQueryId,
+ submit_attempts: 3,
+ retry_wait_ms: elapsedMs,
+ retry_status: status,
+ error_status: status,
+ })
+ expect(captureSpy.mock.calls.filter(([event]) => event === 'query completed')).toHaveLength(0)
+ })
+
+ it.each([
+ ['the two hints exceed the budget', 15, 10, 0],
+ ['the failed retry uses the remaining budget', 5, 10, 6000],
+ ])('surfaces the full next cooldown when %s', async (_name, firstWait, nextWait, requestTimeMs) => {
+ jest.useFakeTimers()
+ const captureSpy = jest.spyOn(posthog, 'capture').mockClear()
+ let lastError: ApiError | undefined
+ const querySpy = jest
+ .spyOn(api, 'query')
+ .mockRejectedValueOnce(new ApiError('', 503, new Headers({ 'Retry-After': String(firstWait) })))
+ .mockImplementationOnce(async () => {
+ await new Promise((resolve) => setTimeout(resolve, requestTimeMs))
+ lastError = new ApiError('', 503, new Headers({ 'Retry-After': String(nextWait) }))
+ throw lastError
+ })
+ .mockResolvedValue({ results: ['ok'] } as any)
+
+ let receivedError: unknown
+ const outcome = performQuery(query, undefined, 'blocking').catch((error) => {
+ receivedError = error
+ })
+ await jest.advanceTimersByTimeAsync(firstWait * 1000 + requestTimeMs + 1)
+
+ expect(receivedError).toBeInstanceOf(ApiError)
+ expect(receivedError).toBe(lastError)
+ expect(lastError?.retryAfterSeconds).toBe(nextWait)
+ await jest.advanceTimersByTimeAsync(60_000)
+ await outcome
+ expect(querySpy).toHaveBeenCalledTimes(2)
+ expect(captureSpy.mock.calls.find(([event]) => event === 'query failed')?.[1]).toMatchObject({
+ submit_attempts: 2,
+ retry_wait_ms: firstWait * 1000,
+ retry_status: 503,
+ })
+ })
+
+ it.each([
+ { waitSeconds: 20, resumedAt: 20_050, retries: true },
+ { waitSeconds: 20, resumedAt: 21_000, retries: false },
+ { waitSeconds: 5, resumedAt: 21_000, retries: false },
+ ])(
+ 'bounds timer lateness after a $waitSeconds second hint (resumed at $resumedAt ms)',
+ async ({ waitSeconds, resumedAt, retries }) => {
+ jest.useFakeTimers()
+ const captureSpy = jest.spyOn(posthog, 'capture').mockClear()
+ const clock = jest.spyOn(performance, 'now').mockReturnValue(0)
+ const error = new ApiError('', 503, new Headers({ 'Retry-After': String(waitSeconds) }))
+ const querySpy = jest
+ .spyOn(api, 'query')
+ .mockRejectedValueOnce(error)
+ .mockResolvedValue({ results: ['ok'] } as any)
+
+ const outcome = Promise.allSettled([performQuery(query, undefined, 'blocking')])
+ await jest.advanceTimersByTimeAsync(0)
+ await jest.advanceTimersByTimeAsync(waitSeconds * 1000 - 1)
+ expect(querySpy).toHaveBeenCalledTimes(1)
+ clock.mockReturnValue(resumedAt)
+ await jest.advanceTimersByTimeAsync(1)
+
+ await expect(outcome).resolves.toEqual([
+ retries
+ ? { status: 'fulfilled', value: { results: ['ok'] } }
+ : { status: 'rejected', reason: error },
+ ])
+ expect(querySpy).toHaveBeenCalledTimes(retries ? 2 : 1)
+ const eventName = retries ? 'query completed' : 'query failed'
+ expect(captureSpy.mock.calls.find(([event]) => event === eventName)?.[1]).toMatchObject({
+ submit_attempts: retries ? 2 : 1,
+ retry_wait_ms: resumedAt,
+ retry_status: retries ? 503 : null,
+ })
+ }
+ )
+
+ it.each(
+ (['force_blocking', 'force_async'] as RefreshType[]).flatMap((refresh) =>
+ [502, 503].map((status) => ({ refresh, status }))
+ )
+ )(
+ 'retries $refresh only with a capacity hint, not an ambiguous gateway failure (status=$status)',
+ async ({ refresh, status }) => {
+ jest.useFakeTimers()
+ const error = status === 502 ? badGateway() : shortCapacityWait()
+ const querySpy = jest
+ .spyOn(api, 'query')
+ .mockRejectedValueOnce(error)
+ .mockResolvedValue({ results: ['ok'] } as any)
+
+ const outcome = Promise.allSettled([performQuery(query, undefined, refresh)])
+ await jest.advanceTimersByTimeAsync(4999)
+ expect(querySpy).toHaveBeenCalledTimes(1)
+ await jest.advanceTimersByTimeAsync(1)
+
+ await expect(outcome).resolves.toEqual([
+ status === 502
+ ? { status: 'rejected', reason: error }
+ : { status: 'fulfilled', value: { results: ['ok'] } },
+ ])
+ expect(querySpy).toHaveBeenCalledTimes(status === 502 ? 1 : 2)
+ }
+ )
+
+ it.each([
+ ['a 503 without Retry-After', refused()],
+ ['a 503 above the total retry budget', new ApiError('', 503, new Headers({ 'Retry-After': '21' }), {})],
+ ['a 503 with an invalid Retry-After', new ApiError('', 503, new Headers({ 'Retry-After': '1.5' }), {})],
+ [
+ 'a 503 with a date-form Retry-After',
+ new ApiError('', 503, new Headers({ 'Retry-After': 'Mon, 05 Oct 2026 12:00:05 GMT' }), {}),
+ ],
+ ['a capacity 503 with Retry-After', new ApiError('', 503, new Headers({ 'Retry-After': '45' }), {})],
+ ['a 504, where the backend can still be running the query', new ApiError('', 504, undefined, {})],
+ ])('does not submit again after %s', async (_name, error) => {
+ jest.useFakeTimers()
+ const querySpy = jest.spyOn(api, 'query').mockRejectedValue(error)
+
+ const outcome = Promise.allSettled([performQuery(query, undefined, 'blocking')])
+ await jest.advanceTimersByTimeAsync(60_000)
+
+ await expect(outcome).resolves.toEqual([{ status: 'rejected', reason: error }])
+ expect(querySpy).toHaveBeenCalledTimes(1)
+ })
+ })
+
describe('pollForResults error message parsing', () => {
it('prefers the structured error_code from the query status over one parsed from the message', async () => {
jest.spyOn(api.queryStatus, 'get').mockRejectedValueOnce({
diff --git a/frontend/src/queries/query.ts b/frontend/src/queries/query.ts
index da1d2b606fa7..5db5eadf6dd4 100644
--- a/frontend/src/queries/query.ts
+++ b/frontend/src/queries/query.ts
@@ -1,6 +1,8 @@
import api, { ApiMethodOptions, isAbortError } from 'lib/api'
+import { ApiError } from 'lib/api-error'
import posthog from 'lib/posthog-typed'
-import { delay } from 'lib/utils/async'
+import { delay, retryWithBackoff } from 'lib/utils/async'
+import { uuid } from 'lib/utils/dom'
import { isSharedView } from '~/exporter/exporterViewLogic'
import {
@@ -68,6 +70,45 @@ export const QUERY_TIMEOUT_ERROR_MESSAGE = 'Query timed out'
/** Matches MANAGED_WAREHOUSE_QUERY_UNAVAILABLE_CODE in posthog/api/query.py. */
const MANAGED_WAREHOUSE_UNAVAILABLE_CODE = 'managed_warehouse_connection_unavailable'
+const TRANSIENT_SUBMIT_ATTEMPTS = 3
+const TRANSIENT_SUBMIT_DELAY_MS = 600
+const TRANSIENT_SUBMIT_RETRY_BUDGET_MS = 20_000
+
+type QuerySubmitTelemetry = {
+ client_query_id?: string
+ submit_attempts: number
+ retry_wait_ms: number
+ retry_status: number | null
+ retry_recovered: boolean
+}
+
+function capacityWaitMs(error: unknown): number | undefined {
+ if (!(error instanceof ApiError) || error.status !== 503) {
+ return undefined
+ }
+ const seconds = error.retryAfterSeconds
+ return seconds !== null ? seconds * 1000 : undefined
+}
+
+/**
+ * Treat eligible 502/503 responses as potentially transient and retry within a bounded budget.
+ * A 502 does not establish whether the original query started (RFC 9110, section 15.6.3).
+ * Do not resubmit forced refreshes after a 502, since they bypass completed result caches.
+ * Only retry a 503 with a numeric `Retry-After` that fits the total retry-start budget.
+ * Without a fitting numeric hint the error goes to the caller at once, because an early
+ * resubmit only adds load. A 504 means the gateway stopped waiting while the backend can still be
+ * running the query, so a resubmit can compute it a second time.
+ */
+function isRetryableSubmitFailure(error: unknown, refresh: RefreshType): boolean {
+ if (!(error instanceof ApiError)) {
+ return false
+ }
+ if (error.status === 502) {
+ return refresh !== 'force_blocking' && refresh !== 'force_async' && !error.headers?.has('Retry-After')
+ }
+ return capacityWaitMs(error) !== undefined
+}
+
/**
* Parse error message that may be in ErrorDetail string format.
* Backend sometimes serializes ValidationError.detail as a string like:
@@ -167,6 +208,7 @@ export async function pollForResults(
*/
async function executeQuery<N extends DataNode>(
queryNode: N,
+ submitTelemetry: QuerySubmitTelemetry,
methodOptions?: ApiMethodOptions,
refresh?: RefreshType,
queryId?: string,
@@ -190,14 +232,51 @@ async function executeQuery<N extends DataNode>(
): Promise<NonNullable<N['response']>> {
if (!pollOnly) {
const refreshParam: RefreshType = refresh || 'blocking'
-
- const response = await api.query(queryNode, {
- requestOptions: methodOptions,
- clientQueryId: queryId,
- refresh: refreshParam,
- filtersOverride,
- variablesOverride,
- limitContext,
+ // Share a client ID for tracing and cancellation; it does not guarantee a single execution.
+ const clientQueryId = queryId || uuid()
+ const submitStartedAt = performance.now()
+ let requestDurationMs = 0
+ let retryStatus: number | null = retriedAfterExpiry ? 404 : null
+
+ const response = await retryWithBackoff(
+ async () => {
+ submitTelemetry.client_query_id = clientQueryId
+ submitTelemetry.submit_attempts++
+ if (retryStatus !== null) {
+ submitTelemetry.retry_status = retryStatus
+ }
+ const requestStartedAt = performance.now()
+ try {
+ return await api.query(queryNode, {
+ requestOptions: methodOptions,
+ clientQueryId,
+ refresh: refreshParam,
+ filtersOverride,
+ variablesOverride,
+ limitContext,
+ })
+ } catch (error) {
+ retryStatus = error instanceof ApiError ? (error.status ?? null) : null
+ throw error
+ } finally {
+ requestDurationMs += performance.now() - requestStartedAt
+ }
+ },
+ {
+ maxAttempts: TRANSIENT_SUBMIT_ATTEMPTS,
+ initialDelayMs: TRANSIENT_SUBMIT_DELAY_MS,
+ backoffMultiplier: 2,
+ signal: methodOptions?.signal,
+ shouldRetry: (error) => isRetryableSubmitFailure(error, refreshParam),
+ getDelayMs: capacityWaitMs,
+ maxRetryTimeMs: TRANSIENT_SUBMIT_RETRY_BUDGET_MS,
+ }
+ ).finally(() => {
+ // Exclude request time so slow responses do not look like long retry waits.
+ submitTelemetry.retry_wait_ms += Math.max(
+ 0,
+ Math.round(performance.now() - submitStartedAt - requestDurationMs)
+ )
})
if (response.detail) {
@@ -206,12 +285,19 @@ async function executeQuery<N extends DataNode>(
if (!isAsyncResponse(response)) {
// Executed query synchronously or from cache
+ submitTelemetry.retry_recovered =
+ submitTelemetry.submit_attempts > 1 && (!('results' in response) || response.results != null)
return response
}
if (acceptStaleCache && 'is_cached' in response && response.is_cached) {
// Cached results are already present alongside a background recompute, so use them
// now rather than discarding them to poll a job that may take a while (or be stuck).
+ submitTelemetry.retry_recovered =
+ submitTelemetry.submit_attempts > 1 &&
+ 'results' in response &&
+ response.results != null &&
+ !response.query_status.error
return response
}
@@ -250,6 +336,7 @@ async function executeQuery<N extends DataNode>(
}
return await executeQuery(
queryNode,
+ submitTelemetry,
methodOptions,
refresh === 'force_async' ? 'async' : refresh,
queryId,
@@ -262,6 +349,8 @@ async function executeQuery<N extends DataNode>(
true
)
}
+ submitTelemetry.retry_recovered =
+ submitTelemetry.submit_attempts > 1 && statusResponse.results != null && !statusResponse.error
return statusResponse.results
}
@@ -280,6 +369,13 @@ export async function performQuery<N extends DataNode>(
): Promise<NonNullable<N['response']>> {
let response: NonNullable<N['response']>
const logParams: Record<string, any> = {}
+ const submitTelemetry: QuerySubmitTelemetry = {
+ client_query_id: queryId,
+ submit_attempts: 0,
+ retry_wait_ms: 0,
+ retry_status: null,
+ retry_recovered: false,
+ }
const startTime = performance.now()
try {
@@ -289,6 +385,7 @@ export async function performQuery<N extends DataNode>(
} else {
response = await executeQuery(
queryNode,
+ submitTelemetry,
methodOptions,
refresh,
queryId,
@@ -329,6 +426,7 @@ export async function performQuery<N extends DataNode>(
data_warehouse_source_ids: warehouseSources.map((s) => s.id),
data_warehouse_source_types: warehouseSources.map((s) => s.source_type).filter(Boolean),
...logParams,
+ ...submitTelemetry,
})
return response
} catch (e) {
@@ -345,6 +443,8 @@ export async function performQuery<N extends DataNode>(
error_code: error?.code ?? null,
uses_data_warehouse_source: queryUsesDataWarehouse(queryNode),
...logParams,
+ ...submitTelemetry,
+ retry_recovered: false,
})
}
throw e
diff --git a/frontend/src/scenes/insights/EmptyStates/EmptyStates.tsx b/frontend/src/scenes/insights/EmptyStates/EmptyStates.tsx
index 10ddde26d8f6..23aafc2b58f9 100644
--- a/frontend/src/scenes/insights/EmptyStates/EmptyStates.tsx
+++ b/frontend/src/scenes/insights/EmptyStates/EmptyStates.tsx
@@ -21,6 +21,7 @@ import { MCPUseCaseCard } from 'lib/components/MCPHint/MCPUseCaseCard'
import { supportLogic } from 'lib/components/Support/supportLogic'
import { dayjs } from 'lib/dayjs'
import { holidaysMatcher, isChristmas } from 'lib/holidays'
+import { useInterval } from 'lib/hooks/useInterval'
import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
import { usePageVisibility } from 'lib/hooks/usePageVisibility'
import { IconChristmasOrnament, IconErrorOutline, IconOpenInNew } from 'lib/lemon-ui/icons'
@@ -57,6 +58,7 @@ import { funnelDataLogic } from 'products/product_analytics/frontend/insights/fu
import { insightDataLogic } from '../insightDataLogic'
import { insightVizDataLogic } from '../insightVizDataLogic'
+import { getRetryCooldown } from '../sharedUtils'
import { SampleDataState, SampleDataVariant } from './SampleDataState'
import { sampleDataStateLogic } from './sampleDataStateLogic'
@@ -211,10 +213,12 @@ const RetryButton = ({
onRetry,
query,
loading = false,
+ disabledReason,
}: {
onRetry: () => void
query?: Record<string, any> | Node | null
loading?: boolean
+ disabledReason?: string
}): JSX.Element => {
const sideAction = query
? {
@@ -240,6 +244,7 @@ const RetryButton = ({
size="small"
type="primary"
loading={loading}
+ disabledReason={disabledReason}
onClick={() => onRetry()}
sideAction={sideAction}
>
@@ -822,6 +827,7 @@ export interface InsightErrorStateProps {
query?: Record<string, any> | Node | null
queryId?: string | null
retryAfter?: string | null
+ retryAfterTimestamp?: number | null
retryLoading?: boolean
placement?: DashboardPlacement | 'SavedInsightGrid'
excludeDetail?: boolean
@@ -837,6 +843,7 @@ export function InsightErrorState({
query,
queryId,
retryAfter,
+ retryAfterTimestamp,
retryLoading = false,
placement,
excludeDetail = false,
@@ -845,15 +852,28 @@ export function InsightErrorState({
fixWithAIComponent,
onRetry,
}: InsightErrorStateProps): JSX.Element {
+ const [, setTick] = useState(0)
const errorKind = getInsightErrorKind(titleStatus)
const canRetry = errorKind !== 'invalid_query' && errorKind !== 'permission'
+ // InsightCard passes the later of its own and its embedded query's deadlines, so a non-503 card error can carry one.
+ const capacityRetryAt = canRetry ? retryAfterTimestamp : null
+ const {
+ secondsLeft: retrySecondsLeft,
+ disabledReason: retryDisabledReason,
+ remediation: capacityRemediation,
+ } = getRetryCooldown(capacityRetryAt)
+ useInterval(() => setTick((tick) => tick + 1), retrySecondsLeft > 0 ? 1000 : null)
const safeTitle = typeof title === 'string' && isRawServerErrorTitle(title, titleStatus) ? null : title
const displayTitle = getInsightErrorTitle(errorKind, safeTitle, titleStatus)
const isExport = placement === DashboardPlacement.Export
const showBugReport = !isExport && (errorKind === 'transient' || errorKind === 'server' || errorKind === 'unknown')
// A 513 body is curated backend copy, unless a staff account got the raw ClickHouse trace back.
const backendDetail = typeof title === 'string' && !isRawServerErrorTitle(title) ? title : null
- const remediation = getInsightErrorRemediation(errorKind, retryAfter, backendDetail)
+ // A 429 card error can carry the 503 deadline of its embedded query. That deadline still guards the retry button,
+ // but the copy keeps the 429 wait because it can outlast the 503 deadline.
+ const remediation =
+ (errorKind === 'rate_limit' ? null : capacityRemediation) ??
+ getInsightErrorRemediation(errorKind, retryAfter, backendDetail)
const { preflight } = useValues(preflightLogic)
const { openSupportForm } = useActions(supportLogic)
@@ -906,7 +926,12 @@ export function InsightErrorState({
{!supportOnly && (
<div className="mt-4">
- {remediation && <p className="max-w-120">{renderDetailWithLinks(remediation)}</p>}
+ {remediation && (
+ <p className="max-w-120">
+ {/* A sole string child keeps the countdown updating after page translation replaces its text node. */}
+ {capacityRetryAt ? remediation : renderDetailWithLinks(remediation)}
+ </p>
+ )}
{!excludeDetail && showBugReport && <p>{bugReportLink}</p>}
</div>
)}
@@ -918,7 +943,16 @@ export function InsightErrorState({
{!excludeActions && errorKind !== 'permission' && (
<div className="flex gap-2 mt-4">
{onRetry && canRetry ? (
- <RetryButton onRetry={onRetry} query={query} loading={retryLoading} />
+ <RetryButton
+ onRetry={() => {
+ if (!capacityRetryAt || Date.now() >= capacityRetryAt) {
+ onRetry()
+ }
+ }}
+ query={query}
+ loading={retryLoading}
+ disabledReason={retryDisabledReason}
+ />
) : (
<QueryDebuggerButton query={query} />
)}
diff --git a/frontend/src/scenes/insights/EmptyStates/InsightErrorStates.test.tsx b/frontend/src/scenes/insights/EmptyStates/InsightErrorStates.test.tsx
index bacd3251ffab..9761c0061fee 100644
--- a/frontend/src/scenes/insights/EmptyStates/InsightErrorStates.test.tsx
+++ b/frontend/src/scenes/insights/EmptyStates/InsightErrorStates.test.tsx
@@ -1,6 +1,7 @@
-import { cleanup, render, screen } from '@testing-library/react'
+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
import posthog from 'posthog-js'
+import { ApiError } from 'lib/api-error'
import { preflightLogic } from 'lib/logic/preflightLogic'
import { useMocks } from '~/mocks/jest'
@@ -26,6 +27,7 @@ describe('insight error states', () => {
afterEach(() => {
cleanup()
+ jest.useRealTimers()
})
it('reports "insight error message shown" when a validation error renders', () => {
@@ -196,6 +198,102 @@ describe('insight error states', () => {
expect(screen.queryByText(/DB::Exception/)).toBeNull()
})
+ it('honors a numeric capacity cooldown across remounts', () => {
+ jest.useFakeTimers()
+ const error = new ApiError('', 503, new Headers({ 'Retry-After': '45' }))
+ const onRetry = jest.fn()
+ const view = (
+ <InsightErrorState
+ titleStatus={error.status}
+ retryAfterTimestamp={error.retryAfterTimestamp}
+ onRetry={onRetry}
+ />
+ )
+ const { unmount } = render(view)
+
+ expect(screen.getByText('PostHog is busy. You can retry in 45 seconds.')).toBeTruthy()
+ fireEvent.click(screen.getByTestId('insight-retry-button'))
+ expect(onRetry).not.toHaveBeenCalled()
+
+ act(() => jest.advanceTimersByTime(15_000))
+ unmount()
+ render(view)
+ expect(screen.getByText('PostHog is busy. You can retry in 30 seconds.')).toBeTruthy()
+
+ act(() => jest.advanceTimersByTime(29_000))
+ fireEvent.click(screen.getByTestId('insight-retry-button'))
+ expect(onRetry).not.toHaveBeenCalled()
+
+ act(() => jest.advanceTimersByTime(1000))
+ expect(screen.getByText('You can try this query again now.')).toBeTruthy()
+ expect(onRetry).not.toHaveBeenCalled()
+ fireEvent.click(screen.getByTestId('insight-retry-button'))
+ expect(onRetry).toHaveBeenCalledTimes(1)
+ })
+
+ it('keeps rate-limit guidance when a 429 carries an embedded capacity deadline', () => {
+ jest.useFakeTimers()
+ const onRetry = jest.fn()
+ render(
+ <InsightErrorState
+ titleStatus={429}
+ retryAfter="in 2 minutes"
+ retryAfterTimestamp={Date.now() + 10_000}
+ onRetry={onRetry}
+ />
+ )
+
+ expect(screen.getByText('Try again in 2 minutes.')).toBeTruthy()
+ fireEvent.click(screen.getByTestId('insight-retry-button'))
+ expect(onRetry).not.toHaveBeenCalled()
+
+ act(() => jest.advanceTimersByTime(10_000))
+ expect(screen.getByText('Try again in 2 minutes.')).toBeTruthy()
+ expect(screen.queryByText('You can try this query again now.')).toBeNull()
+ fireEvent.click(screen.getByTestId('insight-retry-button'))
+ expect(onRetry).toHaveBeenCalledTimes(1)
+ })
+
+ it('updates the capacity countdown after page translation replaces its text node', () => {
+ jest.useFakeTimers()
+ const onRetry = jest.fn()
+ render(<InsightErrorState titleStatus={503} retryAfterTimestamp={Date.now() + 2000} onRetry={onRetry} />)
+ const message = screen.getByText('PostHog is busy. You can retry in 2 seconds.')
+ const translateMessage = (): void => {
+ const translated = document.createElement('font')
+ translated.textContent = 'Translated countdown'
+ message.replaceChild(translated, message.firstChild!)
+ }
+
+ translateMessage()
+ act(() => jest.advanceTimersByTime(1000))
+ expect(message.textContent).toBe('PostHog is busy. You can retry in 1 second.')
+ fireEvent.click(screen.getByTestId('insight-retry-button'))
+ expect(onRetry).not.toHaveBeenCalled()
+
+ translateMessage()
+ act(() => jest.advanceTimersByTime(1000))
+ expect(message.textContent).toBe('You can try this query again now.')
+ fireEvent.click(screen.getByTestId('insight-retry-button'))
+ expect(onRetry).toHaveBeenCalledTimes(1)
+ })
+
+ it('uses the latest capacity deadline when a retry is rejected again', () => {
+ jest.useFakeTimers()
+ const onRetry = jest.fn()
+ const { rerender } = render(
+ <InsightErrorState titleStatus={503} retryAfterTimestamp={Date.now() + 30_000} onRetry={onRetry} />
+ )
+ act(() => jest.advanceTimersByTime(30_000))
+ fireEvent.click(screen.getByTestId('insight-retry-button'))
+ expect(onRetry).toHaveBeenCalledTimes(1)
+
+ rerender(<InsightErrorState titleStatus={503} retryAfterTimestamp={Date.now() + 60_000} onRetry={onRetry} />)
+ expect(screen.getByText('PostHog is busy. You can retry in 60 seconds.')).toBeTruthy()
+ fireEvent.click(screen.getByTestId('insight-retry-button'))
+ expect(onRetry).toHaveBeenCalledTimes(1)
+ })
+
it('uses user-facing copy for invalid query errors', () => {
render(<InsightErrorState title="This query is invalid" titleStatus={400} query={{ kind: 'InsightVizNode' }} />)
diff --git a/frontend/src/scenes/insights/insightSceneLogic.test.ts b/frontend/src/scenes/insights/insightSceneLogic.test.ts
index 9590b1dc27b1..74a2bab16c28 100644
--- a/frontend/src/scenes/insights/insightSceneLogic.test.ts
+++ b/frontend/src/scenes/insights/insightSceneLogic.test.ts
@@ -87,6 +87,32 @@ describe('insightSceneLogic', () => {
})
})
+ it.each([false, true])(
+ 'releases scene-owned insight logics on navigation (shared owner: %s)',
+ async (sharedOwner) => {
+ router.actions.push(urls.insightNew())
+ logic = insightSceneLogic()
+ const unmountScene = logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ const insight = logic.values.insightLogicRef!.logic
+ const data = logic.values.insightDataLogicRef!.logic
+ const releaseSharedInsight = sharedOwner ? insight.mount() : undefined
+ const releaseSharedData = sharedOwner ? data.mount() : undefined
+
+ unmountScene()
+
+ expect(logic.isMounted()).toBe(false)
+ expect(insight.isMounted()).toBe(sharedOwner)
+ expect(data.isMounted()).toBe(sharedOwner)
+
+ releaseSharedInsight?.()
+ releaseSharedData?.()
+ expect(insight.isMounted()).toBe(false)
+ expect(data.isMounted()).toBe(false)
+ }
+ )
+
it('updates the generated breadcrumb when cohort names arrive after the query', async () => {
router.actions.push(urls.insightNew())
logic = insightSceneLogic()
diff --git a/frontend/src/scenes/insights/insightSceneLogic.tsx b/frontend/src/scenes/insights/insightSceneLogic.tsx
index 742a3705d6d6..39422e5ea861 100644
--- a/frontend/src/scenes/insights/insightSceneLogic.tsx
+++ b/frontend/src/scenes/insights/insightSceneLogic.tsx
@@ -703,7 +703,7 @@ export const insightSceneLogic = kea<insightSceneLogicType>([
!isDashboardFilterOverrideEmpty(tileFiltersOverride),
],
}),
- sharedListeners(({ actions, values }) => ({
+ sharedListeners(({ actions, values, cache }) => ({
/**
* The editor must show the insight in the URL and the tile the user opened—not a different saved insight.
* After "Save as" from a dashboard, the tile still belongs to the original; if we kept the wrong editor
@@ -717,8 +717,6 @@ export const insightSceneLogic = kea<insightSceneLogicType>([
const propsMismatch = Boolean(insightId && mountedDashboardItemId && mountedDashboardItemId !== insightId)
if (logicInsightId !== insightId || propsMismatch) {
- const oldRef = values.insightLogicRef // free old logic after mounting new one
- const oldRef2 = values.insightDataLogicRef // free old logic after mounting new one
if (insightId) {
const insightProps: InsightLogicProps = {
dashboardItemId: insightId,
@@ -735,15 +733,20 @@ export const insightSceneLogic = kea<insightSceneLogicType>([
const logic2 = insightDataLogic.build(insightProps)
const unmount2 = logic2.mount()
actions.setInsightDataLogicRef(logic2, unmount2)
+
+ // Mount the new owners before releasing the old ones to preserve shared insight state.
+ cache.disposables.add(
+ () => () => {
+ unmount()
+ unmount2()
+ },
+ 'insightLogics',
+ { pauseOnPageHidden: false }
+ )
} else {
actions.setInsightLogicRef(null, null)
actions.setInsightDataLogicRef(null, null)
- }
- if (oldRef) {
- oldRef.unmount()
- }
- if (oldRef2) {
- oldRef2.unmount()
+ cache.disposables.dispose('insightLogics')
}
} else if (insightId) {
values.insightLogicRef?.logic.actions.loadInsight(
diff --git a/frontend/src/scenes/insights/sharedUtils.ts b/frontend/src/scenes/insights/sharedUtils.ts
index fae86a6d0780..3181d319520c 100644
--- a/frontend/src/scenes/insights/sharedUtils.ts
+++ b/frontend/src/scenes/insights/sharedUtils.ts
@@ -1,4 +1,6 @@
// This is separate from utils.ts because here we don't include `funnelLogic`, `retentionLogic`, etc
+import { ApiError } from 'lib/api-error'
+
import {
ChartDisplayType,
FilterType,
@@ -12,6 +14,29 @@ import {
TrendsFilterType,
} from '~/types'
+export function getCapacityRetryAt(tileError: unknown, queryError: unknown): number | null {
+ const tileRetryAt = tileError instanceof ApiError ? tileError.retryAfterTimestamp : null
+ const queryRetryAt = queryError instanceof ApiError ? queryError.retryAfterTimestamp : null
+ return Math.max(tileRetryAt ?? 0, queryRetryAt ?? 0) || null
+}
+
+export function getRetryCooldown(retryAt: number | null | undefined): {
+ secondsLeft: number
+ disabledReason: string | undefined
+ remediation: string | null
+} {
+ if (!retryAt) {
+ return { secondsLeft: 0, disabledReason: undefined, remediation: null }
+ }
+ const secondsLeft = Math.max(0, Math.ceil((retryAt - Date.now()) / 1000))
+ if (secondsLeft === 0) {
+ return { secondsLeft, disabledReason: undefined, remediation: 'You can try this query again now.' }
+ }
+ const unit = secondsLeft === 1 ? 'second' : 'seconds'
+ const message = `PostHog is busy. You can retry in ${secondsLeft} ${unit}.`
+ return { secondsLeft, disabledReason: message, remediation: message }
+}
+
/**
* Get a key function for InsightLogicProps.
* The key will equals either 'scene', 'new' or an ID.
diff --git a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/liveWebAnalyticsMetricsLogic.test.ts b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/liveWebAnalyticsMetricsLogic.test.ts
index e3bc1d477bff..6d6340c109b5 100644
--- a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/liveWebAnalyticsMetricsLogic.test.ts
+++ b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/liveWebAnalyticsMetricsLogic.test.ts
@@ -6,6 +6,7 @@ import posthog from 'posthog-js'
import { lemonToast } from '@posthog/lemon-ui'
import api from 'lib/api'
+import { ApiError } from 'lib/api-error'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { webAnalyticsLogic } from 'scenes/web-analytics/webAnalyticsLogic'
@@ -43,7 +44,10 @@ describe('liveWebAnalyticsMetricsLogic', () => {
],
})
jest.spyOn(api, 'query').mockResolvedValue({ results: [] } as any)
+ jest.spyOn(api, 'stream').mockResolvedValue(undefined)
;(posthog as any).setPersonProperties = jest.fn()
+ unmountFeatureFlagLogic = featureFlagLogic.mount()
+ featureFlagLogic.actions.setFeatureFlags([], {})
logic = liveWebAnalyticsMetricsLogic()
logic.mount()
})
@@ -51,16 +55,186 @@ describe('liveWebAnalyticsMetricsLogic', () => {
afterEach(() => {
logic.unmount()
unmountFeatureFlagLogic?.()
+ unmountFeatureFlagLogic = undefined
jest.restoreAllMocks()
+ jest.useRealTimers()
})
const enableBotAnalysis = (): void => {
- unmountFeatureFlagLogic = featureFlagLogic.mount()
featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.WEB_ANALYTICS_BOT_ANALYSIS], {
[FEATURE_FLAGS.WEB_ANALYTICS_BOT_ANALYSIS]: true,
})
}
+ it.each(
+ [
+ { statuses: [502], attempts: 3 },
+ { statuses: [503], attempts: 1 },
+ { statuses: [504], attempts: 1 },
+ { statuses: [502, 502, 504], attempts: 3 },
+ { statuses: [502, 504], attempts: 2 },
+ ].flatMap((testCase) =>
+ ['live_device_breakdown', 'live_bots'].map((failedQuery) => ({ ...testCase, failedQuery }))
+ )
+ )(
+ 'bounds $failedQuery submissions for $statuses failures to $attempts attempts',
+ async ({ statuses, attempts, failedQuery }) => {
+ enableBotAnalysis()
+ await expectLogic(logic).toFinishAllListeners()
+ jest.useFakeTimers()
+ jest.spyOn(console, 'error').mockImplementation(() => undefined)
+ jest.spyOn(lemonToast, 'error').mockReturnValue('toast-id')
+ let queryAttempts = 0
+ ;(api.query as jest.Mock).mockClear().mockImplementation(async (query: HogQLQuery | TrendsQuery) => {
+ if (query.tags?.name === failedQuery) {
+ throw new ApiError('', statuses[queryAttempts++ % statuses.length])
+ }
+ return { results: [] }
+ })
+ logic.actions.loadInitialData(true)
+
+ await jest.advanceTimersByTimeAsync(10_000)
+
+ const names = getLiveQueryNames()
+ expect(names).toContain('live_bots')
+ expect(names.filter((name) => name === failedQuery)).toHaveLength(attempts)
+ expect(logic.values.isLoading).toBe(false)
+ }
+ )
+
+ it.each(
+ ['live_device_breakdown', 'live_bots'].flatMap((failedQuery) =>
+ [true, false].map((hogql) => ({ failedQuery, hogql }))
+ )
+ )(
+ 'respects $failedQuery capacity hints during retries and scheduled refreshes (HogQL=$hogql)',
+ async ({ failedQuery, hogql }) => {
+ await expectLogic(logic).toFinishAllListeners()
+ jest.useFakeTimers()
+ featureFlagLogic.actions.setFeatureFlags(
+ [FEATURE_FLAGS.WEB_ANALYTICS_BOT_ANALYSIS, ...(hogql ? [FEATURE_FLAGS.LIVESTREAM_HOGQL] : [])],
+ {
+ [FEATURE_FLAGS.LIVESTREAM_HOGQL]: hogql,
+ [FEATURE_FLAGS.WEB_ANALYTICS_BOT_ANALYSIS]: true,
+ }
+ )
+ jest.spyOn(console, 'error').mockImplementation(() => undefined)
+ jest.spyOn(lemonToast, 'warning').mockReturnValue('toast-id')
+ ;(api.query as jest.Mock).mockClear().mockImplementation(async (query: HogQLQuery | TrendsQuery) => {
+ if (query.tags?.name === failedQuery) {
+ throw new ApiError('', 503, new Headers({ 'Retry-After': '45' }))
+ }
+ return { results: [] }
+ })
+ logic.actions.loadInitialData(true)
+
+ await jest.advanceTimersByTimeAsync(0)
+ expect(getLiveQueryNames().filter((name) => name === failedQuery)).toHaveLength(1)
+
+ await jest.advanceTimersByTimeAsync(44_999)
+ expect(getLiveQueryNames().filter((name) => name === failedQuery)).toHaveLength(1)
+
+ await jest.advanceTimersByTimeAsync(1)
+ expect(getLiveQueryNames().filter((name) => name === failedQuery)).toHaveLength(2)
+ }
+ )
+
+ it.each([
+ { status: 504, recovers: true },
+ { status: 400, recovers: false },
+ ])('reloads historical SSE data only after transient failures (status=$status)', async ({ status, recovers }) => {
+ await expectLogic(logic).toFinishAllListeners()
+ jest.useFakeTimers()
+ jest.spyOn(console, 'error').mockImplementation(() => undefined)
+ jest.spyOn(lemonToast, 'warning').mockReturnValue('toast-id')
+ let deviceAttempts = 0
+ ;(api.query as jest.Mock).mockClear().mockImplementation(async (query: HogQLQuery | TrendsQuery) => {
+ if (query.tags?.name === 'live_device_breakdown') {
+ if (++deviceAttempts === 1) {
+ throw new ApiError('', status)
+ }
+ return { results: [[new Date().toISOString(), { Desktop: ['visitor-1'] }]] }
+ }
+ return { results: [] }
+ })
+ logic.actions.loadInitialData(true)
+
+ await jest.advanceTimersByTimeAsync(29_999)
+ expect(deviceAttempts).toBe(1)
+ expect(logic.values.deviceBreakdown).toEqual([])
+ await jest.advanceTimersByTimeAsync(1)
+
+ expect(logic.values.deviceBreakdown).toEqual(recovers ? [{ device: 'Desktop', count: 1, percentage: 100 }] : [])
+ await jest.advanceTimersByTimeAsync(60_000)
+ expect(deviceAttempts).toBe(recovers ? 2 : 1)
+ })
+
+ it.each([true, false])('backs off repeated live failures and resets after recovery (HogQL=%s)', async (hogql) => {
+ await expectLogic(logic).toFinishAllListeners()
+ jest.useFakeTimers()
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.LIVESTREAM_HOGQL]: hogql })
+ jest.spyOn(console, 'error').mockImplementation(() => undefined)
+ jest.spyOn(lemonToast, 'warning').mockReturnValue('toast-id')
+ let failing = true
+ let deviceAttempts = 0
+ ;(api.query as jest.Mock).mockImplementation(async (query: HogQLQuery | TrendsQuery) => {
+ if (query.tags?.name === 'live_device_breakdown') {
+ deviceAttempts++
+ if (failing) {
+ throw new ApiError('', 504)
+ }
+ }
+ return { results: [] }
+ })
+ logic.actions.loadInitialData(true)
+ await jest.advanceTimersByTimeAsync(0)
+
+ for (const delay of [30_000, 60_000, 120_000, 240_000, 300_000, 300_000]) {
+ const attempts = deviceAttempts
+ await jest.advanceTimersByTimeAsync(delay - 1)
+ expect(deviceAttempts).toBe(attempts)
+ await jest.advanceTimersByTimeAsync(1)
+ expect(deviceAttempts).toBe(attempts + 1)
+ }
+
+ failing = false
+ await jest.advanceTimersByTimeAsync(300_000)
+ failing = true
+ logic.actions.loadInitialData(true)
+ await jest.advanceTimersByTimeAsync(0)
+ const attempts = deviceAttempts
+ await jest.advanceTimersByTimeAsync(29_999)
+ expect(deviceAttempts).toBe(attempts)
+ await jest.advanceTimersByTimeAsync(1)
+ expect(deviceAttempts).toBe(attempts + 1)
+ })
+
+ it.each(['reload', 'unmount'])('cancels pending SSE recovery on %s', async (action) => {
+ await expectLogic(logic).toFinishAllListeners()
+ jest.useFakeTimers()
+ jest.spyOn(console, 'error').mockImplementation(() => undefined)
+ jest.spyOn(lemonToast, 'warning').mockReturnValue('toast-id')
+ let deviceAttempts = 0
+ ;(api.query as jest.Mock).mockClear().mockImplementation(async (query: HogQLQuery | TrendsQuery) => {
+ if (query.tags?.name === 'live_device_breakdown' && ++deviceAttempts === 1) {
+ throw new ApiError('', 504)
+ }
+ return { results: [] }
+ })
+ logic.actions.loadInitialData(true)
+ await jest.advanceTimersByTimeAsync(15_000)
+ expect(deviceAttempts).toBe(1)
+
+ if (action === 'reload') {
+ logic.actions.loadInitialData(true)
+ } else {
+ logic.unmount()
+ }
+ await jest.advanceTimersByTimeAsync(60_000)
+
+ expect(deviceAttempts).toBe(action === 'reload' ? 2 : 1)
+ })
+
it('collapses streamed pageviews that clean to the same path into one row', () => {
logic.actions.addEvents(
[pageview('/classes/928q3hr9paw8hfe', 'user-1'), pageview('/classes/j2k4l6m8n0p', 'user-2')],
diff --git a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/liveWebAnalyticsMetricsLogic.tsx b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/liveWebAnalyticsMetricsLogic.tsx
index f60e7fe4c043..dd598ce24a76 100644
--- a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/liveWebAnalyticsMetricsLogic.tsx
+++ b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/liveWebAnalyticsMetricsLogic.tsx
@@ -5,13 +5,13 @@ import { subscriptions } from 'kea-subscriptions'
import { lemonToast } from '@posthog/lemon-ui'
+import { ApiError, isTransientServerError } from 'lib/api-error'
import { createStreamConnection } from 'lib/api-stream'
import { applyPathCleaning } from 'lib/components/PathCleanFilters/pathCleaningUtils'
import { FEATURE_FLAGS } from 'lib/constants'
import { dayjs } from 'lib/dayjs'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { liveEventsHostOrigin } from 'lib/utils/apiHost'
-import { retryWithBackoff } from 'lib/utils/async'
import { CATEGORY_LABELS } from 'lib/utils/botDetection'
import { ConcurrencyController } from 'lib/utils/concurrencyController'
import { isAbortedRequest } from 'lib/utils/requests'
@@ -71,12 +71,10 @@ const COUNTRY_BREAKDOWN_LIMIT = 6
const CITY_BREAKDOWN_LIMIT = 6
const LIVE_QUERY_SCENE = 'web-analytics-live'
const LIVE_QUERY_CONCURRENCY = 4
-const LIVE_QUERY_MAX_ATTEMPTS = 3
-const LIVE_QUERY_RETRY_DELAY_MS = 250
const RELOAD_DEBOUNCE_MS = 300
const HOGQL_RELOAD_INTERVAL_MS = 30000
+const MAX_RECOVERY_RELOAD_DELAY_MS = 300000
const PAUSE_GRACE_MS = 2000
-const TRANSIENT_QUERY_STATUSES = new Set([502, 503, 504])
type BotQueryStatus = 'idle' | 'loading' | 'loaded' | 'error'
@@ -89,22 +87,6 @@ const liveQueryTags = (name: string): QueryLogTags => ({
name,
})
-const isTransientQueryError = (error: unknown): boolean => {
- const status = (error as { status?: number } | null)?.status
- return status !== undefined && TRANSIENT_QUERY_STATUSES.has(status)
-}
-
-const performLiveQuery = <N extends HogQLQuery | TrendsQuery>(
- query: N,
- signal: AbortSignal
-): Promise<NonNullable<N['response']>> =>
- retryWithBackoff(() => performQuery(query, { signal }), {
- maxAttempts: LIVE_QUERY_MAX_ATTEMPTS,
- initialDelayMs: LIVE_QUERY_RETRY_DELAY_MS,
- signal,
- shouldRetry: isTransientQueryError,
- })
-
const collapseTopWithOther = <T extends { count: number; percentage: number }>(
items: T[],
limit: number,
@@ -725,10 +707,20 @@ export const liveWebAnalyticsMetricsLogic = kea<liveWebAnalyticsMetricsLogicType
actions.loadInitialData(true)
},
loadInitialData: async ({ isBackground }) => {
+ // A new load must not be aborted by a reload scheduled by the previous one.
+ cache.disposables.dispose('hogqlReload')
cache.loadAbortController?.abort()
const abortController = new AbortController()
cache.loadAbortController = abortController
const { signal } = abortController
+ let retryAfterTimestamp = 0
+ let hasTransientQueryError = false
+ const onQueryError = (error: unknown): void => {
+ hasTransientQueryError ||= isTransientServerError(error)
+ if (error instanceof ApiError) {
+ retryAfterTimestamp = Math.max(retryAfterTimestamp, error.retryAfterTimestamp ?? 0)
+ }
+ }
const isColdLoad = !cache.hasLoadedData || !isBackground
if (isColdLoad) {
@@ -760,6 +752,7 @@ export const liveWebAnalyticsMetricsLogic = kea<liveWebAnalyticsMetricsLogicType
filtersEnabled: true,
doPathCleaning: values.pathCleaningFilters.length > 0,
abortController,
+ onQueryError,
})
if (signal.aborted) {
@@ -809,6 +802,7 @@ export const liveWebAnalyticsMetricsLogic = kea<liveWebAnalyticsMetricsLogicType
filterTestAccounts: values.shouldFilterTestAccounts,
filtersEnabled: true,
abortController,
+ onQueryError,
})
if (signal.aborted) {
return
@@ -843,6 +837,12 @@ export const liveWebAnalyticsMetricsLogic = kea<liveWebAnalyticsMetricsLogicType
if (!signal.aborted) {
actions.setIsLoading(false)
actions.setIsRefreshing(false)
+ cache.recoveryReloadDelay = hasTransientQueryError
+ ? Math.min(
+ (cache.recoveryReloadDelay || HOGQL_RELOAD_INTERVAL_MS / 2) * 2,
+ MAX_RECOVERY_RELOAD_DELAY_MS
+ )
+ : 0
}
cache.hasInitialized = true
// A filter change that arrived mid-load was queued rather than dropped:
@@ -852,9 +852,17 @@ export const liveWebAnalyticsMetricsLogic = kea<liveWebAnalyticsMetricsLogicType
resetStreamStateAndReload(cache as FlushCache, actions)
}
// Counted from load completion, so a load slower than the interval is never aborted by the next one.
- if (!signal.aborted && values.featureFlags[FEATURE_FLAGS.LIVESTREAM_HOGQL]) {
+ if (
+ !signal.aborted &&
+ (values.featureFlags[FEATURE_FLAGS.LIVESTREAM_HOGQL] || hasTransientQueryError)
+ ) {
cache.disposables.add(() => {
- const timeoutId = setTimeout(() => actions.loadInitialData(true), HOGQL_RELOAD_INTERVAL_MS)
+ const delay = Math.max(
+ HOGQL_RELOAD_INTERVAL_MS,
+ cache.recoveryReloadDelay,
+ retryAfterTimestamp - Date.now()
+ )
+ const timeoutId = setTimeout(() => actions.loadInitialData(true), delay)
return () => clearTimeout(timeoutId)
}, 'hogqlReload')
}
@@ -871,8 +879,6 @@ export const liveWebAnalyticsMetricsLogic = kea<liveWebAnalyticsMetricsLogicType
cache.eventsConnection?.abort()
if (values.featureFlags[FEATURE_FLAGS.LIVESTREAM_HOGQL]) {
- // A new load is starting, so a reload scheduled by the previous one must not abort it.
- cache.disposables.dispose('hogqlReload')
return
}
@@ -1181,6 +1187,7 @@ const loadQueryData = async ({
filtersEnabled,
doPathCleaning,
abortController,
+ onQueryError,
}: {
dateFrom: Date
dateTo: Date
@@ -1191,6 +1198,7 @@ const loadQueryData = async ({
filtersEnabled: boolean
doPathCleaning: boolean
abortController: AbortController
+ onQueryError: (error: unknown) => void
}): Promise<LiveQueryData> => {
const { signal } = abortController
const { whereClause, queryParams, botEligibleEventsTuple } = buildLiveQueryContext({
@@ -1417,7 +1425,7 @@ const loadQueryData = async ({
const settled = await Promise.allSettled(
jobs.map((job) =>
liveQueryConcurrency.run({
- fn: () => performLiveQuery(job.query, signal),
+ fn: () => performQuery(job.query, { signal }),
abortController,
debugTag: job.key,
})
@@ -1447,6 +1455,7 @@ const loadQueryData = async ({
data[key] = result.value as HogQLQueryResponse
}
} else if (!isAbortedRequest(result.reason)) {
+ onQueryError(result.reason)
data.failedQueries.push(LIVE_QUERY_LABELS[key])
console.error(`Live query "${query.tags?.name ?? key}" failed:`, result.reason)
}
@@ -1463,7 +1472,11 @@ const loadBotQueryData = async ({
filterTestAccounts,
filtersEnabled,
abortController,
-}: LiveQueryContextParams & { abortController: AbortController }): Promise<HogQLQueryResponse | null> => {
+ onQueryError,
+}: LiveQueryContextParams & {
+ abortController: AbortController
+ onQueryError: (error: unknown) => void
+}): Promise<HogQLQueryResponse | null> => {
const { signal } = abortController
const { whereClause, queryParams, botEligibleEventsTuple } = buildLiveQueryContext({
dateFrom,
@@ -1508,12 +1521,13 @@ const loadBotQueryData = async ({
try {
return await liveQueryConcurrency.run({
- fn: () => performLiveQuery(botQuery, signal),
+ fn: () => performQuery(botQuery, { signal }),
abortController,
debugTag: 'bot',
})
} catch (error) {
if (!isAbortedRequest(error)) {
+ onQueryError(error)
console.error('Live query "live_bots" failed:', error)
}
return null
diff --git a/posthog/exceptions.py b/posthog/exceptions.py
index d258e54dda0d..2b895c49c181 100644
--- a/posthog/exceptions.py
+++ b/posthog/exceptions.py
@@ -93,7 +93,7 @@ class ClickHouseAtCapacity(APIException):
def __init__(self, detail: Optional[str] = None, code: Optional[str] = None) -> None:
super().__init__(detail=detail, code=code)
# Spread retries across requests while keeping a minimum recovery window.
- self.wait = random.randint(30, 60)
+ self.wait = random.randint(5, 20)
class QueryRanConcurrently(APIException):
diff --git a/posthog/test/test_exceptions.py b/posthog/test/test_exceptions.py
index f0c8c2284219..baafcc1265b0 100644
--- a/posthog/test/test_exceptions.py
+++ b/posthog/test/test_exceptions.py
@@ -20,9 +20,9 @@ from posthog.exceptions import ClickHouseAtCapacity, ClickHouseQueryTimeOut, Que
class TestQueryRetryAfter(SimpleTestCase):
@parameterized.expand(
[
- ("capacity", ClickHouseAtCapacity, 0, 503, "57"),
- ("capacity_minimum", ClickHouseAtCapacity, 31, 503, "30"),
- ("capacity_maximum", ClickHouseAtCapacity, 2, 503, "60"),
+ ("capacity", ClickHouseAtCapacity, 0, 503, "17"),
+ ("capacity_minimum", ClickHouseAtCapacity, 31, 503, "5"),
+ ("capacity_maximum", ClickHouseAtCapacity, 12, 503, "20"),
("timeout", ClickHouseQueryTimeOut, 0, 504, None),
("single_flight_follower", QueryRanConcurrently, 0, 503, None),
]
@@ -43,7 +43,7 @@ class TestQueryRetryAfter(SimpleTestCase):
def test_capacity_retry_after_varies_between_errors_but_is_stable_for_each_error(self) -> None:
with patch("random.randint", side_effect=Random(0).randint):
- for expected_retry_after in ("57", "42", "54"):
+ for expected_retry_after in ("17", "18", "6"):
exception = ClickHouseAtCapacity(detail="Try again later.", code="busy")
for _ in range(2):
response = exception_handler(