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): receiving fewer metrics on latest now starts a recalcualtion (#95361)

Rodrigo Iloroa7bb530733c8
diff --git a/frontend/src/scenes/experiments/experimentLogic.test.ts b/frontend/src/scenes/experiments/experimentLogic.test.ts
index 9bc78a898fc0..35a3fb1a1e98 100644
--- a/frontend/src/scenes/experiments/experimentLogic.test.ts
+++ b/frontend/src/scenes/experiments/experimentLogic.test.ts
@@ -352,6 +352,37 @@ describe('experimentLogic', () => {
])
.toFinishAllListeners()
})
+
+ it('addSharedMetricsToExperiment reuses the window (metric_config_change)', async () => {
+ // A keyed logic with a real experiment id so loadExperiment returns the launched experiment
+ // (the default unkeyed logic resolves experimentId to "new" and loads a draft). Mock every
+ // endpoint the follow-up refresh touches so its async work settles before unmount.
+ useMocks({
+ get: { '/api/projects/:team/experiments/:id': experiment },
+ post: {
+ '/api/environments/:team/query': () => [
+ 200,
+ { cache_key: 'cache_key', query_status: experimentMetricResultsSuccessJson.query_status },
+ ],
+ },
+ })
+ jest.spyOn(api, 'update').mockResolvedValue(experiment)
+ const keyed = experimentLogic({ experimentId: experiment.id })
+ keyed.mount()
+ keyed.actions.setExperiment(experiment)
+
+ await expectLogic(keyed, () => {
+ keyed.actions.addSharedMetricsToExperiment([1], { type: 'primary' })
+ })
+ .toDispatchActions([
+ (action) =>
+ action.type === keyed.actionTypes.refreshExperimentResults &&
+ action.payload.triggeredBy === 'metric_config_change',
+ ])
+ .toFinishAllListeners()
+
+ keyed.unmount()
+ })
})
describe('currentRefresh tracking', () => {
diff --git a/frontend/src/scenes/experiments/experimentMetricsLogic.test.ts b/frontend/src/scenes/experiments/experimentMetricsLogic.test.ts
index f25eda069bb4..3578cc896f52 100644
--- a/frontend/src/scenes/experiments/experimentMetricsLogic.test.ts
+++ b/frontend/src/scenes/experiments/experimentMetricsLogic.test.ts
@@ -381,6 +381,39 @@ describe('experimentMetricsLogic', () => {
expect(capturedBody).toEqual({ trigger: 'cold_run' })
})
+ it('heals a completed run that is missing a metric added after it finished', async () => {
+ // A metric added after the last run finished is absent from that run's results. The run's own
+ // counts look complete, so only a uuid comparison catches the gap; without the heal the new metric
+ // stays stuck loading on every page load.
+ // Derive the extra metric from a real fixture metric so it stays fully typed; only the uuid differs.
+ const addedMetric = { ...EXPERIMENT.metrics[0], uuid: 'added-after-run-uuid' }
+ const experimentWithExtraMetric: Experiment = {
+ ...EXPERIMENT,
+ metrics: [...EXPERIMENT.metrics, addedMetric],
+ }
+ let capturedBody: any
+ useMocks({
+ get: {
+ // Completed run that covers only the two original metrics, not the newly added one.
+ '/api/projects/:team_id/experiments/:id/metrics_recalculation/latest/': () => [
+ 200,
+ completedRecalculation,
+ ],
+ },
+ post: {
+ '/api/projects/:team_id/experiments/:id/metrics_recalculation/': async ({ request }) => {
+ capturedBody = await request.json()
+ return [201, completedRecalculation2]
+ },
+ },
+ })
+ logic = experimentMetricsLogic({ experiment: experimentWithExtraMetric })
+ logic.mount()
+
+ await expectLogic(logic).toDispatchActions(['triggerRecalculation']).toFinishAllListeners()
+ expect(capturedBody).toEqual({ trigger: 'experiment_config_change' })
+ })
+
it('applies terminal results and resumes polling the active run (reload while recalculating)', async () => {
const createMock = jest.fn(() => [201, pendingRecalculation])
useMocks({
@@ -624,6 +657,98 @@ describe('experimentMetricsLogic', () => {
expect(createMock).not.toHaveBeenCalled()
})
+ it('posts instead of queuing when only a latest-load is in flight (no running run)', async () => {
+ // Adding a shared metric reloads the experiment, which re-fires loadLatestRecalculation. That
+ // fetch flips recalculationLoading true but never polls, so it can't drain a queue. A config
+ // change here must create a run, not queue against the transient load and strand forever.
+ const createMock = jest.fn(() => [201, pendingRecalculation])
+ useMocks({
+ get: {
+ '/api/projects/:team_id/experiments/:id/metrics_recalculation/latest/': () => [
+ 200,
+ completedRecalculation,
+ ],
+ },
+ post: { '/api/projects/:team_id/experiments/:id/metrics_recalculation/': createMock },
+ })
+ mountLogic()
+ await expectLogic(logic).toDispatchActions(['setCurrentRecalculation']).toFinishAllListeners()
+
+ // Reproduce the transient state a latest-load leaves: loading true, only a completed run
+ // resolved. This is busy under isRecalculating, but no run is pending or in_progress.
+ logic.actions.setRecalculationLoading(true)
+ expect(logic.values.isRecalculating).toBe(true)
+ expect(logic.values.currentRecalculation?.status).toBe('completed')
+
+ await expectLogic(logic, () => {
+ logic.actions.triggerRecalculation('metric_config_change')
+ })
+ .toDispatchActions(['triggerRecalculation'])
+ .toNotHaveDispatchedActions(['setQueuedRerun'])
+ .toFinishAllListeners()
+
+ expect(logic.values.queuedRerun).toBeNull()
+ expect(createMock).toHaveBeenCalled()
+ })
+
+ it('queues a config change that arrives while a create POST is still in flight', async () => {
+ // Between the create POST firing and its response landing, currentRecalculation still holds the
+ // previous terminal status. A second config change here must queue, not post a duplicate the
+ // backend would dedupe to the active run and silently drop. cache.createInFlight closes it.
+ let resolveFirstCreate: (value: unknown) => void = () => {}
+ const createMock = jest.fn(async () => {
+ if (createMock.mock.calls.length === 1) {
+ // Hold the first create in flight until the test releases it.
+ await new Promise((resolve) => {
+ resolveFirstCreate = resolve
+ })
+ }
+ // Terminal-on-create so no poll arms; the drain must fire the queued rerun.
+ return [201, completedRecalculation2]
+ })
+ useMocks({
+ get: {
+ // Completed latest so mount does not auto-trigger; the run is at rest.
+ '/api/projects/:team_id/experiments/:id/metrics_recalculation/latest/': () => [
+ 200,
+ completedRecalculation,
+ ],
+ },
+ post: { '/api/projects/:team_id/experiments/:id/metrics_recalculation/': createMock },
+ })
+ mountLogic()
+ await expectLogic(logic).toDispatchActions(['setCurrentRecalculation']).toFinishAllListeners()
+
+ // First config change: its create POST is now in flight (held by the mock).
+ logic.actions.triggerRecalculation('metric_config_change')
+ while (createMock.mock.calls.length === 0) {
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ }
+ expect(createMock).toHaveBeenCalledTimes(1)
+
+ // Second config change arrives during the in-flight create: it must queue, not post again.
+ // No toFinishAllListeners here: the first create is deliberately held, so its listener is open.
+ await expectLogic(logic, () => {
+ logic.actions.triggerRecalculation('experiment_config_change')
+ }).toDispatchActions(['setQueuedRerun'])
+ expect(logic.values.queuedRerun).toBe('experiment_config_change')
+ expect(createMock).toHaveBeenCalledTimes(1)
+
+ // The first create settles terminal; the drain fires the queued rerun, which now creates.
+ await expectLogic(logic, () => {
+ resolveFirstCreate([201, completedRecalculation2])
+ }).toDispatchActions([
+ (a) =>
+ a.type === logic.actionTypes.triggerRecalculation &&
+ a.payload.trigger === 'experiment_config_change',
+ ])
+ while (createMock.mock.calls.length < 2) {
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ }
+ expect(logic.values.queuedRerun).toBeNull()
+ expect(createMock).toHaveBeenCalledTimes(2)
+ })
+
it('does not queue a cold_run (cold_run always starts fresh)', async () => {
const createMock = jest.fn(() => [201, pendingRecalculation])
useMocks({
diff --git a/frontend/src/scenes/experiments/experimentMetricsLogic.ts b/frontend/src/scenes/experiments/experimentMetricsLogic.ts
index 0dbe421b216e..2cd6c9a18d55 100644
--- a/frontend/src/scenes/experiments/experimentMetricsLogic.ts
+++ b/frontend/src/scenes/experiments/experimentMetricsLogic.ts
@@ -92,6 +92,22 @@ const metricsInOrder = (experiment: Experiment, type: 'primary' | 'secondary'):
return [...(inline as ExperimentMetric[]), ...sharedMetrics]
}
+/**
+ * Every metric uuid on the experiment now, across primary and secondary (inline + shared). Metrics without
+ * a uuid are skipped: they can't be matched against a run's per-uuid results, so they never signal a gap.
+ */
+const currentMetricUuids = (experiment: Experiment): string[] =>
+ [
+ ...metricsInOrder(experiment, 'primary').map((metric) => metric.uuid),
+ ...metricsInOrder(experiment, 'secondary').map((metric) => metric.uuid),
+ ].filter((uuid): uuid is string => !!uuid)
+
+/** Metric uuids a run resolved: a computed result or a recorded failure. */
+const coveredMetricUuids = (recalculation: ExperimentMetricsRecalculationApi): string[] => [
+ ...(recalculation.results ?? []).map(({ metric_uuid }) => metric_uuid),
+ ...Object.keys((recalculation.metric_errors as Record<string, unknown> | null) ?? {}),
+]
+
type MetricErrorState = { detail: string } | null
type ResolveByUuid<T> = (uuid: string) => T
@@ -693,14 +709,23 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([
}
/**
- * We have no per-metric staleness signal, so a results + failures count short of the total
- * means the run diverged: re-run to heal it. This recovery is generic (it also fires after a
- * reset and relaunch), so advance the window with experiment_config_change rather than reuse a
- * cutoff that may predate the new start_date.
+ * Heal a completed run that does not cover every current metric. Two cases:
+ * 1. The run diverged: its own resolved count fell short of its total (also fires after a
+ * reset and relaunch).
+ * 2. A metric was added after this run finished, so a current metric uuid is absent from the
+ * run's results. The run's own counts look complete, so only a uuid comparison catches it.
+ * Otherwise the new metric shows a perpetual loading state, since nothing else re-runs on
+ * page load. Advance the window with experiment_config_change rather than reuse a cutoff that
+ * may predate the new start_date.
*/
+ const coveredUuids = new Set(coveredMetricUuids(recalculation))
+ const missingCurrentMetric = currentMetricUuids(props.experiment).some(
+ (uuid) => !coveredUuids.has(uuid)
+ )
if (
recalculation.status === RECALCULATION_STATUSES.completed &&
- recalculation.completed_metrics + recalculation.failed_metrics < recalculation.total_metrics
+ (recalculation.completed_metrics + recalculation.failed_metrics < recalculation.total_metrics ||
+ missingCurrentMetric)
) {
actions.triggerRecalculation('experiment_config_change')
return
@@ -743,12 +768,22 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([
return
}
/**
- * If we have a recalculation in flight, and the user has changed the experiment or the metrics configuration,
- * we schedule a new recalculation with the corresponding trigger.
+ * A config change while a run is active queues a rerun; the terminal branch (poll, or a
+ * terminal-on-create) drains it. Guard on the run status, not isRecalculating: a transient
+ * loadLatestRecalculation fetch also flips isRecalculating, and queueing against it strands the
+ * rerun forever, because that fetch never polls and so never drains the queue.
+ *
+ * `cache.createInFlight` closes the window between the create POST firing and
+ * setCurrentRecalculation landing the pending run: during that round-trip currentRecalculation
+ * still holds the previous terminal status, so without this a second config change would post
+ * again, and the backend would dedupe it to the active run and drop its trigger.
*/
+ const runStatus = values.currentRecalculation?.status
+ const runInFlight =
+ runStatus === RECALCULATION_STATUSES.pending || runStatus === RECALCULATION_STATUSES.in_progress
if (
(trigger === 'experiment_config_change' || trigger === 'metric_config_change') &&
- values.isRecalculating
+ (runInFlight || cache.createInFlight)
) {
actions.setQueuedRerun(trigger)
return
@@ -783,6 +818,9 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([
* Cleared by setCurrentRecalculation on success, or in the catch below on failure.
*/
actions.setRecalculationLoading(true)
+ // Mark the create in flight synchronously so a second config change during the POST round-trip
+ // queues instead of posting a duplicate the backend would dedupe and drop. Cleared in finally.
+ cache.createInFlight = true
try {
const { projectId, experimentId } = resolvedIds
@@ -825,6 +863,16 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([
*/
applyResults(recalculation)
emitTerminalEvent(recalculation)
+ // Terminal-on-create arms no poll, so drain any rerun queued during this create here,
+ // the way the poll's terminal branch does. Otherwise a config change made mid-create
+ // would strand. Clear createInFlight first so the drained rerun creates instead of
+ // re-queuing against this finished create.
+ cache.createInFlight = false
+ const queued = values.queuedRerun
+ if (queued) {
+ actions.setQueuedRerun(null)
+ actions.triggerRecalculation(queued)
+ }
} else {
if (trigger === 'manual' && !recalculation.is_existing) {
lemonToast.info(
@@ -839,6 +887,8 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([
*/
actions.setRecalculationLoading(false)
lemonToast.error(error?.detail || 'Failed to trigger metrics recalculation')
+ } finally {
+ cache.createInFlight = false
}
},
/**