: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(search): prevent /search page from hanging on loading skeleton (#64953)
posthog[bot]b09b6632779c
diff --git a/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx b/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsxindex 683db2e03467..6fcb2563ad06 100644--- a/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx+++ b/frontend/src/layout/panel-layout/ProjectTree/projectTreeDataLogic.tsx@@ -10,6 +10,7 @@ import { lemonToast } from 'lib/lemon-ui/LemonToast'import { TreeDataItem } from 'lib/lemon-ui/LemonTree/LemonTree'import { Spinner } from 'lib/lemon-ui/Spinner'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { withTimeout } from 'lib/utils/async'import { eventUsageLogic } from 'lib/utils/eventUsageLogic'import { getCurrentTeamIdOrNone } from 'lib/utils/getAppContext'import { capitalizeFirstLetter, humanList, identifierToHuman, pluralize } from 'lib/utils/strings'@@ -47,6 +48,13 @@ import type { projectTreeDataLogicType } from './projectTreeDataLogicType'const MOVE_ALERT_LIMIT = 50const DELETE_ALERT_LIMIT = 0+/**+ * Upper bound on how long the starred-shortcuts fetch may run before we give up. A stalled+ * request that never settles would otherwise leave `shortcutDataHasLoaded` false forever,+ * freezing the global search page on a loading skeleton (the flag only flips via the loader's+ * Success/Failure reducers).+ */+const SHORTCUTS_LOADER_TIMEOUT_MS = 10000export const PAGINATION_LIMIT = 100const PRODUCTS_SHOWN_WITH_SELECTED_PRODUCTS: Record<string, string[]> = {'LLM analytics': ['MCP analytics'],@@ -465,7 +473,16 @@ export const projectTreeDataLogic = kea<projectTreeDataLogicType>([return []}- const response = await api.fileSystemShortcuts.list()+ // A stalled fetch that never settles would leave `shortcutDataHasLoaded` false+ // forever and freeze the search page on a loading skeleton. The timeout makes+ // the loader settle: on timeout it rejects, firing loadShortcutsFailure (which+ // flips shortcutDataHasLoaded), and kea-loaders' global onFailure handler in+ // initKea captures the exception so the previously-silent hang is surfaced.+ const response = await withTimeout(+ api.fileSystemShortcuts.list(),+ SHORTCUTS_LOADER_TIMEOUT_MS,+ 'loadShortcuts timed out'+ )return response.results},addShortcutItem: async ({ item }) => {diff --git a/frontend/src/lib/utils/async.test.ts b/frontend/src/lib/utils/async.test.tsindex fc215d0c6884..f306de0aa202 100644--- a/frontend/src/lib/utils/async.test.ts+++ b/frontend/src/lib/utils/async.test.ts@@ -1,6 +1,42 @@-import { retryWithBackoff } from 'lib/utils/async'+import { PromiseTimeoutError, retryWithBackoff, withTimeout } from 'lib/utils/async'describe('async utils', () => {+ describe('withTimeout()', () => {+ beforeEach(() => {+ jest.useFakeTimers()+ })++ afterEach(() => {+ jest.useRealTimers()+ })++ it('resolves with the value when the promise settles in time', async () => {+ const result = await withTimeout(Promise.resolve('done'), 1000)+ expect(result).toBe('done')+ })++ it('rejects with the original error when the promise rejects in time', async () => {+ await expect(withTimeout(Promise.reject(new Error('boom')), 1000)).rejects.toThrow('boom')+ })++ it('rejects with a PromiseTimeoutError when the promise never settles', async () => {+ // A promise that never resolves nor rejects — the stalled-fetch scenario.+ const neverSettles = new Promise<string>(() => {})+ const wrapped = withTimeout(neverSettles, 10000, 'loadRecents timed out')+ const assertion = expect(wrapped).rejects.toThrow(PromiseTimeoutError)+ await jest.advanceTimersByTimeAsync(10000)+ await assertion+ await expect(wrapped).rejects.toThrow('loadRecents timed out')+ })++ it('does not time out a promise that resolves just before the deadline', async () => {+ const slow = new Promise<string>((resolve) => setTimeout(() => resolve('slow'), 9000))+ const wrapped = withTimeout(slow, 10000)+ await jest.advanceTimersByTimeAsync(9000)+ await expect(wrapped).resolves.toBe('slow')+ })+ })+describe('retryWithBackoff()', () => {it('returns result on first successful attempt', async () => {const fn = jest.fn().mockResolvedValue('success')diff --git a/frontend/src/lib/utils/async.ts b/frontend/src/lib/utils/async.tsindex 41f033e602ea..ea08b7313c7d 100644--- a/frontend/src/lib/utils/async.ts+++ b/frontend/src/lib/utils/async.ts@@ -87,6 +87,44 @@ export async function retryWithBackoff<T>(fn: () => Promise<T>, options: RetryOpthrow lastError}+/** Thrown by {@link withTimeout} when the wrapped promise does not settle in time. */+export class PromiseTimeoutError extends Error {+ constructor(message?: string) {+ super(message ?? 'Promise timed out')+ this.name = 'PromiseTimeoutError'+ }+}++/**+ * Races a promise against a timeout. If `promise` does not settle within `timeoutMs`, the+ * returned promise rejects with a {@link PromiseTimeoutError}.+ *+ * Use this to guard against a fetch that can stall indefinitely without ever resolving or+ * rejecting (e.g. a hung connection that is never aborted). Such a fetch leaves any awaiting+ * loader permanently "loading", which is exactly what freezes the global search page on a+ * loading skeleton.+ *+ * @example+ * const response = await withTimeout(api.fileSystem.list(...), 10000, 'loadRecents timed out')+ */+export function withTimeout<T>(promise: Promise<T>, timeoutMs: number, message?: string): Promise<T> {+ return new Promise<T>((resolve, reject) => {+ const timeoutId = setTimeout(() => {+ reject(new PromiseTimeoutError(message ?? `Promise timed out after ${timeoutMs}ms`))+ }, timeoutMs)+ promise.then(+ (value) => {+ clearTimeout(timeoutId)+ resolve(value)+ },+ (error) => {+ clearTimeout(timeoutId)+ reject(error)+ }+ )+ })+}+export function promiseResolveReject<T>(): {resolve: (value: T) => voidreject: (reason?: any) => voiddiff --git a/frontend/src/models/recentItemsModel.ts b/frontend/src/models/recentItemsModel.tsindex 8c9217131886..3b0f051e7303 100644--- a/frontend/src/models/recentItemsModel.ts+++ b/frontend/src/models/recentItemsModel.ts@@ -1,7 +1,9 @@import { actions, afterMount, connect, kea, listeners, path, reducers } from 'kea'import { loaders } from 'kea-loaders'+import posthog from 'posthog-js'import api, { ApiConfig } from 'lib/api'+import { PromiseTimeoutError, withTimeout } from 'lib/utils/async'import { permanentlyMount } from 'lib/utils/kea-logic-builders'import { teamLogic } from 'scenes/teamLogic'@@ -10,6 +12,13 @@ import { FileSystemEntry } from '~/queries/schema/schema-general'import type { recentItemsModelType } from './recentItemsModelType'const RECENTS_FETCH_LIMIT = 20+/**+ * Upper bound on how long a recents/scene-views fetch may run before we give up. A stalled+ * request that never settles would otherwise leave `recentsHasLoaded` / `sceneLogViewsHasLoaded`+ * false forever, freezing the global search page on a loading skeleton (these flags only flip+ * via the loaders' Success/Failure reducers).+ */+const LOADER_TIMEOUT_MS = 10000export const recentItemsModel = kea<recentItemsModelType>([path(['models', 'recentItemsModel']),@@ -32,13 +41,23 @@ export const recentItemsModel = kea<recentItemsModelType>([}try {- const response = await api.fileSystem.list({- orderBy: '-last_viewed_at',- notType: 'folder',- limit: RECENTS_FETCH_LIMIT,- })+ const response = await withTimeout(+ api.fileSystem.list({+ orderBy: '-last_viewed_at',+ notType: 'folder',+ limit: RECENTS_FETCH_LIMIT,+ }),+ LOADER_TIMEOUT_MS,+ 'loadRecents timed out'+ )return response.results- } catch {+ } catch (error) {+ // A stalled fetch that never settles would freeze the search page on a+ // skeleton; the timeout lets the loader settle. Surface the hang so these+ // previously-invisible stuck states show up as captured exceptions.+ if (error instanceof PromiseTimeoutError) {+ posthog.captureException(error)+ }// Recents are a non-essential homepage widget — transient failures (offline,// aborted navigation, blocked requests) shouldn't surface as captured exceptions.return []@@ -55,7 +74,11 @@ export const recentItemsModel = kea<recentItemsModelType>([}try {- const results = await api.fileSystemLogView.list({ type: 'scene' })+ const results = await withTimeout(+ api.fileSystemLogView.list({ type: 'scene' }),+ LOADER_TIMEOUT_MS,+ 'loadSceneLogViews timed out'+ )const record: Record<string, string> = {}for (const { ref, viewed_at } of results) {const current = record[ref]@@ -64,9 +87,12 @@ export const recentItemsModel = kea<recentItemsModelType>([}}return record- } catch {- // See loadRecents: this is a best-effort homepage widget, so transient- // fetch failures should degrade to an empty result rather than throw.+ } catch (error) {+ // See loadRecents: a hung fetch is surfaced, while transient failures+ // degrade to an empty result rather than throw.+ if (error instanceof PromiseTimeoutError) {+ posthog.captureException(error)+ }return {}}},