:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(insights): run a query again when its status has expired (#94881)
Sandy Spicer594d496a53ac
diff --git a/frontend/src/queries/query.test.ts b/frontend/src/queries/query.test.tsindex 737d529a4615..48d0887b3fe5 100644--- a/frontend/src/queries/query.test.ts+++ b/frontend/src/queries/query.test.ts@@ -283,6 +283,98 @@ describe('query', () => {})})+ describe('polling a query the server has forgotten', () => {+ const query = { kind: NodeKind.EventsQuery, select: ['*'] } as EventsQuery+ const submitted = (id: string): any => ({ query_status: { id, complete: false } })+ const forgotten = (): ApiError => new ApiError('Query not found', 404, undefined, { detail: 'Query not found' })++ afterEach(() => {+ jest.restoreAllMocks()+ delete (window as any).POSTHOG_EXPORTED_DATA+ })++ it('runs the query again when its status has expired', async () => {+ const querySpy = jest+ .spyOn(api, 'query')+ .mockResolvedValueOnce(submitted('gone'))+ .mockResolvedValueOnce({ results: ['from the cache'], is_cached: true } as any)+ jest.spyOn(api.queryStatus, 'get').mockRejectedValueOnce(forgotten())++ await expect(performQuery(query, undefined, 'async')).resolves.toMatchObject({+ results: ['from the cache'],+ })++ 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')+ })++ it('reads the cache on the retry rather than forcing the same work twice', async () => {+ const querySpy = jest+ .spyOn(api, 'query')+ .mockResolvedValueOnce(submitted('gone'))+ .mockResolvedValueOnce({ results: ['from the cache'], is_cached: true } as any)+ jest.spyOn(api.queryStatus, 'get').mockRejectedValueOnce(forgotten())++ await performQuery(query, undefined, 'force_async')++ // force_async disregards the cache, and the first run already cached what it computed.+ expect(querySpy.mock.calls[0][1]?.refresh).toBe('force_async')+ expect(querySpy.mock.calls[1][1]?.refresh).toBe('async')+ })++ it.each([+ ['an error that is not a 404', new ApiError('boom', 500)],+ [+ 'a warehouse whose connection is down',+ new ApiError('unavailable', 404, undefined, { code: 'managed_warehouse_connection_unavailable' }),+ ],+ ])('does not resubmit on %s', async (_name, failure) => {+ const querySpy = jest.spyOn(api, 'query').mockResolvedValueOnce(submitted('gone'))+ jest.spyOn(api.queryStatus, 'get').mockRejectedValueOnce(failure)++ await expect(performQuery(query, undefined, 'async')).rejects.toMatchObject({+ status: failure.status,+ })++ expect(querySpy).toHaveBeenCalledTimes(1)+ })++ it('gives up when the second attempt is forgotten too', async () => {+ jest.spyOn(api, 'query').mockResolvedValue(submitted('gone'))+ const statusSpy = jest.spyOn(api.queryStatus, 'get').mockRejectedValue(forgotten())++ await expect(performQuery(query, undefined, 'async')).rejects.toMatchObject({ status: 404 })++ expect(statusSpy).toHaveBeenCalledTimes(2)+ })++ it('runs the query again for a tile resuming a recompute, which polls by id but holds the query', async () => {+ const querySpy = jest+ .spyOn(api, 'query')+ .mockResolvedValueOnce({ results: ['from the cache'], is_cached: true } as any)+ jest.spyOn(api.queryStatus, 'get').mockRejectedValueOnce(forgotten())++ await expect(+ performQuery(query, undefined, 'async', 'resumed', undefined, undefined, undefined, true)+ ).resolves.toMatchObject({ results: ['from the cache'] })++ expect(querySpy).toHaveBeenCalledTimes(1)+ })++ it('does not even try to resubmit from a shared or exported view', async () => {+ const querySpy = jest.spyOn(api, 'query')+ jest.spyOn(api.queryStatus, 'get').mockRejectedValueOnce(forgotten())+ ;(window as any).POSTHOG_EXPORTED_DATA = { type: 'embed' }++ await expect(+ performQuery(query, undefined, 'async', 'gone', undefined, undefined, undefined, true)+ ).rejects.toMatchObject({ status: 404 })++ expect(querySpy).not.toHaveBeenCalled()+ })+ })+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.tsindex d77263be5262..cd9b517ad7ac 100644--- a/frontend/src/queries/query.ts+++ b/frontend/src/queries/query.ts@@ -2,6 +2,7 @@ import api, { ApiMethodOptions, isAbortError } from 'lib/api'import posthog from 'lib/posthog-typed'import { delay } from 'lib/utils/async'+import { isSharedView } from '~/exporter/exporterViewLogic'import {DashboardFilter,DataNode,@@ -64,6 +65,8 @@ export function waitForPageVisible(signal?: AbortSignal): Promise<void> {const QUERY_ASYNC_MAX_INTERVAL_SECONDS = 3const QUERY_ASYNC_TOTAL_POLL_SECONDS = 10 * 60 + 6 // keep in sync with backend-side timeout (currently 10min) + a small bufferexport 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'/*** Parse error message that may be in ErrorDetail string format.@@ -181,7 +184,9 @@ async function executeQuery<N extends DataNode>(* (stale-while-revalidate: `is_cached` is true *and* an incomplete `query_status` is* attached), return the cached results immediately instead of blocking on the recompute.*/- acceptStaleCache = false+ acceptStaleCache = false,+ /** True on the retry below, so a failed retry cannot start another one. */+ retriedAfterExpiry = false): Promise<NonNullable<N['response']>> {if (!pollOnly) {const refreshParam: RefreshType = refresh || 'blocking'@@ -220,7 +225,43 @@ async function executeQuery<N extends DataNode>(}}- const statusResponse = await pollForResults(queryId, methodOptions, setPollResponse)+ let statusResponse: QueryStatus+ 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.+ //+ // 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;+ // safe because the server only joins a query that is still running.+ //+ // 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()+ ) {+ throw e+ }+ return await executeQuery(+ queryNode,+ methodOptions,+ refresh === 'force_async' ? 'async' : refresh,+ queryId,+ setPollResponse,+ filtersOverride,+ variablesOverride,+ false,+ limitContext,+ acceptStaleCache,+ true+ )+ }return statusResponse.results}diff --git a/posthog/clickhouse/client/execute_async.py b/posthog/clickhouse/client/execute_async.pyindex 4d2881ec2411..069b3742b4b3 100644--- a/posthog/clickhouse/client/execute_async.py+++ b/posthog/clickhouse/client/execute_async.py@@ -121,9 +121,6 @@ class QueryStatusManager:self._store_clickhouse_query_progress_dict(clickhouse_query_progress_dict)self.redis_client.set(self.heartbeat_key, "1", ex=self.HEARTBEAT_TTL_SECONDS)- def has_results(self) -> bool:- return self.redis_client.exists(self.results_key) == 1-def get_clickhouse_progresses(self) -> Optional[ClickhouseQueryProgress]:try:clickhouse_query_progress_dict = self._get_clickhouse_query_progress_dict()@@ -357,9 +354,17 @@ def enqueue_process_query_task(if force:cancel_query(team.id, query_id)- if manager.has_results() and not refresh_requested:- # If we've seen this query before return and don't resubmit it.- return manager.get_query_status()+ if not refresh_requested:+ try:+ # Only join a query that is still running. We are here because the cache already+ # decided this query needs to run, so handing back a finished record would replay the+ # old result and start nothing, blocking the refresh until that record expires.+ # Throttling a query that keeps failing is the query runner's job, not this one's.+ in_flight = manager.get_query_status()+ if not in_flight.complete:+ return in_flight+ except QueryNotFoundError:+ passtry:if cache_key:diff --git a/posthog/clickhouse/client/test/test_execute_async.py b/posthog/clickhouse/client/test/test_execute_async.pyindex 7fc596e75918..3154779c8521 100644--- a/posthog/clickhouse/client/test/test_execute_async.py+++ b/posthog/clickhouse/client/test/test_execute_async.py@@ -410,26 +410,38 @@ class ClickhouseClientTestCase(TestCase, ClickhouseTestMixin):except Exception as e:self.assertEqual(str(e), f"Query {query_id} not found for team {wrong_team}")+ @parameterized.expand(+ [+ ("still_running", None, 1),+ ("finished", False, 2),+ ("failed", True, 2),+ ]+ )@patch("posthog.clickhouse.client.execute_process_query")- def test_async_query_client_is_lazy(self, execute_process_query_mock):+ def test_async_query_client_joins_only_a_run_still_going(+ self, _name, finished_with_error, expected_runs, execute_process_query_mock+ ):query = build_query("SELECT 4 + 4")query_id = uuid.uuid4().hex+ manager = QueryStatusManager(query_id, self.team.id)client.enqueue_process_query_task(self.team, self.user.id, query, query_id=query_id, _test_only_bypass_celery=True)+ if finished_with_error is not None:+ status = manager.get_query_status()+ status.complete = True+ status.error = finished_with_error+ manager.store_query_status(status)- # Try the same query again+ # The same query ID twice more: joined while the run is going, rerun once it has finished.client.enqueue_process_query_task(self.team, self.user.id, query, query_id=query_id, _test_only_bypass_celery=True)-- # Try the same query again (for good measure!)client.enqueue_process_query_task(self.team, self.user.id, query, query_id=query_id, _test_only_bypass_celery=True)- # Assert that we only called clickhouse once- execute_process_query_mock.assert_called_once()+ self.assertEqual(execute_process_query_mock.call_count, expected_runs)@patch("posthog.clickhouse.client.execute_process_query")def test_async_query_client_is_lazy_but_not_too_lazy(self, execute_process_query_mock):