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(dashboards): rerun a tile query when its async status expired (#109210)

posthog[bot]6e8f2820fbc9
diff --git a/frontend/src/queries/query.test.ts b/frontend/src/queries/query.test.ts
index 9c86eb7d6ef4..7ccd15c78e85 100644
--- a/frontend/src/queries/query.test.ts
+++ b/frontend/src/queries/query.test.ts
@@ -340,6 +340,25 @@ describe('query', () => {
expect(querySpy.mock.calls[1][1]?.refresh).toBe('async')
})
+ it.each([
+ { name: 'a failed rerun', results: undefined, error: true, recovered: false },
+ { name: 'an empty result', results: [], error: false, recovered: true },
+ ])('records recovery accurately for $name after expiry', async ({ results, error, recovered }) => {
+ const capture = jest.spyOn(posthog, 'capture').mockImplementation()
+ jest.spyOn(api, 'query').mockResolvedValueOnce(submitted('gone')).mockResolvedValueOnce(submitted('rerun'))
+ jest.spyOn(api.queryStatus, 'get')
+ .mockRejectedValueOnce(forgotten())
+ .mockResolvedValueOnce({ query_status: { id: 'rerun', complete: true, error, results } } as any)
+
+ await expect(performQuery(query, undefined, 'async')).resolves.toEqual(results)
+
+ expect(capture.mock.calls.find(([event]) => event === 'query completed')?.[1]).toMatchObject({
+ submit_attempts: 2,
+ retry_status: 404,
+ retry_recovered: recovered,
+ })
+ })
+
it.each([
['an error that is not a 404', new ApiError('boom', 500), undefined],
['an error with a caller-supplied ID', new ApiError('boom', 500), 'client-query-id'],
diff --git a/frontend/src/queries/query.ts b/frontend/src/queries/query.ts
index 5db5eadf6dd4..a9c6f122bd9d 100644
--- a/frontend/src/queries/query.ts
+++ b/frontend/src/queries/query.ts
@@ -109,6 +109,14 @@ function isRetryableSubmitFailure(error: unknown, refresh: RefreshType): boolean
return capacityWaitMs(error) !== undefined
}
+/**
+ * A missing query status can be recovered by submitting again. An unavailable managed
+ * warehouse also answers 404, but resubmitting cannot fix that.
+ */
+export function isExpiredQueryStatusError(e: any): boolean {
+ return e?.status === 404 && e?.code !== MANAGED_WAREHOUSE_UNAVAILABLE_CODE
+}
+
/**
* Parse error message that may be in ErrorDetail string format.
* Backend sometimes serializes ValidationError.detail as a string like:
@@ -315,9 +323,7 @@ async function executeQuery<N extends DataNode>(
try {
statusResponse = await pollForResults(queryId, methodOptions, setPollResponse)
} catch (e: any) {
- // The server keeps a query's status in Redis for 20 minutes. A backgrounded tab stops
- // polling and stops its own give-up timer, so it can outlive that TTL and then poll for a
- // query the server has forgotten. That query most likely finished and cached its result.
+ // A backgrounded tab can outlive the query's status. Submit once more to recover its result.
//
// So run it again, once. force_async becomes async, to read the cached result instead of
// recomputing it. The query ID is reused, so cancels and log lookups still find the run;
@@ -326,12 +332,7 @@ async function executeQuery<N extends DataNode>(
// A warehouse that is down also answers 404. Do not retry that one. A shared or exported
// view may only read, so it cannot submit at all; report the expired status rather than
// the permission error the server would answer with.
- if (
- retriedAfterExpiry ||
- e?.status !== 404 ||
- e?.code === MANAGED_WAREHOUSE_UNAVAILABLE_CODE ||
- isSharedView()
- ) {
+ if (retriedAfterExpiry || !isExpiredQueryStatusError(e) || isSharedView()) {
throw e
}
return await executeQuery(
diff --git a/frontend/src/scenes/dashboard/dashboardUtils.test.ts b/frontend/src/scenes/dashboard/dashboardUtils.test.ts
index 46689593ad8a..d052c3bd3915 100644
--- a/frontend/src/scenes/dashboard/dashboardUtils.test.ts
+++ b/frontend/src/scenes/dashboard/dashboardUtils.test.ts
@@ -373,9 +373,10 @@ describe('getInsightWithRetry', () => {
})
describe.each([
- ['blocking retry', 2],
- ['async fallback', 1],
- ] as const)('%s recovery', (_path, maxAttempts) => {
+ ['blocking retry', 2, false],
+ ['async fallback', 1, false],
+ ['expired async fallback', 1, true],
+ ] as const)('%s recovery', (_path, maxAttempts, expiredStatus) => {
it.each<{ name: string; response: Partial<InsightModel> | null; recovered: boolean; hasError: boolean }>([
{
name: 'a usable result',
@@ -422,9 +423,12 @@ describe('getInsightWithRetry', () => {
error_message: null,
},
})
- jest.spyOn(api.queryStatus, 'get').mockResolvedValue({
+ const statusSpy = jest.spyOn(api.queryStatus, 'get').mockResolvedValue({
query_status: { ...capacityStatus, error: false, error_code: null, error_message: null },
})
+ if (expiredStatus) {
+ statusSpy.mockRejectedValueOnce(new ApiError('Query not found', 404))
+ }
const request = getInsightWithRetry(
1,
@@ -447,8 +451,120 @@ describe('getInsightWithRetry', () => {
).toHaveLength(recovered ? 1 : 0)
expect(result?.result ?? null).toEqual(response?.result ?? null)
expect(Boolean(result?.query_status?.error)).toBe(hasError)
+ if (expiredStatus) {
+ expect(capture.mock.calls.filter(([event]) => event === 'query rerun after status expired')).toEqual([
+ ['query rerun after status expired', { source: 'dashboard_tile', recovered }, undefined],
+ ])
+ }
})
})
+
+ it.each(['failed status', 'failed cache fetch', 'cancelled cache fetch'] as const)(
+ 'does not count a %s as recovery after expiry',
+ async (failure) => {
+ const capture = jest.spyOn(posthog, 'capture').mockImplementation()
+ jest.spyOn(lemonToast, 'error').mockImplementation()
+ const cancelled = failure === 'cancelled cache fetch'
+ const cacheError = cancelled ? new DOMException('Aborted', 'AbortError') : new ApiError('Unavailable', 503)
+ const getResponse = jest
+ .spyOn(api, 'getResponse')
+ .mockResolvedValueOnce(insightResponse({ ...insight, result: null, query_status: capacityStatus }))
+ .mockRejectedValueOnce(cacheError)
+ jest.spyOn(api, 'get').mockResolvedValue({
+ ...insight,
+ query_status: { ...capacityStatus, complete: false, error: false },
+ })
+ jest.spyOn(api.queryStatus, 'get')
+ .mockRejectedValueOnce(new ApiError('Query not found', 404))
+ .mockResolvedValueOnce({ query_status: { ...capacityStatus, error: failure === 'failed status' } })
+
+ const request = getInsightWithRetry(
+ 1,
+ insight,
+ 60,
+ 'query-id',
+ 'blocking',
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ 1,
+ 1
+ )
+ const outcome = Promise.allSettled([request])
+ await jest.runAllTimersAsync()
+ expect((await outcome)[0].status).toBe(cancelled ? 'rejected' : 'fulfilled')
+ expect(getResponse).toHaveBeenCalledTimes(failure === 'failed status' ? 1 : 2)
+ expect(capture.mock.calls.filter(([event]) => event === 'query rerun after status expired')).toEqual(
+ cancelled
+ ? []
+ : [['query rerun after status expired', { source: 'dashboard_tile', recovered: false }, undefined]]
+ )
+ expect(
+ capture.mock.calls.filter(([event]) => event === 'dashboard tile recovered from capacity error')
+ ).toHaveLength(0)
+ }
+ )
+
+ it.each([
+ { description: 'available', cachedResult: ['from the cache'], queryStatus: null },
+ { description: 'missing', cachedResult: null, queryStatus: null },
+ {
+ description: 'available while refreshing',
+ cachedResult: ['from the cache'],
+ queryStatus: { id: 'refresh', complete: false, error: false },
+ },
+ {
+ description: 'empty while refreshing',
+ cachedResult: [],
+ queryStatus: { id: 'refresh', complete: false, error: false },
+ },
+ ])('handles a cached result that is $description after status expiry', async ({ cachedResult, queryStatus }) => {
+ const capture = jest.spyOn(posthog, 'capture').mockImplementation()
+ jest.spyOn(lemonToast, 'error').mockImplementation()
+ const rateLimited = {
+ ...insight,
+ result: null,
+ query_status: { id: 'cache_1_abc', error: true, error_message: 'concurrency_limit_exceeded' },
+ }
+ jest.spyOn(api, 'getResponse').mockResolvedValue({ json: async () => rateLimited } as Response)
+ const getSpy = jest
+ .spyOn(api, 'get')
+ .mockResolvedValueOnce({ ...insight, result: null, query_status: { id: 'cache_1_abc', complete: false } })
+ .mockResolvedValueOnce({ ...insight, result: cachedResult, query_status: queryStatus })
+ const statusSpy = jest
+ .spyOn(api.queryStatus, 'get')
+ .mockRejectedValueOnce(new ApiError('Query not found', 404))
+ .mockRejectedValue(new ApiError('Background refresh unavailable', 503))
+
+ const request = getInsightWithRetry(
+ 1,
+ insight,
+ 60,
+ 'query-id',
+ 'blocking',
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ 1,
+ 1
+ )
+ await jest.runAllTimersAsync()
+ const result = await request
+ expect(result?.result).toEqual(cachedResult)
+ expect(Boolean(result?.query_status?.error)).toBe(cachedResult === null)
+ expect(getSpy.mock.calls[1][0]).toContain('refresh=async')
+ expect(statusSpy).toHaveBeenCalledTimes(1)
+ expect(
+ capture.mock.calls.filter(([event]) => event === 'dashboard tile recovered from capacity error')
+ ).toHaveLength(cachedResult === null ? 0 : 1)
+ expect(capture).toHaveBeenCalledWith(
+ 'query rerun after status expired',
+ { source: 'dashboard_tile', recovered: cachedResult !== null },
+ undefined
+ )
+ })
})
describe('shouldSharedDashboardAutoForceForStaleTime', () => {
diff --git a/frontend/src/scenes/dashboard/dashboardUtils.ts b/frontend/src/scenes/dashboard/dashboardUtils.ts
index a64c3d01008a..119c009ccffd 100644
--- a/frontend/src/scenes/dashboard/dashboardUtils.ts
+++ b/frontend/src/scenes/dashboard/dashboardUtils.ts
@@ -4,7 +4,7 @@ import { ResponsiveLayouts } from 'react-grid-layout'
import { lemonToast } from '@posthog/lemon-ui'
import { getDashboardWidgetCatalogEntry } from '@posthog/products-dashboards/frontend/widget_types/catalog'
-import api, { ApiMethodOptions, getJSONOrNull } from 'lib/api'
+import api, { ApiMethodOptions, getJSONOrNull, isAbortError } from 'lib/api'
import { ApiError, CLICKHOUSE_MEMORY_LIMIT_ERROR_CODE } from 'lib/api-error'
import type { Dayjs } from 'lib/dayjs'
import { currentSessionId } from 'lib/internalMetrics'
@@ -16,8 +16,8 @@ import { isDeterministicClientError, shouldCancelQuery } from 'lib/utils/request
import { toParams } from 'lib/utils/url'
import { getQueryBasedInsightModel } from '~/queries/nodes/InsightViz/utils'
-import { parseErrorMessage, pollForResults } from '~/queries/query'
-import { DashboardFilter, HogQLVariable, TileFilters } from '~/queries/schema/schema-general'
+import { isExpiredQueryStatusError, parseErrorMessage, pollForResults } from '~/queries/query'
+import { DashboardFilter, HogQLVariable, QueryStatus, TileFilters } from '~/queries/schema/schema-general'
import {
AccessControlLevel,
AccessControlResourceType,
@@ -304,6 +304,28 @@ export const layoutsByTile = (layouts: ResponsiveLayouts): Record<string, Record
return itemLayouts
}
+/**
+ * Records whether a tile rerun after an expired status poll recovers, because the 404 alone does not show it.
+ * The insights endpoint bypasses performQuery, so its query submission telemetry never sees this rerun.
+ */
+async function captureTileRerunAfterStatusExpired(
+ rerun: () => Promise<InsightModel | null>
+): Promise<InsightModel | null> {
+ try {
+ const result = await rerun()
+ posthog.capture('query rerun after status expired', {
+ source: 'dashboard_tile',
+ recovered: result?.result != null && !result.query_status?.error,
+ })
+ return result
+ } catch (e) {
+ if (!isAbortError(e)) {
+ posthog.capture('query rerun after status expired', { source: 'dashboard_tile', recovered: false })
+ }
+ throw e
+ }
+}
+
/**
* Fetches an insight with a retry and polling mechanism.
* It first attempts to fetch the insight synchronously. If rate-limited, it retries with exponential backoff.
@@ -371,21 +393,17 @@ export async function getInsightWithRetry(
if (attempt >= maxAttempts) {
// We've exhausted all attempts, so we need to try the async endpoint.
try {
- const asyncApiUrl = `api/projects/${currentTeamId}/insights/${insight.id}/?${toParams({
- refresh: 'force_async',
- from_dashboard: dashboardId,
- client_query_id: queryId,
- session_id: currentSessionId(),
- ...(filtersOverride ? { filters_override: filtersOverride } : {}),
- ...(variablesOverride ? { variables_override: variablesOverride } : {}),
- ...(tileFiltersOverride ? { tile_filters_override: tileFiltersOverride } : {}),
- })}`
- // The async call returns an insight with a query_status object
- // nosemgrep: prefer-codegen-api -- Legacy raw API call with a URL built at runtime and an unchecked response type. Use a generated function if one covers this endpoint.
- const insightResponse = await api.get(asyncApiUrl, methodOptions)
-
- if (insightResponse?.query_status?.id) {
- const finalStatus = await pollForResults(insightResponse.query_status.id, methodOptions)
+ const asyncApiUrl = (asyncRefresh: 'force_async' | 'async'): string =>
+ `api/projects/${currentTeamId}/insights/${insight.id}/?${toParams({
+ refresh: asyncRefresh,
+ from_dashboard: dashboardId,
+ client_query_id: queryId,
+ session_id: currentSessionId(),
+ ...(filtersOverride ? { filters_override: filtersOverride } : {}),
+ ...(variablesOverride ? { variables_override: variablesOverride } : {}),
+ ...(tileFiltersOverride ? { tile_filters_override: tileFiltersOverride } : {}),
+ })}`
+ const readCachedInsight = async (finalStatus: QueryStatus): Promise<InsightModel | null> => {
if (finalStatus.complete && !finalStatus.error) {
const cacheUrl = `api/projects/${currentTeamId}/insights/${insight.id}/?${toParams({
refresh: 'force_cache',
@@ -404,7 +422,6 @@ export async function getInsightWithRetry(
const legacyInsight: InsightModel | null = await getJSONOrNull(refreshedInsightResponse)
if (legacyInsight) {
const queryBasedInsight = getQueryBasedInsightModel(legacyInsight)
- captureRecovery(queryBasedInsight)
return {
...queryBasedInsight,
query_status: queryBasedInsight.query_status?.error
@@ -413,6 +430,54 @@ export async function getInsightWithRetry(
}
}
}
+ return null
+ }
+ // nosemgrep: prefer-codegen-api -- Legacy raw API call with a URL built at runtime and an unchecked response type. Use a generated function if one covers this endpoint.
+ const insightResponse = await api.get(asyncApiUrl('force_async'), methodOptions)
+
+ if (insightResponse?.query_status?.id) {
+ let finalStatus: QueryStatus
+ try {
+ finalStatus = await pollForResults(insightResponse.query_status.id, methodOptions)
+ } catch (e) {
+ // pollForResults pauses in a hidden tab, so the status can expire before the next poll.
+ // The insights endpoint ignores client_query_id and names the run by its cache key, so
+ // the rerun in executeQuery never sees this poll. Submit once more with async, which
+ // reads the result that the finished run cached.
+ if (!isExpiredQueryStatusError(e)) {
+ throw e
+ }
+ const rerun = await captureTileRerunAfterStatusExpired(async () => {
+ // nosemgrep: prefer-codegen-api -- Preserve the existing dynamic insight request and its filter overrides.
+ const rerunResponse = await api.get(asyncApiUrl('async'), methodOptions)
+ if (rerunResponse?.result != null && !rerunResponse.query_status?.error) {
+ return getQueryBasedInsightModel(rerunResponse)
+ }
+ if (
+ rerunResponse?.result == null &&
+ rerunResponse?.query_status?.id &&
+ !rerunResponse.query_status.complete
+ ) {
+ return await readCachedInsight(
+ await pollForResults(rerunResponse.query_status.id, methodOptions)
+ )
+ }
+ if (rerunResponse?.result == null) {
+ throw new Error('The rerun returned no result')
+ }
+ return getQueryBasedInsightModel(rerunResponse)
+ })
+ if (!rerun) {
+ throw new Error('The rerun returned no result')
+ }
+ captureRecovery(rerun)
+ return rerun
+ }
+ const cachedInsight = await readCachedInsight(finalStatus)
+ if (cachedInsight) {
+ captureRecovery(cachedInsight)
+ return cachedInsight
+ }
}
// If something went wrong with async, show an error.