: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
chore(frontend): share the abort-resilient loading reducer across products (#92016)
Jimmy Zhu6f2026dc0d7d
diff --git a/frontend/src/lib/utils/kea-logic-builders.ts b/frontend/src/lib/utils/kea-logic-builders.tsindex b64433306660..0f0d742ed2be 100644--- a/frontend/src/lib/utils/kea-logic-builders.ts+++ b/frontend/src/lib/utils/kea-logic-builders.ts@@ -13,3 +13,39 @@ export function permanentlyMount(): (logic: BuiltLogic) => void {})(logic)}}++// Abort reasons for requests a logic cancels on purpose, passed as the message of an+// AbortError-named DOMException so api.ts recognizes the cancellation. kea-loaders reduces a+// rejection to its message, so failure reducers and listeners see only this text.+export const NEW_QUERY_STARTED_ERROR_MESSAGE = 'new query started' as const+export const UNMOUNTING_ERROR_MESSAGE = 'unmounting component' as const++// Neither of our abort reasons contains "abort", so both need matching by name: an unmatched+// one is treated as a genuine failure, which toasts the user, fires a query-failed capture,+// or drops a loading flag for a request that was cancelled on purpose.+export function isUserInitiatedError(error: unknown): boolean {+ const errorStr = String(error).toLowerCase()+ return error === NEW_QUERY_STARTED_ERROR_MESSAGE || error === UNMOUNTING_ERROR_MESSAGE || errorStr.includes('abort')+}++type LoadingHandlers = Record<string, (state: boolean, payload: { error: string }) => boolean>++/**+ * Handlers for a loading flag whose in-flight request can be aborted by a superseding call.+ *+ * kea-loaders' auto `<key>Loading` drops to false when the aborted request's rejection lands+ * as a failure, even though the superseding call is still in flight, so the UI flashes its+ * empty state between the spinner and the data. These handlers ride out user-initiated aborts+ * and only clear on success or a real failure. Pass every loader action that should drive+ * the flag (e.g. a first-page and a next-page fetch), and keep the reducer's `[false as+ * boolean, ...]` default inline, where kea-typegen can read it.+ */+export function abortResilientLoading(...loaderActions: string[]): LoadingHandlers {+ const handlers: LoadingHandlers = {}+ for (const action of loaderActions) {+ handlers[action] = () => true+ handlers[`${action}Success`] = () => false+ handlers[`${action}Failure`] = (state, { error }) => (isUserInitiatedError(error) ? state : false)+ }+ return handlers+}diff --git a/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.ts b/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.tsindex a4c30fa0e8ca..87d43077fad1 100644--- a/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.ts+++ b/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.ts@@ -23,6 +23,11 @@ import { lemonToast } from '@posthog/lemon-ui'import api from 'lib/api'import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'import { dayjs } from 'lib/dayjs'+import {+ NEW_QUERY_STARTED_ERROR_MESSAGE,+ UNMOUNTING_ERROR_MESSAGE,+ isUserInitiatedError,+} from 'lib/utils/kea-logic-builders'import { teamLogic } from 'scenes/teamLogic'import { LogMessage, LogsQuery, ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'@@ -47,8 +52,6 @@ import type { LogsColumnConfig } from '../config/columns'const DEFAULT_LIVE_TAIL_POLL_INTERVAL_MS = 1000const DEFAULT_LOGS_PAGE_SIZE: number = 250export const DEFAULT_INITIAL_LOGS_LIMIT = null as number | null-const NEW_QUERY_STARTED_ERROR_MESSAGE = 'new query started' as const-const UNMOUNTING_ERROR_MESSAGE = 'unmounting component' as const// Parse cache keyed on log object identity — leak-free by construction (entries die with their// logs) and shared across logic instances. Parsing is pure per object, so cached entries are@@ -80,15 +83,6 @@ function classifyQueryError(error: unknown): { error_type: string; status_code:return { error_type: 'unknown', status_code: statusCode }}-// kea-loaders reduces a rejection to its message, so an aborted request arrives here as the reason-// text we passed to `abort()`. Neither of our reasons contains "abort", so both need matching by-// name: an unmatched one is treated as a genuine failure, which toasts the user and fires a-// `logs query failed` capture for a request that was cancelled on purpose.-function isUserInitiatedError(error: unknown): boolean {- const errorStr = String(error).toLowerCase()- return error === NEW_QUERY_STARTED_ERROR_MESSAGE || error === UNMOUNTING_ERROR_MESSAGE || errorStr.includes('abort')-}-const stringifyLogAttributes = (attributes: Record<string, any>): Record<string, string> => {const result: Record<string, string> = {}for (const attributeKey of Object.keys(attributes)) {diff --git a/products/metrics/frontend/components/metricsUsageTrackingLogic.test.ts b/products/metrics/frontend/components/metricsUsageTrackingLogic.test.tsindex cd5e29a32c71..24de2717a7ca 100644--- a/products/metrics/frontend/components/metricsUsageTrackingLogic.test.ts+++ b/products/metrics/frontend/components/metricsUsageTrackingLogic.test.ts@@ -2,6 +2,7 @@ import { router } from 'kea-router'import { expectLogic } from 'kea-test-utils'import posthog from 'posthog-js'+import { NEW_QUERY_STARTED_ERROR_MESSAGE } from 'lib/utils/kea-logic-builders'import { teamLogic } from 'scenes/teamLogic'import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'@@ -19,7 +20,7 @@ import { metricsSceneLogic } from '../metricsSceneLogic'import { metricNamePickerLogic } from './metricNamePickerLogic'import { metricsSamplesLogic } from './metricsSamplesLogic'import { metricsUsageTrackingLogic } from './metricsUsageTrackingLogic'-import { metricsViewerLogic, NEW_QUERY_STARTED_ERROR_MESSAGE } from './metricsViewerLogic'+import { metricsViewerLogic } from './metricsViewerLogic'jest.mock('posthog-js')diff --git a/products/metrics/frontend/components/metricsUsageTrackingLogic.ts b/products/metrics/frontend/components/metricsUsageTrackingLogic.tsindex c8e6e5bcb2a8..c668e9bfdc88 100644--- a/products/metrics/frontend/components/metricsUsageTrackingLogic.ts+++ b/products/metrics/frontend/components/metricsUsageTrackingLogic.ts@@ -1,6 +1,7 @@import { MakeLogicType, actions, connect, kea, listeners, path } from 'kea'import posthog from 'posthog-js'+import { isUserInitiatedError } from 'lib/utils/kea-logic-builders'import { teamLogic } from 'scenes/teamLogic'import { type MetricsQuery, ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'@@ -15,7 +16,7 @@ import { metricsSceneLogic } from '../metricsSceneLogic'import type { MetricsSceneActiveTab } from '../metricsSceneLogic'import { metricsSamplesLogic } from './metricsSamplesLogic'import type { MetricsPanelTab } from './metricsSamplesLogic'-import { isUserInitiatedError, metricsViewerLogic } from './metricsViewerLogic'+import { metricsViewerLogic } from './metricsViewerLogic'import type { MetricAggregation } from './metricsViewerLogic'// Generated by kea-typegen. Update if you're an agent, ignore if you're human.diff --git a/products/metrics/frontend/components/metricsViewerLogic.test.ts b/products/metrics/frontend/components/metricsViewerLogic.test.tsindex fb9ec154c923..3ff5c9a7be84 100644--- a/products/metrics/frontend/components/metricsViewerLogic.test.ts+++ b/products/metrics/frontend/components/metricsViewerLogic.test.ts@@ -1,5 +1,6 @@import { expectLogic } from 'kea-test-utils'+import { NEW_QUERY_STARTED_ERROR_MESSAGE } from 'lib/utils/kea-logic-builders'import { insightsApi } from 'scenes/insights/utils/api'import { NodeKind } from '~/queries/schema/schema-general'@@ -22,7 +23,7 @@ import {} from 'products/metrics/frontend/generated/api'import { metricNamePickerLogic } from './metricNamePickerLogic'-import { metricsViewerLogic, NEW_QUERY_STARTED_ERROR_MESSAGE } from './metricsViewerLogic'+import { metricsViewerLogic } from './metricsViewerLogic'jest.mock('products/metrics/frontend/generated/api', () => ({...jest.requireActual('products/metrics/frontend/generated/api'),diff --git a/products/metrics/frontend/components/metricsViewerLogic.tsx b/products/metrics/frontend/components/metricsViewerLogic.tsxindex fe2d537d5df5..75162ead0182 100644--- a/products/metrics/frontend/components/metricsViewerLogic.tsx+++ b/products/metrics/frontend/components/metricsViewerLogic.tsx@@ -9,6 +9,11 @@ import { isUniversalGroupFilterLike } from 'lib/components/UniversalFilters/utilimport { dayjs } from 'lib/dayjs'import { escapeRegex } from 'lib/utils/actions'import { dateStringToDayJs } from 'lib/utils/dateFilters'+import {+ NEW_QUERY_STARTED_ERROR_MESSAGE,+ abortResilientLoading,+ isUserInitiatedError,+} from 'lib/utils/kea-logic-builders'import { objectsEqual } from 'lib/utils/objects'import { insightsApi } from 'scenes/insights/utils/api'import { teamLogic } from 'scenes/teamLogic'@@ -89,15 +94,6 @@ export const RECOMMENDED_AGGREGATION_BY_TYPE: Record<string, MetricAggregation>export const DEFAULT_DATE_FROM = '-1h'// Kept off the persisted node: a saved query with no `display` renders as a line chart anyway.export const DEFAULT_DISPLAY_TYPE: MetricsDisplayType = 'line'-export const NEW_QUERY_STARTED_ERROR_MESSAGE = 'A new metrics query started, canceling the previous one'--// A superseded or unmounted request rejects with an abort, not a real failure — never surface it as an error.-// The cancel path aborts with NEW_QUERY_STARTED_ERROR_MESSAGE, whose text doesn't contain "abort", so match it-// explicitly alongside the generic abort check (mirrors logsViewerDataLogic's isUserInitiatedError).-export const isUserInitiatedError = (error: unknown): boolean => {- const errorStr = String(error).toLowerCase()- return error === NEW_QUERY_STARTED_ERROR_MESSAGE || errorStr.includes('abort')-}// The anomaly badge characterizes the most recent slice of the selected window against the rest.const ANOMALY_WINDOW_FRACTION = 0.2export const LIVE_REFRESH_MS = 15_000@@ -594,18 +590,9 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([isUserInitiatedError(error) ? state : error || 'Something went wrong running this query.',},],- // kea-loaders' auto `queryResultsLoading` drops to false when a superseded query's- // abort lands as a failure, flashing the empty state while the replacement query is- // still in flight. This flag only clears on success or a real failure, so the UI- // must read it instead of `queryResultsLoading`.- queryLoading: [- false as boolean,- {- fetchQueryResults: () => true,- fetchQueryResultsSuccess: () => false,- fetchQueryResultsFailure: (state, { error }) => (isUserInitiatedError(error) ? state : false),- },- ],+ // Rides out superseded-query aborts, so the UI must read it instead of the auto+ // `queryResultsLoading`, which drops mid-refetch and flashes the empty state.+ queryLoading: [false as boolean, abortResilientLoading('fetchQueryResults')],}),listeners(({ actions, values, cache }) => ({// Narrows the metric picker to the filtered services, so it offers only thediff --git a/products/tracing/frontend/tracingDataLogic.test.ts b/products/tracing/frontend/tracingDataLogic.test.tsindex f284f82ef572..596bbcd1da1b 100644--- a/products/tracing/frontend/tracingDataLogic.test.ts+++ b/products/tracing/frontend/tracingDataLogic.test.ts@@ -4,12 +4,13 @@ import posthog from 'posthog-js'import { lemonToast } from '@posthog/lemon-ui'import api from 'lib/api'+import { NEW_QUERY_STARTED_ERROR_MESSAGE, UNMOUNTING_ERROR_MESSAGE } from 'lib/utils/kea-logic-builders'import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'import { AggregatedSpanRow } from '~/queries/schema/schema-general'import { initKeaTests } from '~/test/init'-import { NEW_QUERY_STARTED_ERROR_MESSAGE, UNMOUNTING_ERROR_MESSAGE, tracingDataLogic } from './tracingDataLogic'+import { tracingDataLogic } from './tracingDataLogic'import { tracingFiltersLogic } from './tracingFiltersLogic'import type { Span } from './types'diff --git a/products/tracing/frontend/tracingDataLogic.ts b/products/tracing/frontend/tracingDataLogic.tsindex 52175f0f5590..a50e56b56c99 100644--- a/products/tracing/frontend/tracingDataLogic.ts+++ b/products/tracing/frontend/tracingDataLogic.ts@@ -23,6 +23,12 @@ import { FEATURE_FLAGS } from 'lib/constants'import { dayjs } from 'lib/dayjs'import { featureFlagLogic, type FeatureFlagsSet } from 'lib/logic/featureFlagLogic'import { humanFriendlyDetailedTime } from 'lib/utils/datetime'+import {+ NEW_QUERY_STARTED_ERROR_MESSAGE,+ UNMOUNTING_ERROR_MESSAGE,+ abortResilientLoading,+ isUserInitiatedError,+} from 'lib/utils/kea-logic-builders'import { AggregatedSpanRow, SpanTreeNode } from '~/queries/schema/schema-general'import { PropertyGroupFilter } from '~/types'@@ -78,17 +84,6 @@ const DEFAULT_PAGE_SIZE = 100// the full set for client-side sort/filter, unlike the smaller default the endpoint serves agents.const OPERATIONS_AGGREGATION_LIMIT = 5000export const PREFETCH_SPANS = 20-export const NEW_QUERY_STARTED_ERROR_MESSAGE = 'new query started' as const-export const UNMOUNTING_ERROR_MESSAGE = 'unmounting component' as const--// kea-loaders reduces a rejection to its message, so an aborted request arrives here as the reason-// text we passed to `abort()`. Neither of our reasons contains "abort", so both need matching by-// name: an unmatched one is treated as a genuine failure, which toasts the user and fires a-// `tracing query failed` capture for a request that was cancelled on purpose.-export function isUserInitiatedError(error: unknown): boolean {- const errorStr = String(error).toLowerCase()- return error === NEW_QUERY_STARTED_ERROR_MESSAGE || error === UNMOUNTING_ERROR_MESSAGE || errorStr.includes('abort')-}// A ts hint (from a shared/cold link) bounds the lookup tightly around the trace instead of the// scene's current date range — the table is time-keyed, so this is what keeps an id lookup from@@ -766,19 +761,9 @@ export const tracingDataLogic = kea<tracingDataLogicType>([fetchSpansFailure: () => true,},],- spansLoading: [- false as boolean,- {- fetchSpans: () => true,- fetchSpansSuccess: () => false,- // A superseded query is aborted by the newer one that already re-set loading true;- // keep loading so the list holds its spinner instead of flashing "No spans found".- fetchSpansFailure: (state, { error }) => (isUserInitiatedError(error) ? state : false),- fetchNextPage: () => true,- fetchNextPageSuccess: () => false,- fetchNextPageFailure: (state, { error }) => (isUserInitiatedError(error) ? state : false),- },- ],+ // A superseded query is aborted by the newer one that already re-set loading true;+ // keep loading so the list holds its spinner instead of flashing "No spans found".+ spansLoading: [false as boolean, abortResilientLoading('fetchSpans', 'fetchNextPage')],sparklineLoading: [false as boolean,{@@ -803,14 +788,7 @@ export const tracingDataLogic = kea<tracingDataLogicType>([fetchLatencyHeatmapFailure: () => false,},],- aggregationLoading: [- false as boolean,- {- fetchAggregation: () => true,- fetchAggregationSuccess: () => false,- fetchAggregationFailure: (state, { error }) => (isUserInitiatedError(error) ? state : false),- },- ],+ aggregationLoading: [false as boolean, abortResilientLoading('fetchAggregation')],spanTreeLoading: [false as boolean,{diff --git a/products/tracing/frontend/tracingOperationSceneLogic.ts b/products/tracing/frontend/tracingOperationSceneLogic.tsindex 5e109a980fd6..84f94d3f8937 100644--- a/products/tracing/frontend/tracingOperationSceneLogic.ts+++ b/products/tracing/frontend/tracingOperationSceneLogic.ts@@ -8,6 +8,7 @@ import api from 'lib/api'import { dataColorVars } from 'lib/colors'import { FEATURE_FLAGS } from 'lib/constants'import { featureFlagLogic, type FeatureFlagsSet } from 'lib/logic/featureFlagLogic'+import { NEW_QUERY_STARTED_ERROR_MESSAGE, isUserInitiatedError } from 'lib/utils/kea-logic-builders'import { objectsEqual } from 'lib/utils/objects'import { AggregatedSpanRow, DateRange } from '~/queries/schema/schema-general'@@ -24,7 +25,6 @@ import {import type { HeatmapBrushSelection } from './heatmapBrush'import { type DurationRange, operationFilterGroup } from './operationFilters'import { traceLookupDateRange } from './traceLinks'-import { isUserInitiatedError, NEW_QUERY_STARTED_ERROR_MESSAGE } from './tracingDataLogic'import { DEFAULT_DATE_RANGE } from './tracingFiltersLogic'import type { Span } from './types'