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(experiments): stop background tabs from burning the query poll deadline (#76496)

posthog[bot]16cff31ca856
diff --git a/frontend/src/queries/query.test.ts b/frontend/src/queries/query.test.ts
index cc9633ec3d66..e309aab77d1e 100644
--- a/frontend/src/queries/query.test.ts
+++ b/frontend/src/queries/query.test.ts
@@ -233,6 +233,41 @@ describe('query', () => {
})
})
+ describe('pollForResults and backgrounded tabs', () => {
+ const originalVisibilityState = document.visibilityState
+
+ afterEach(() => {
+ Object.defineProperty(document, 'visibilityState', { value: originalVisibilityState, configurable: true })
+ jest.restoreAllMocks()
+ })
+
+ it('does not count time spent hidden against the poll deadline', async () => {
+ Object.defineProperty(document, 'visibilityState', { value: 'visible', configurable: true })
+
+ let now = 0
+ jest.spyOn(performance, 'now').mockImplementation(() => now)
+
+ jest.spyOn(api.queryStatus, 'get')
+ .mockResolvedValueOnce({ query_status: { complete: false } } as any)
+ .mockResolvedValueOnce({ query_status: { complete: true, results: ['ok'] } } as any)
+
+ const promise = pollForResults('test-query-id', undefined, () => {
+ // Fires right after the first (incomplete) poll, before the loop rechecks its
+ // deadline for the next one. Simulate the tab backgrounding for longer than the
+ // whole poll deadline (10m6s) right here: a wall-clock deadline would time out on
+ // the very next check, even though no polling actually happened during that time.
+ Object.defineProperty(document, 'visibilityState', { value: 'hidden', configurable: true })
+ now += 11 * 60 * 1000
+ setTimeout(() => {
+ Object.defineProperty(document, 'visibilityState', { value: 'visible', configurable: true })
+ document.dispatchEvent(new Event('visibilitychange'))
+ }, 0)
+ })
+
+ await expect(promise).resolves.toMatchObject({ complete: true, results: ['ok'] })
+ })
+ })
+
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.ts
index 756c2e771d54..ffb54ce851e6 100644
--- a/frontend/src/queries/query.ts
+++ b/frontend/src/queries/query.ts
@@ -116,13 +116,18 @@ export async function pollForResults(
methodOptions?: ApiMethodOptions,
onPoll?: (response: QueryStatus) => void
): Promise<QueryStatus> {
- const pollStart = performance.now()
+ // Measured only across time spent actually polling (page visible), not raw wall-clock time -
+ // otherwise a backgrounded tab burns down the deadline via waitForPageVisible below without
+ // ever getting a chance to poll, and the query "times out" despite never really being tried.
+ let activeElapsedMs = 0
let currentDelay = 300 // start low, because all queries will take at minimum this
- while (performance.now() - pollStart < QUERY_ASYNC_TOTAL_POLL_SECONDS * 1000) {
+ while (activeElapsedMs < QUERY_ASYNC_TOTAL_POLL_SECONDS * 1000) {
await waitForPageVisible(methodOptions?.signal)
+ const iterationStart = performance.now()
await delay(currentDelay, methodOptions?.signal)
currentDelay = Math.min(currentDelay * 1.25, QUERY_ASYNC_MAX_INTERVAL_SECONDS * 1000)
+ activeElapsedMs += performance.now() - iterationStart
try {
const statusResponse = (await api.queryStatus.get(queryId, true)).query_status
diff --git a/frontend/src/scenes/experiments/ExperimentView/Exposures.tsx b/frontend/src/scenes/experiments/ExperimentView/Exposures.tsx
index f0e336dc6ea8..4e1acd5bb3c9 100644
--- a/frontend/src/scenes/experiments/ExperimentView/Exposures.tsx
+++ b/frontend/src/scenes/experiments/ExperimentView/Exposures.tsx
@@ -1,5 +1,5 @@
import { useActions, useValues } from 'kea'
-import { useCallback, useMemo, useState } from 'react'
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { IconCheckCircle, IconCorrelationAnalysis, IconInfo, IconPencil, IconWarning } from '@posthog/icons'
import { LemonButton, LemonCollapse, LemonTable, LemonTag, Spinner, Tooltip } from '@posthog/lemon-ui'
@@ -28,6 +28,32 @@ import { VariantTag } from './VariantTag'
const srmFailureTooltipText =
"The distribution of users across variants doesn't match your configured rollout percentages (p < 0.001). This may indicate issues with randomization or data collection."
+// Below this, a load looks like any other; above it, the user has no way to tell a slow query
+// from a stuck one, so we start showing elapsed time and a way to retry.
+const SLOW_LOAD_THRESHOLD_SECONDS = 20
+
+/** Seconds since `active` last became true, ticking every second, reset to 0 when it goes false. */
+function useElapsedSeconds(active: boolean): number {
+ const [elapsed, setElapsed] = useState(0)
+ const startRef = useRef<number | null>(null)
+
+ useEffect(() => {
+ if (!active) {
+ startRef.current = null
+ setElapsed(0)
+ return
+ }
+ startRef.current = performance.now()
+ setElapsed(0)
+ const intervalId = setInterval(() => {
+ setElapsed(Math.floor((performance.now() - (startRef.current as number)) / 1000))
+ }, 1000)
+ return () => clearInterval(intervalId)
+ }, [active])
+
+ return elapsed
+}
+
interface MicroChartProps {
exposures: ExperimentExposureQueryResponse
}
@@ -102,8 +128,11 @@ export function Exposures(): JSX.Element {
resolvedExposureEvent,
} = useValues(experimentLogic)
const { openExposureCriteriaModal } = useActions(exposureCriteriaModalLogic)
+ const { refreshExperimentResults } = useActions(experimentLogic)
const [isCollapsed, setIsCollapsed] = useState(true)
+ const exposuresElapsedSeconds = useElapsedSeconds(exposuresLoading)
+ const exposuresLoadingSlowly = exposuresLoading && exposuresElapsedSeconds >= SLOW_LOAD_THRESHOLD_SECONDS
let totalExposures = 0
const variants: Array<{ variant: string; count: number; percentage: number }> = []
@@ -163,7 +192,14 @@ export function Exposures(): JSX.Element {
}`}
>
{exposuresLoading ? (
- <Spinner className="text-lg" />
+ <div className="flex items-center gap-2">
+ <Spinner className="text-lg" />
+ {exposuresLoadingSlowly && (
+ <span className="text-secondary text-xs">
+ Still loading ({exposuresElapsedSeconds}s)
+ </span>
+ )}
+ </div>
) : (
<>
<span>
@@ -228,8 +264,22 @@ export function Exposures(): JSX.Element {
<div className="space-y-4 bg-bg-light -m-4 p-4">
{/* Chart Section */}
{exposuresLoading ? (
- <div className="relative border rounded h-[200px] flex justify-center items-center">
+ <div className="relative border rounded h-[200px] flex flex-col gap-3 justify-center items-center">
<Spinner className="text-5xl" />
+ {exposuresLoadingSlowly && (
+ <div className="flex flex-col items-center gap-2">
+ <span className="text-secondary text-sm">
+ Still loading exposures after {exposuresElapsedSeconds}s
+ </span>
+ <LemonButton
+ type="secondary"
+ size="small"
+ onClick={() => refreshExperimentResults(true, 'manual')}
+ >
+ Retry
+ </LemonButton>
+ </div>
+ )}
</div>
) : !exposures?.timeseries?.length ? (
<div className="relative border rounded h-[200px] flex justify-center items-center">