: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(experiments): keep polling a recalc run that waits in a queue (#128325)
Rodrigo Iloro6310b87d101d
diff --git a/frontend/src/scenes/experiments/experimentMetricsLogic.test.ts b/frontend/src/scenes/experiments/experimentMetricsLogic.test.tsindex b86b866fb449..20d50884002b 100644--- a/frontend/src/scenes/experiments/experimentMetricsLogic.test.ts+++ b/frontend/src/scenes/experiments/experimentMetricsLogic.test.ts@@ -589,9 +589,9 @@ describe('experimentMetricsLogic', () => {jest.useRealTimers()})- it('stops polling a run older than the staleness window instead of polling it forever', async () => {+ it('stops polling a run older than the queued-run ceiling instead of polling it forever', async () => {// A worker that dies mid-run leaves the row in_progress permanently; the poll loop must give up- // once the run passes the backend's staleness threshold rather than hitting the by-id endpoint+ // once the run passes the backend's 1-hour ceiling rather than hitting the by-id endpoint// (and its live-progress query) every tick until the tab closes.const retrieveMock = jest.fn(() => [200, { ...pendingRecalculation, status: 'in_progress' }])useMocks({@@ -610,7 +610,7 @@ describe('experimentMetricsLogic', () => {expect(retrieveMock).toHaveBeenCalled()// Age the run past the cap: polling must stop and the in-flight tags must clear.- logic.cache.recalcStartMs = Date.now() - 31 * 60 * 1000+ logic.cache.recalcStartMs = Date.now() - 61 * 60 * 1000await jest.advanceTimersByTimeAsync(POLL_INTERVAL_MS)retrieveMock.mockClear()await jest.advanceTimersByTimeAsync(POLL_INTERVAL_MS * 5)@@ -622,6 +622,47 @@ describe('experimentMetricsLogic', () => {jest.useRealTimers()})+ it.each([+ // A page reload while the run waits in a queue: the server still reports it as the active run.+ ['reloaded while queued', 40],+ // A tab that stays open while the run crosses the backend's 30-minute staleness threshold.+ ['open across the staleness threshold', 29],+ ])('keeps polling a run that waits past 30 minutes until it completes (%s)', async (_, ageMinutes) => {+ jest.useFakeTimers()+ const startedAt = new Date(Date.now() - ageMinutes * 60 * 1000).toISOString()+ const queuedRun = { ...inProgressRecalculation, created_at: startedAt, started_at: startedAt }+ let completed = false+ const retrieveMock = jest.fn(() => [200, completed ? completedRecalculation2 : queuedRun])+ const createMock = jest.fn(() => [201, { ...manualPending, id: 'recalc-3' }])+ useMocks({+ get: {+ '/api/projects/:team_id/experiments/:id/metrics_recalculation/latest/': () => [+ 200,+ { ...completedRecalculation, active_run: { id: 'recalc-2', status: 'in_progress' } },+ ],+ '/api/projects/:team_id/experiments/:id/metrics_recalculation/:recalc_id/': retrieveMock,+ },+ post: { '/api/projects/:team_id/experiments/:id/metrics_recalculation/': createMock },+ })+ mountLogic()+ await expectLogic(logic).toDispatchActions(['loadLatestRecalculation', 'pollRecalculation'])+ logic.actions.setQueuedRerun('manual')++ // Wait 20 minutes in the queue: the run passes 30 minutes, polling backs off and does not give up.+ await jest.advanceTimersByTimeAsync(20 * 60 * 1000)+ expect(logic.values.currentRecalculation?.status).toBe('in_progress')+ expect(logic.values.isRecalculating).toBe(true)+ expect(logic.values.queuedRerun).toBe('manual')+ expect(retrieveMock.mock.calls.length).toBeLessThan(120)++ completed = true+ await jest.advanceTimersByTimeAsync(60 * 1000)+ expect(logic.values.primaryMetricsResults[0]).toEqual(primaryResult)+ // The rerun queued during the wait fires once the run ends.+ expect(createMock).toHaveBeenCalledTimes(1)+ jest.useRealTimers()+ })+it('does not auto-trigger when the latest completed run is healthy', async () => {// freshCompletedRecalculation has result_source 'recalculation' (a real run) with all metrics// resolved, so neither the config-change heal path nor the timeseries-fallback path fires.diff --git a/frontend/src/scenes/experiments/experimentMetricsLogic.ts b/frontend/src/scenes/experiments/experimentMetricsLogic.tsindex 17abd7247478..33d0231ea3e1 100644--- a/frontend/src/scenes/experiments/experimentMetricsLogic.ts+++ b/frontend/src/scenes/experiments/experimentMetricsLogic.ts@@ -73,13 +73,16 @@ export interface ExperimentMetricsLogicProps {// minutes a dashboard waits between bulk refreshes. The backend applies the same window and returns that run.const MIN_MANUAL_REFRESH_INTERVAL_MINUTES = 5const RECALCULATION_POLL_INTERVAL_MS = 2000+/** A run past the backend's 30-minute staleness threshold is usually waiting for a slot in a capped queue. */+const QUEUED_RUN_AGE_MS = 30 * 60 * 1000+const QUEUED_RUN_POLL_INTERVAL_MS = 60 * 1000const MAX_POLL_RETRIES = 5/**- * Mirrors the backend's 30-minute staleness threshold (_STALE_RECALC_THRESHOLD): a run still non-terminal- * past it is a zombie whose worker died, and the backend will force-fail it on the next trigger. Without- * this cap every tab that resumed the run would poll its id (and the per-tick live-progress query) forever.+ * Mirrors the backend's 1-hour ceiling (_QUEUED_RECALC_CEILING): a run still non-terminal past it is treated+ * as dead, and the backend fails it on the next trigger. Without this cap every tab that resumed the run would+ * poll its id (and the per-tick live-progress query) forever.*/-const MAX_POLL_DURATION_MS = 30 * 60 * 1000+const MAX_POLL_DURATION_MS = 60 * 60 * 1000// A request that never settles neither resolves nor rejects, so without a deadline the page loads forever.const LATEST_REQUEST_TIMEOUT_MS = 30 * 1000const POLL_REQUEST_TIMEOUT_MS = 15 * 1000@@ -91,6 +94,10 @@ const STALE_REFRESH_STATUSES: ReadonlySet<ExperimentStatus> = new Set([ExperimentStatus.ExposureFrozen,])+function pollIntervalMs(runAgeMs: number): number {+ return runAgeMs > QUEUED_RUN_AGE_MS ? QUEUED_RUN_POLL_INTERVAL_MS : RECALCULATION_POLL_INTERVAL_MS+}+class RecalculationRequestTimeoutError extends Error {}/**@@ -1075,13 +1082,14 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([* stop polling, and clear recalculation state. This includes any queued rerun, that will never* be fired.*/- if (Date.now() - (cache.recalcStartMs ?? Date.now()) > MAX_POLL_DURATION_MS) {+ const runAgeMs = Date.now() - (cache.recalcStartMs ?? Date.now())+ if (runAgeMs > MAX_POLL_DURATION_MS) {actions.abandonRecalculation('poll_duration_cap', recalculationId)return}// Pace this tick; aborts here if a newer poll superseded us or the logic unmounted.- await breakpoint(RECALCULATION_POLL_INTERVAL_MS)+ await breakpoint(pollIntervalMs(runAgeMs))let recalculation: ExperimentMetricsRecalculationRunApitry {