: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(taxonomic-filter): show a retryable error when a list fetch fails (#78609)
Eli Reisman08cf9ad1fd08
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 6c16fa66e472..c5af2e2d888c 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -2536,6 +2536,10 @@ snapshots:hash: v1.k794b7964.422ddb7aef488b7df5fb0a27715994aed79448f280b62f4e786e08f755c88b3c.kny9iJ5G5fwjTNqF1xKveHzAT06hjte-CATByxBVFaMfilters-taxonomic-filter--events-premium--light:hash: v1.k794b7964.81a78bc8ee376be4d5515ddcab000082de15195a6ea1e700546a2346d4cb17f3.BZBvpIZWaczTKJuEBUyigcG45af_A0jgpe10HbXQ9rQ+ filters-taxonomic-filter--failed-fetch-offers-retry--dark:+ hash: v1.k794b7964.dbbfe19dede7bc642e918f48fb4f80151c48e2ccbbcb62617157e6df3c4d533d.C8yxDgBe0uM24bqwnL0r4iJczX5vS93okDcE1Ceqsos+ filters-taxonomic-filter--failed-fetch-offers-retry--light:+ hash: v1.k794b7964.a7baf4370142ad9d63f131c07b9485638e88a08d8dec67196e85f1b098a7c48d.KNaiZbsQDpXQXNeJ04WDLW_9pdwkXpIH0HyEajxI86Ifilters-taxonomic-filter--mcp-tool-call-context-leads-with-mcp-properties--dark:hash: v1.k794b7964.13fd306591ab8aa983b98d475f2fa5566c4fdc3f8cf86d634d98c884c326a779.ZS2ZfxmIjJjZY9VD_0Ueclr1mbmK_5qkuHbny_eV2B4filters-taxonomic-filter--mcp-tool-call-context-leads-with-mcp-properties--light:diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 7a8d9c15ea79..72692d861d6b 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -3803,13 +3803,13 @@ const api = {async list(params: GroupListParams): Promise<CountedPaginatedResponse<Group>> {return await new ApiRequest().groups().withQueryString(toParams(params, true)).get()},- async listClickhouse(params: GroupListParams): Promise<GroupsQueryResponse> {+ async listClickhouse(params: GroupListParams, options?: ApiMethodOptions): Promise<GroupsQueryResponse> {const groupsQuery: GroupsQuery = {kind: NodeKind.GroupsQuery,...params,}- return await new ApiRequest().query().create({ data: { query: groupsQuery } })+ return await new ApiRequest().query().create({ ...options, data: { query: groupsQuery } })},async create(data: CreateGroupParams): Promise<Group> {return await new ApiRequest().groups().create({ data })diff --git a/frontend/src/lib/components/TaxonomicFilter/InfiniteList.tsx b/frontend/src/lib/components/TaxonomicFilter/InfiniteList.tsxindex a799623aa027..42bf6969825e 100644--- a/frontend/src/lib/components/TaxonomicFilter/InfiniteList.tsx+++ b/frontend/src/lib/components/TaxonomicFilter/InfiniteList.tsx@@ -6,7 +6,7 @@ import { BindLogic, useActions, useValues } from 'kea'import { CSSProperties, useEffect, useState } from 'react'import { List, useListRef } from 'react-window'-import { IconArchive, IconCheck, IconPin, IconPinFilled, IconPlus, IconSearch } from '@posthog/icons'+import { IconArchive, IconCheck, IconPin, IconPinFilled, IconPlus, IconSearch, IconWarning } from '@posthog/icons'import { LemonButton, LemonDivider, LemonTag } from '@posthog/lemon-ui'import { AutoSizer } from 'lib/components/AutoSizer'@@ -824,6 +824,26 @@ function InfiniteListEmptyState(): JSX.Element {)}+function InfiniteListErrorState(): JSX.Element {+ const { retryRemoteItems } = useActions(infiniteListLogic)++ return (+ <div className="no-infinite-results flex flex-col gap-y-1 items-center">+ <IconWarning className="text-5xl text-tertiary" />+ <span className="text-center">Couldn't load results</span>+ <LemonButton+ type="secondary"+ size="xsmall"+ data-attr="taxonomic-retry-remote-items"+ onClick={retryRemoteItems}+ >+ Try again+ </LemonButton>+ <span className="text-center text-secondary italic">If it keeps happening, contact support.</span>+ </div>+ )+}+export function InfiniteList({ popupAnchorElement, definitionPopoverRenderer }: InfiniteListProps): JSX.Element {const {mouseInteractionsEnabled,@@ -852,6 +872,7 @@ export function InfiniteList({ popupAnchorElement, definitionPopoverRenderer }:showPopover,showNonCapturedEventOption,showEmptyState,+ showErrorState,showLoadingState,isSuggestedFilters,isActiveTab,@@ -878,12 +899,14 @@ export function InfiniteList({ popupAnchorElement, definitionPopoverRenderer }:<divclassName={cn('taxonomic-infinite-list',- showEmptyState && 'empty-infinite-list',+ (showEmptyState || showErrorState) && 'empty-infinite-list','h-full',isSuggestedFilters && 'empty-infinite-list--start')}>- {showEmptyState ? (+ {showErrorState ? (+ <InfiniteListErrorState />+ ) : showEmptyState ? (<InfiniteListEmptyState />) : showLoadingState ? (<div className="flex items-center justify-center h-full">diff --git a/frontend/src/lib/components/TaxonomicFilter/TaxonomicFilter.stories.tsx b/frontend/src/lib/components/TaxonomicFilter/TaxonomicFilter.stories.tsxindex ca08fd79e985..9675e9729a52 100644--- a/frontend/src/lib/components/TaxonomicFilter/TaxonomicFilter.stories.tsx+++ b/frontend/src/lib/components/TaxonomicFilter/TaxonomicFilter.stories.tsx@@ -603,6 +603,42 @@ export const RenamedSeriesSelectedPill: Story = {},}+export const FailedFetchOffersRetry: Story = {+ render: (args) => {+ useMountedLogic(actionsModel)+ const { setSearchQuery } = useActions(+ taxonomicFilterLogic({ ...args, taxonomicFilterLogicKey: args.taxonomicFilterLogicKey as string })+ )++ useOnMountEffect(() => setSearchQuery('user_signed_up'))++ return (+ <div className="w-fit border rounded p-2 bg-surface-primary">+ <TaxonomicFilter {...args} />+ </div>+ )+ },+ args: {+ taxonomicFilterLogicKey: 'events-failed-fetch',+ taxonomicGroupTypes: [TaxonomicFilterGroupType.Events],+ },+ decorators: [+ mswDecorator({+ get: {+ '/api/projects/:team_id/event_definitions': () => [500, { detail: 'server error' }],+ },+ }),+ ],+ parameters: {+ testOptions: { waitForSelector: '[data-attr="taxonomic-retry-remote-items"]' },+ docs: {+ description: {+ story: 'When the search request fails, the list says so and offers a retry, rather than showing the same "No results" as a genuine empty search.',+ },+ },+ },+}+export const EmptyEventsWithStaleToggle: Story = {render: (args) => {useMountedLogic(actionsModel)diff --git a/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.test.ts b/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.test.tsindex db412d24065b..7318b90896fe 100644--- a/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.test.ts+++ b/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.test.ts@@ -14,6 +14,7 @@ import { dataWarehouseSettingsSceneLogic } from 'scenes/data-warehouse/settings/import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'import { useMocks } from '~/mocks/jest'+import { Mocks } from '~/mocks/utils'import { initKeaTests } from '~/test/init'import { mockEventDefinitions, mockEventPropertyDefinitions } from '~/test/mocks'import { AppContext, PropertyDefinition, PropertyFilterType, PropertyOperator, PropertyType } from '~/types'@@ -540,7 +541,7 @@ describe('infiniteListLogic', () => {beforeEach(silenceKeaLoadersErrors)afterEach(resumeKeaLoadersErrors)- it('falls back to the empty state instead of spinning forever when the fetch fails', async () => {+ it('surfaces the error state instead of spinning forever or claiming no results', async () => {useMocks({get: {'/api/projects/:team/event_definitions': () => [500, { detail: 'server error' }],@@ -562,12 +563,12 @@ describe('infiniteListLogic', () => {.toFinishAllListeners().toMatchValues({showLoadingState: false,- showEmptyState: true,+ // A failure must not read as "this event doesn't exist" - that sends people+ // hunting for a tracking bug instead of retrying.+ showEmptyState: false,+ showErrorState: true,})- // The failure lands on the same empty state as a genuine no-match, so telemetry is- // the only prod signal that the backend blipped — losing this capture makes the- // worst case ("event exists, fetch failed") invisible.const failedCalls = captureSpy.mock.calls.filter((c) => c[0] === 'taxonomic filter fetch failed')expect(failedCalls).toHaveLength(1)expect(failedCalls[0][1]).toMatchObject({@@ -575,6 +576,129 @@ describe('infiniteListLogic', () => {searchQuery: 'user_signed_up',})})++ // Group names go out over the query endpoint instead of the list endpoint, so they need+ // the abort signal wired separately - without it the watchdog fires against a controller+ // nobody is listening to and the list keeps spinning.+ const hangingListCases: { label: string; listGroupType: TaxonomicFilterGroupType; mocks: Mocks }[] = [+ {+ label: 'a list endpoint',+ listGroupType: TaxonomicFilterGroupType.Events,+ mocks: {+ get: { '/api/projects/:team/event_definitions': () => new Promise(() => {}) },+ },+ },+ {+ label: 'a group name query',+ listGroupType: `${TaxonomicFilterGroupType.GroupNamesPrefix}_0` as TaxonomicFilterGroupType,+ mocks: {+ get: {+ '/api/projects/:team/groups_types': [+ { group_type: 'organization', group_type_index: 0, name_singular: null, name_plural: null },+ ],+ },+ post: { '/api/environments/:team_id/query/': () => new Promise(() => {}) },+ },+ },+ ]++ it.each(hangingListCases)('gives up on $label that never responds', async ({ listGroupType, mocks }) => {+ useMocks(mocks)+ initKeaTests()+ jest.useFakeTimers()+ try {+ const hangingLogic = infiniteListLogic({+ taxonomicFilterLogicKey: 'hangingList',+ listGroupType,+ taxonomicGroupTypes: [listGroupType],+ showNumericalPropsOnly: false,+ })+ hangingLogic.mount()+ // Let the group type list arrive, so a group name list resolves its group index+ // and takes the query path rather than falling back to the list endpoint.+ await jest.advanceTimersByTimeAsync(1)+ hangingLogic.actions.setSearchQuery('user_signed_up')++ // Past the debounce, so the request is in flight rather than still queued.+ await jest.advanceTimersByTimeAsync(600)+ expect(hangingLogic.values.showLoadingState).toBe(true)++ await jest.advanceTimersByTimeAsync(30000)+ expect(hangingLogic.values.showErrorState).toBe(true)+ } finally {+ jest.useRealTimers()+ }+ })++ it('leaves a search that legitimately found nothing alone once the request timeout elapses', async () => {+ useMocks({+ get: {+ '/api/projects/:team/event_definitions': () => [200, { results: [], count: 0 }],+ },+ })+ initKeaTests()+ jest.useFakeTimers()+ try {+ const emptyLogic = infiniteListLogic({+ taxonomicFilterLogicKey: 'emptyList',+ listGroupType: TaxonomicFilterGroupType.Events,+ taxonomicGroupTypes: [TaxonomicFilterGroupType.Events],+ showNumericalPropsOnly: false,+ })+ emptyLogic.mount()+ emptyLogic.actions.setSearchQuery('definitely_not_a_real_event')++ await jest.advanceTimersByTimeAsync(600)+ expect(emptyLogic.values.showEmptyState).toBe(true)++ // Well past the watchdog: it bounds a request in flight, and this one already+ // answered. "No results" must not decay into "couldn't load results".+ await jest.advanceTimersByTimeAsync(31000)+ expect(emptyLogic.values.showErrorState).toBe(false)+ expect(emptyLogic.values.showEmptyState).toBe(true)+ } finally {+ jest.useRealTimers()+ }+ })++ it('clears the error state when a retry succeeds', async () => {+ let attempts = 0+ useMocks({+ get: {+ '/api/projects/:team/event_definitions': () => {+ attempts += 1+ return attempts === 1+ ? [500, { detail: 'server error' }]+ : [200, { results: [{ name: 'user_signed_up', id: 'uuid-1' }], count: 1 }]+ },+ },+ })+ initKeaTests()+ const retryingLogic = infiniteListLogic({+ taxonomicFilterLogicKey: 'retryingList',+ listGroupType: TaxonomicFilterGroupType.Events,+ taxonomicGroupTypes: [TaxonomicFilterGroupType.Events],+ showNumericalPropsOnly: false,+ })+ retryingLogic.mount()+ await expectLogic(retryingLogic, () => {+ retryingLogic.actions.setSearchQuery('user_signed_up')+ })+ .toDispatchActions(['loadRemoteItemsFailure'])+ .toFinishAllListeners()+ .toMatchValues({ showErrorState: true })++ await expectLogic(retryingLogic, () => {+ retryingLogic.actions.retryRemoteItems()+ })+ .toDispatchActions(['retryRemoteItems', 'loadRemoteItems', 'loadRemoteItemsSuccess'])+ .toFinishAllListeners()+ .toMatchValues({+ showErrorState: false,+ showEmptyState: false,+ })+ expect(retryingLogic.values.totalResultCount).toBeGreaterThan(0)+ })})describe('SuggestedFilters aggregate holds the empty state until sibling groups settle', () => {diff --git a/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.ts b/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.tsindex ec7c87fd9519..d2a1c3dd4e9e 100644--- a/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.ts+++ b/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.ts@@ -16,7 +16,7 @@ import { loaders } from 'kea-loaders'import { combineUrl } from 'kea-router'import posthog from 'posthog-js'-import api from 'lib/api'+import api, { ApiMethodOptions } from 'lib/api'import { formatPropertyLabel } from 'lib/components/PropertyFilters/utils'import {expandRecentsForDisplay,@@ -202,6 +202,9 @@ const createEmptyListStorage = (searchQuery = '', first = false): ListStorage =>// simple cache with a setTimeout expiryconst API_CACHE_TIMEOUT = 60000+// Well under the gateway's own ceiling, so a wedged list request surfaces as a retryable error+// here rather than spinning until the proxy returns a 504.+const REMOTE_ITEMS_REQUEST_TIMEOUT_MS = 30000let apiCache: Record<string, ListStorage> = {}let apiCacheTimers: Record<string, number> = {}@@ -221,12 +224,16 @@ export function clearApiCache(): void {apiCacheTimers = {}}-async function fetchCachedListResponse(path: string, searchParams: Record<string, any>): Promise<ListStorage> {+async function fetchCachedListResponse(+ path: string,+ searchParams: Record<string, any>,+ options?: ApiMethodOptions+): Promise<ListStorage> {const url = combineUrl(path, searchParams).urlif (apiCache[url]) {return apiCache[url]}- const response = await api.get(url)+ const response = await api.get(url, options)// Never cache an empty response. A transient empty result (a backend blip, a race) would// otherwise be pinned for the full timeout, so an event that actually exists keeps reading as// "No results" for up to a minute — retrying the same query just re-reads the cached blank.@@ -323,6 +330,7 @@ export interface infiniteListLogicValues {value: TaxonomicFilterValue | undefined}showEmptyState: boolean+ showErrorState: booleanshowLoadingState: booleanshowNonCapturedEventOption: booleanshowPopover: boolean@@ -429,6 +437,9 @@ export interface infiniteListLogicActions {resetPinnedRowState: () => {value: true}+ retryRemoteItems: () => {+ value: true+ }selectSelected: () => {value: true}@@ -554,6 +565,12 @@ export interface infiniteListLogicMeta {anyGroupStale: boolean,searchQuery: string) => boolean+ showErrorState: (+ remoteFetchFailed: string | null,+ searchQuery: string,+ isLoading: boolean,+ totalListCount: number+ ) => booleanshowEmptyState: (totalListCount: number,isLoading: boolean,@@ -562,7 +579,8 @@ export interface infiniteListLogicMeta {hasRemoteDataSource: boolean,showNonCapturedEventOption: boolean,needsMoreSearchCharacters: boolean,- remoteResultsAreFresh: boolean+ remoteResultsAreFresh: boolean,+ showErrorState: boolean) => booleanshowLoadingState: (isLoading: boolean,@@ -845,6 +863,7 @@ export const infiniteListLogic = kea<infiniteListLogicType>([abortAnyRunningQuery: true,setHasMore: (hasMore: boolean) => ({ hasMore }),remoteItemsFetchFailedForQuery: (searchQuery: string) => ({ searchQuery }),+ retryRemoteItems: true,}),loaders(({ actions, values, cache, props }) => ({remoteItems: [@@ -903,17 +922,23 @@ export const infiniteListLogic = kea<infiniteListLogicType>([let response: anylet expandedCountResponse: any = null+ const runAbortController = cache.abortController+ const requestOptions = { signal: runAbortController?.signal }+try {// Querying groups from /groups/ endpoint may result in query timeouts. Let's query clickhouse insteadconst isGroupNamesFilter = values.listGroupType.startsWith(TaxonomicFilterGroupType.GroupNamesPrefix)if (isGroupNamesFilter && values.group?.groupTypeIndex !== undefined) {- const groupsResponse = await api.groups.listClickhouse({- group_type_index: values.group.groupTypeIndex as GroupTypeIndex,- search: searchQuery || '',- limit,- })+ const groupsResponse = await api.groups.listClickhouse(+ {+ group_type_index: values.group.groupTypeIndex as GroupTypeIndex,+ search: searchQuery || '',+ limit,+ },+ requestOptions+ )const transformedGroups = mapGroupQueryResponse(groupsResponse)response = {@@ -930,33 +955,61 @@ export const infiniteListLogic = kea<infiniteListLogicType>([// get the list of resultsfetchCachedListResponse(scopedRemoteEndpoint && !isExpanded ? scopedRemoteEndpoint : remoteEndpoint,- searchParams+ searchParams,+ requestOptions),// if this is an unexpanded scoped list, get the count for the full listscopedRemoteEndpoint && !isExpanded- ? fetchCachedListResponse(remoteEndpoint, {- ...searchParams,- limit: 1,- offset: 0,- })+ ? fetchCachedListResponse(+ remoteEndpoint,+ {+ ...searchParams,+ limit: 1,+ offset: 0,+ },+ requestOptions+ ): null,])response = apiResponseexpandedCountResponse = expandedApiResponse}} catch (error: any) {- if (!isBreakpoint(error)) {+ // An abort means either a newer query superseded this run, which owns the+ // outcome now, or the request timeout fired, which already recorded the+ // failure itself. Neither case belongs to this query.+ const aborted = error?.name === 'AbortError'+ if (aborted) {+ // A superseded run must not settle the loader. kea-loaders keeps one+ // loading flag per loader, so failing here would clear the flag the+ // newer run just set, and the SuggestedFilters reveal barrier opens on+ // `!anyGroupLoading` — it would drop its skeletons and reveal partial+ // results while that run is still in flight. This throws for a+ // superseded run and does nothing for the watchdog's own abort, which+ // does need to settle as a failure.+ breakpoint()+ }+ if (!isBreakpoint(error) && !aborted) {// Carry the query that was in flight when this run errored so the// reducer can attribute the failure to the right query string.actions.remoteItemsFetchFailedForQuery(searchQuery)}throw error+ } finally {+ // Disarm the watchdog now this run has settled. It only bounds a request+ // that is still in flight, and left armed it would fire against a finished+ // one and turn a legitimately empty result into an error 30s later. A newer+ // run owns the shared disposable, so leave that one alone or we abort its+ // request instead.+ if (cache.abortController === runAbortController) {+ cache.disposables.dispose('abortController')+ cache.abortController = null+ }}breakpoint()const queryChanged = values.remoteItems.searchQuery !== searchQueryconst existingResults = values.remoteItems.results- cache.abortController = nullreturn {results: appendAtIndex(@@ -1267,6 +1320,21 @@ export const infiniteListLogic = kea<infiniteListLogicType>([searchQuery: string): boolean => isSuggestedFilters && (anyGroupLoading || anyGroupStale) && searchQuery.trim().length > 0,],+ // A fetch that failed for the *current* query with nothing usable to fall back on. Kept+ // separate from `showEmptyState` so a timeout or a 5xx doesn't read as "this project has+ // no matching properties", which sends people looking for a tracking bug that isn't there.+ showErrorState: [+ (s) => [s.remoteFetchFailed, s.searchQuery, s.isLoading, s.totalListCount],+ (+ remoteFetchFailed: string | null,+ searchQuery: string,+ isLoading: boolean,+ totalListCount: number+ ): boolean =>+ // Compare the exact query for the same reason `remoteResultsAreFresh` does: a stale+ // failure from a superseded run must not surface against a newer query.+ remoteFetchFailed === searchQuery && !isLoading && totalListCount === 0,+ ],showEmptyState: [(s) => [s.totalListCount,@@ -1277,6 +1345,7 @@ export const infiniteListLogic = kea<infiniteListLogicType>([s.showNonCapturedEventOption,s.needsMoreSearchCharacters,s.remoteResultsAreFresh,+ s.showErrorState,],(totalListCount: number,@@ -1286,10 +1355,12 @@ export const infiniteListLogic = kea<infiniteListLogicType>([hasRemoteDataSource: boolean,showNonCapturedEventOption: boolean,needsMoreSearchCharacters: boolean,- remoteResultsAreFresh: boolean+ remoteResultsAreFresh: boolean,+ showErrorState: boolean): boolean =>(totalListCount === 0 &&!isLoading &&+ !showErrorState &&// Don't declare "No results" until the fetch for the *current* query has landed —// otherwise a stale/empty list from the previous query masquerades as no matches.remoteResultsAreFresh &&@@ -2234,9 +2305,24 @@ export const infiniteListLogic = kea<infiniteListLogicType>([const abortController = new AbortController()// Store reference in cache for the fetch operation to usecache.abortController = abortController- return () => abortController.abort()+ // Some of these list endpoints have no server-side statement timeout, so a query+ // that wedges only fails when the gateway gives up two minutes later. Giving up+ // first bounds how long the list can sit in its loading state. The failure is+ // recorded here rather than in the loader's catch, because the catch cannot tell+ // this abort apart from the one a newer query triggers.+ const timeoutId = window.setTimeout(() => {+ actions.remoteItemsFetchFailedForQuery(values.searchQuery)+ abortController.abort()+ }, REMOTE_ITEMS_REQUEST_TIMEOUT_MS)+ return () => {+ window.clearTimeout(timeoutId)+ abortController.abort()+ }}, 'abortController')},+ retryRemoteItems: () => {+ actions.loadRemoteItems({ offset: 0, limit: values.limit })+ },})),events(({ actions, values, props, cache }) => ({afterMount: () => {