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.

feat(experiments): reuse metric results when changing metric configuration (#90484)

Rodrigo Iloro01d47fef91b8
diff --git a/frontend/src/lib/utils/eventUsageLogic.ts b/frontend/src/lib/utils/eventUsageLogic.ts
index c2a8bbcde65a..88be8b30cc05 100644
--- a/frontend/src/lib/utils/eventUsageLogic.ts
+++ b/frontend/src/lib/utils/eventUsageLogic.ts
@@ -1208,10 +1208,12 @@ export interface eventUsageLogicActions {
| 'auto_refresh'
| 'cold_run'
| 'config_change'
+ | 'experiment_config_change'
| 'experiment_launch'
| 'experiment_stop'
| 'experiment_update'
| 'manual'
+ | 'metric_config_change'
| 'stale_refresh'
}
) => {
@@ -1229,10 +1231,12 @@ export interface eventUsageLogicActions {
| 'auto_refresh'
| 'cold_run'
| 'config_change'
+ | 'experiment_config_change'
| 'experiment_launch'
| 'experiment_stop'
| 'experiment_update'
| 'manual'
+ | 'metric_config_change'
| 'stale_refresh'
| undefined
}
@@ -1318,7 +1322,7 @@ export interface eventUsageLogicActions {
successful_count: number
total_duration_ms: number
total_metrics_count: number
- triggered_by: 'auto_refresh' | 'config_change' | 'manual' | 'page_load'
+ triggered_by: 'auto_refresh' | 'experiment_config_change' | 'manual' | 'metric_config_change' | 'page_load'
}
) => {
context: {
@@ -1334,7 +1338,7 @@ export interface eventUsageLogicActions {
successful_count: number
total_duration_ms: number
total_metrics_count: number
- triggered_by: 'auto_refresh' | 'config_change' | 'manual' | 'page_load'
+ triggered_by: 'auto_refresh' | 'experiment_config_change' | 'manual' | 'metric_config_change' | 'page_load'
}
experimentId: ExperimentIdType
teamId: number | null | undefined
@@ -2658,7 +2662,12 @@ export const eventUsageLogic = kea<eventUsageLogicType>([
successful_count: number
errored_count: number
cached_count: number
- triggered_by: 'page_load' | 'manual' | 'auto_refresh' | 'config_change'
+ triggered_by:
+ | 'page_load'
+ | 'manual'
+ | 'auto_refresh'
+ | 'experiment_config_change'
+ | 'metric_config_change'
force_refresh: boolean
refresh_id: string
experiment_duration_hours: number | null
@@ -2684,6 +2693,8 @@ export const eventUsageLogic = kea<eventUsageLogicType>([
| 'cold_run'
| 'stale_refresh'
| 'auto_refresh'
+ | 'experiment_config_change'
+ | 'metric_config_change'
| 'config_change'
| 'experiment_launch'
| 'experiment_stop'
diff --git a/frontend/src/scenes/experiments/experimentLogic.test.ts b/frontend/src/scenes/experiments/experimentLogic.test.ts
index 627f0238337e..0e2eb266964e 100644
--- a/frontend/src/scenes/experiments/experimentLogic.test.ts
+++ b/frontend/src/scenes/experiments/experimentLogic.test.ts
@@ -298,6 +298,28 @@ describe('experimentLogic', () => {
})
})
+ describe('recalculation trigger mapping', () => {
+ // The trigger a config listener sends decides the recalc window: experiment-scoped changes advance it
+ // (recompute all), metric-scoped changes reuse it (cache unchanged metrics). A wrong trigger silently
+ // recomputes everything or skips a needed recompute, so pin each listener to its trigger.
+ beforeEach(() => {
+ logic.actions.setExperiment(experiment)
+ jest.spyOn(api, 'update').mockResolvedValue(experiment)
+ })
+
+ it('changeExperimentStartDate advances the window (experiment_config_change)', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.changeExperimentStartDate('2026-01-01T00:00:00Z')
+ })
+ .toDispatchActions([
+ (action) =>
+ action.type === logic.actionTypes.refreshExperimentResults &&
+ action.payload.triggeredBy === 'experiment_config_change',
+ ])
+ .toFinishAllListeners()
+ })
+ })
+
describe('currentRefresh tracking', () => {
it('marks the refresh as in_progress while running and completed when it succeeds', async () => {
logic.actions.setExperiment(experiment)
@@ -1001,7 +1023,13 @@ describe('experimentLogic', () => {
await expectLogic(logic, () => {
logic.actions.moveMetricsBetweenSections(false, ['primary-metric-uuid'], [], ['primary-metric-uuid'])
})
- .toDispatchActions(['updateExperiment', 'refreshExperimentResults'])
+ .toDispatchActions([
+ 'updateExperiment',
+ // Moving a metric is metric-scoped: reuse the window so unchanged metrics stay cached.
+ (action) =>
+ action.type === logic.actionTypes.refreshExperimentResults &&
+ action.payload.triggeredBy === 'metric_config_change',
+ ])
.toFinishAllListeners()
})
})
diff --git a/frontend/src/scenes/experiments/experimentLogic.tsx b/frontend/src/scenes/experiments/experimentLogic.tsx
index 2465346296e8..130a9be57cdf 100644
--- a/frontend/src/scenes/experiments/experimentLogic.tsx
+++ b/frontend/src/scenes/experiments/experimentLogic.tsx
@@ -180,7 +180,21 @@ export interface ExperimentLogicProps {
formMode?: FormModes
}
-export type ExperimentTriggeredBy = 'page_load' | 'manual' | 'auto_refresh' | 'config_change'
+export type ExperimentTriggeredBy =
+ | 'page_load'
+ | 'manual'
+ | 'auto_refresh'
+ | 'experiment_config_change'
+ | 'metric_config_change'
+
+// Triggers that kick off a metrics recalculation. Each is also a valid API TriggerEnumApi value, so a
+// narrowed triggeredBy passes straight to triggerRecalculation. page_load and manual are handled elsewhere.
+const RECALCULATION_TRIGGERS = ['experiment_config_change', 'metric_config_change', 'auto_refresh'] as const
+
+const isRecalculationTrigger = (
+ triggeredBy: ExperimentTriggeredBy
+): triggeredBy is (typeof RECALCULATION_TRIGGERS)[number] =>
+ (RECALCULATION_TRIGGERS as readonly string[]).includes(triggeredBy)
export type CurrentRefreshState = 'in_progress' | 'completed' | 'partial' | 'errored'
export type FinishedRefreshState = Exclude<CurrentRefreshState, 'in_progress'>
@@ -2629,13 +2643,13 @@ export const experimentLogic = kea<experimentLogicType>([
await asyncActions.updateExperiment({ start_date: startDate, update_feature_flag_params: false })
// eslint-disable-next-line no-unused-expressions
values.experiment && eventUsageLogic.actions.reportExperimentStartDateChange(values.experiment, startDate)
- actions.refreshExperimentResults(true, 'config_change')
+ actions.refreshExperimentResults(true, 'experiment_config_change')
},
changeExperimentEndDate: async ({ endDate }) => {
await asyncActions.updateExperiment({ end_date: endDate, update_feature_flag_params: false })
// eslint-disable-next-line no-unused-expressions
values.experiment && eventUsageLogic.actions.reportExperimentEndDateChange(values.experiment, endDate)
- actions.refreshExperimentResults(true, 'config_change')
+ actions.refreshExperimentResults(true, 'experiment_config_change')
},
endExperiment: async ({ openCleanupPr, repository, setRepositoryAsTeamDefault }) => {
actions.setEndExperimentLoading(true)
@@ -2776,7 +2790,7 @@ export const experimentLogic = kea<experimentLogicType>([
* Config changes and auto-refresh both re-run metrics, tagged with their cause; page loads
* and manual reloads are handled elsewhere. Concurrent triggers coalesce onto one active run.
*/
- if ((triggeredBy === 'config_change' || triggeredBy === 'auto_refresh') && values.experiment) {
+ if (isRecalculationTrigger(triggeredBy) && values.experiment) {
experimentMetricsLogic({ experiment: values.experiment }).actions.triggerRecalculation(
triggeredBy
)
@@ -2931,7 +2945,7 @@ export const experimentLogic = kea<experimentLogicType>([
metricsLogic.actions.setSecondaryMetricsResultsErrors([])
// Reload results for added/edited metrics
- actions.refreshExperimentResults(true, 'config_change')
+ actions.refreshExperimentResults(true, 'metric_config_change')
},
updateExperimentCollectionGoal: async () => {
const { recommendedRunningTime, recommendedSampleSize, minimumDetectableEffect } = values
@@ -2953,13 +2967,13 @@ export const experimentLogic = kea<experimentLogicType>([
},
update_feature_flag_params: false,
})
- actions.refreshExperimentResults(true, 'config_change')
+ actions.refreshExperimentResults(true, 'experiment_config_change')
},
updateExperimentSettings: async ({ update }) => {
// Settings like stats config, CUPED, and conversion-window handling change
// how metrics and exposures are computed, so persist then re-query.
await asyncActions.updateExperiment({ ...update, update_feature_flag_params: false })
- actions.refreshExperimentResults(true, 'config_change')
+ actions.refreshExperimentResults(true, 'experiment_config_change')
},
resetRunningExperiment: async () => {
try {
@@ -3166,7 +3180,7 @@ export const experimentLogic = kea<experimentLogicType>([
}
}
- actions.loadExperiment({ triggeredBy: 'config_change' })
+ actions.loadExperiment({ triggeredBy: 'metric_config_change' })
},
duplicateSharedMetricAsInlineMetric: ({ isSecondary, newUuid }) => {
// Listeners run after reducers, so the copy is only there if the shared metric was actually found
@@ -3210,7 +3224,7 @@ export const experimentLogic = kea<experimentLogicType>([
}
}
- actions.loadExperiment({ triggeredBy: 'config_change' })
+ actions.loadExperiment({ triggeredBy: 'metric_config_change' })
},
createExperimentDashboard: async () => {
actions.setIsCreatingExperimentDashboard(true)
@@ -3652,7 +3666,7 @@ export const experimentLogic = kea<experimentLogicType>([
await asyncActions.updateExperiment(update)
if (!canReuseResults) {
- actions.refreshExperimentResults(true, 'config_change')
+ actions.refreshExperimentResults(true, 'metric_config_change')
return
}
@@ -3722,10 +3736,11 @@ export const experimentLogic = kea<experimentLogicType>([
actions.updateExperiment(updatePayload)
- // Adding a breakdown changes how the metric is computed, so re-run results — recalculation
- // flow triggers a fresh recalc via config_change; legacy flow reloads per-metric results.
+ // Adding a breakdown changes how the metric is computed, so re-run results. The recalculation
+ // flow reuses the current window (metric_config_change), so this breakdown recomputes on its
+ // changed fingerprint while unchanged metrics load from cache; legacy reloads per-metric results.
if (values.featureFlags[FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION]) {
- actions.refreshExperimentResults(true, 'config_change')
+ actions.refreshExperimentResults(true, 'metric_config_change')
} else if (isPrimary) {
actions.loadPrimaryMetricsResults(true)
} else {
@@ -3758,10 +3773,10 @@ export const experimentLogic = kea<experimentLogicType>([
actions.updateExperiment(updatePayload)
// Removing a breakdown changes how the metric is computed, so re-run results. On the
- // recalculation flow this routes through refreshExperimentResults('config_change') (which
- // triggers a fresh recalculation); the legacy flow reloads the per-metric results directly.
+ // recalculation flow this reuses the current window (metric_config_change), so this metric
+ // recomputes on its changed fingerprint while others load from cache; legacy reloads per-metric.
if (values.featureFlags[FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION]) {
- actions.refreshExperimentResults(true, 'config_change')
+ actions.refreshExperimentResults(true, 'metric_config_change')
} else if (isPrimary) {
actions.loadPrimaryMetricsResults(true)
} else {
@@ -3806,7 +3821,7 @@ export const experimentLogic = kea<experimentLogicType>([
* updating a breakdown limit triggers a recalculation.
*/
if (values.featureFlags[FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION]) {
- actions.refreshExperimentResults(true, 'config_change')
+ actions.refreshExperimentResults(true, 'metric_config_change')
} else if (isPrimary) {
actions.loadPrimaryMetricsResults(true)
} else {
@@ -3850,7 +3865,7 @@ export const experimentLogic = kea<experimentLogicType>([
* updating a breakdown limit triggers a recalculation.
*/
if (values.featureFlags[FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION]) {
- actions.refreshExperimentResults(true, 'config_change')
+ actions.refreshExperimentResults(true, 'metric_config_change')
} else if (isPrimary) {
actions.loadPrimaryMetricsResults(true)
} else {
@@ -3882,13 +3897,14 @@ export const experimentLogic = kea<experimentLogicType>([
},
}
)
- // Re-fetch results since the variant set changed. On the recalculation flow this means a
- // fresh recalc; on the legacy flow it's the per-metric loaders. Exposures refresh either way.
+ // Re-fetch results since the variant set changed. On the recalculation flow this advances the
+ // window (experiment_config_change), so every metric recomputes; legacy uses the per-metric
+ // loaders. Exposures refresh either way.
if (values.featureFlags[FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION]) {
// eslint-disable-next-line no-unused-expressions
values.experiment &&
experimentMetricsLogic({ experiment: values.experiment }).actions.triggerRecalculation(
- 'config_change'
+ 'experiment_config_change'
)
} else {
actions.loadPrimaryMetricsResults(true)
diff --git a/frontend/src/scenes/experiments/experimentMetricsLogic.ts b/frontend/src/scenes/experiments/experimentMetricsLogic.ts
index 563e1cf99891..2c7111161ae4 100644
--- a/frontend/src/scenes/experiments/experimentMetricsLogic.ts
+++ b/frontend/src/scenes/experiments/experimentMetricsLogic.ts
@@ -199,10 +199,12 @@ export interface experimentMetricsLogicActions {
| 'auto_refresh'
| 'cold_run'
| 'config_change'
+ | 'experiment_config_change'
| 'experiment_launch'
| 'experiment_stop'
| 'experiment_update'
| 'manual'
+ | 'metric_config_change'
| 'stale_refresh'
}
) => {
@@ -220,10 +222,12 @@ export interface experimentMetricsLogicActions {
| 'auto_refresh'
| 'cold_run'
| 'config_change'
+ | 'experiment_config_change'
| 'experiment_launch'
| 'experiment_stop'
| 'experiment_update'
| 'manual'
+ | 'metric_config_change'
| 'stale_refresh'
| undefined
}
@@ -654,13 +658,15 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([
/**
* We have no per-metric staleness signal, so a results + failures count short of the total
- * means a shared metric diverged: re-run to heal it.
+ * 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.
*/
if (
recalculation.status === RECALCULATION_STATUSES.completed &&
recalculation.completed_metrics + recalculation.failed_metrics < recalculation.total_metrics
) {
- actions.triggerRecalculation('config_change')
+ actions.triggerRecalculation('experiment_config_change')
return
}
} catch (error: any) {
diff --git a/products/experiments/backend/migrations/0036_alter_experimentmetricsrecalculation_trigger.py b/products/experiments/backend/migrations/0036_alter_experimentmetricsrecalculation_trigger.py
new file mode 100644
index 000000000000..2aa8f195d168
--- /dev/null
+++ b/products/experiments/backend/migrations/0036_alter_experimentmetricsrecalculation_trigger.py
@@ -0,0 +1,33 @@
+# Generated by Django 5.2.17 on 2026-08-27 16:35
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("experiments", "0035_strip_unknown_exposure_criteria_keys"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="experimentmetricsrecalculation",
+ name="trigger",
+ field=models.CharField(
+ choices=[
+ ("manual", "Manual"),
+ ("agent_mcp", "Agent (MCP)"),
+ ("cold_run", "Cold Run"),
+ ("stale_refresh", "Stale Refresh"),
+ ("auto_refresh", "Auto Refresh"),
+ ("experiment_config_change", "Experiment Config Change"),
+ ("metric_config_change", "Metric Config Change"),
+ ("config_change", "Config Change"),
+ ("experiment_launch", "Experiment Launch"),
+ ("experiment_stop", "Experiment Stop"),
+ ("experiment_update", "Experiment Update"),
+ ],
+ default="manual",
+ max_length=30,
+ ),
+ ),
+ ]
diff --git a/products/experiments/backend/migrations/max_migration.txt b/products/experiments/backend/migrations/max_migration.txt
index b8bf9e743df0..d984f4c38343 100644
--- a/products/experiments/backend/migrations/max_migration.txt
+++ b/products/experiments/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0035_strip_unknown_exposure_criteria_keys
+0036_alter_experimentmetricsrecalculation_trigger
diff --git a/products/experiments/backend/models/experiment.py b/products/experiments/backend/models/experiment.py
index 45ac081a1374..ce872b6679ad 100644
--- a/products/experiments/backend/models/experiment.py
+++ b/products/experiments/backend/models/experiment.py
@@ -524,8 +524,14 @@ class ExperimentMetricsRecalculation(TeamScopedRootMixin, UUIDModel):
COLD_RUN = "cold_run", "Cold Run"
STALE_REFRESH = "stale_refresh", "Stale Refresh"
AUTO_REFRESH = "auto_refresh", "Auto Refresh"
- CONFIG_CHANGE = "config_change", "Config Change"
+ # Experiment-scoped change (start/end date, excluded variants, exposure criteria): advances the
+ # window to now, so every metric recomputes.
+ EXPERIMENT_CONFIG_CHANGE = "experiment_config_change", "Experiment Config Change"
+ # Metric-scoped change (add metric, breakdown add/remove/attribution/limit): reuses the latest
+ # completed window, so unchanged metrics load from cache and only new or changed metrics recompute.
+ METRIC_CONFIG_CHANGE = "metric_config_change", "Metric Config Change"
# Deprecated: never emitted, retained for old rows.
+ CONFIG_CHANGE = "config_change", "Config Change"
EXPERIMENT_LAUNCH = "experiment_launch", "Experiment Launch"
EXPERIMENT_STOP = "experiment_stop", "Experiment Stop"
EXPERIMENT_UPDATE = "experiment_update", "Experiment Update"
diff --git a/products/experiments/backend/temporal/recalculation_logic.py b/products/experiments/backend/temporal/recalculation_logic.py
index 162b9d4c56cd..3bf599c8ed3e 100644
--- a/products/experiments/backend/temporal/recalculation_logic.py
+++ b/products/experiments/backend/temporal/recalculation_logic.py
@@ -10,6 +10,7 @@ from datetime import datetime, timedelta
from typing import Any
from django.db import close_old_connections, transaction
+from django.db.models import Q
from django.utils import timezone
import structlog
@@ -172,6 +173,43 @@ def _discover_experiment_metrics_sync(recalculation_id: str) -> list[ExperimentM
# Progress (start / finish only — per-metric progress is folded into the calc step)
# ---------------------------------------------------------------------------
+# Triggers that keep the prior window so unchanged metrics hit the (experiment, metric, query_to, fingerprint)
+# cache and only new or changed metrics recompute. Every other trigger advances the window to now.
+_REUSE_WINDOW_TRIGGERS = frozenset({ExperimentMetricsRecalculation.Trigger.METRIC_CONFIG_CHANGE})
+
+
+def _resolve_query_to(experiment: Experiment, trigger: str | None) -> datetime:
+ """Window end for a starting run: reuse the latest terminal run's for metric-scoped changes, else advance.
+
+ A stopped experiment has a fixed window (experiment_window_end always returns end_date), so reuse is moot
+ and we skip the lookup. archived is orthogonal: it never affects the window, which reads only end_date.
+ """
+ now = timezone.now()
+ if experiment.is_stopped or trigger not in _REUSE_WINDOW_TRIGGERS:
+ return experiment_window_end(experiment, now)
+
+ # Any terminal run is a valid anchor, not only COMPLETED: a partial-failure run is marked FAILED yet its
+ # succeeded metrics hold result rows at that (newer) query_to. Mirror get_latest_recalculation so reuse
+ # picks the newest real window instead of falling back to an older one and moving results backward.
+ latest_query_to = (
+ ExperimentMetricsRecalculation.objects.filter(experiment=experiment, query_to__isnull=False)
+ .filter(
+ Q(status=ExperimentMetricsRecalculation.Status.COMPLETED)
+ | (Q(status=ExperimentMetricsRecalculation.Status.FAILED) & Q(completed_at__isnull=False))
+ )
+ .order_by("-query_to")
+ .values_list("query_to", flat=True)
+ .first()
+ )
+ if latest_query_to is None:
+ return experiment_window_end(experiment, now)
+
+ # A reset+relaunch leaves the prior run's rows behind with a query_to from before the new start_date.
+ # Never reuse a cutoff below start_date, or the window would begin before the experiment exists.
+ if experiment.start_date is not None and latest_query_to < experiment.start_date:
+ return experiment_window_end(experiment, now)
+ return experiment_window_end(experiment, latest_query_to)
+
@database_sync_to_async_pool
def _update_recalculation_progress_sync(update: RecalculationProgressUpdate) -> str | None:
@@ -193,7 +231,7 @@ def _update_recalculation_progress_sync(update: RecalculationProgressUpdate) ->
# calc activities still in flight from the prior attempt).
if update.mark_started:
experiment = Experiment.objects.get(id=state.experiment_id)
- proposed_query_to = experiment_window_end(experiment, timezone.now())
+ proposed_query_to = _resolve_query_to(experiment, state.trigger)
won = (
ExperimentMetricsRecalculation.objects.filter(
diff --git a/products/experiments/backend/temporal/test_recalculation_activities.py b/products/experiments/backend/temporal/test_recalculation_activities.py
index 1b803415b017..a0f38773a158 100644
--- a/products/experiments/backend/temporal/test_recalculation_activities.py
+++ b/products/experiments/backend/temporal/test_recalculation_activities.py
@@ -94,8 +94,10 @@ class TestRecalculationActivities(BaseTest):
team=self.team, created_by=self.user, feature_flag=self._flag(flag_key), name="exp"
)
- def _recalc(self, exp: Experiment) -> ExperimentMetricsRecalculation:
- return ExperimentMetricsRecalculation.objects.create(team=self.team, experiment=exp)
+ def _recalc(
+ self, exp: Experiment, trigger: str = ExperimentMetricsRecalculation.Trigger.MANUAL
+ ) -> ExperimentMetricsRecalculation:
+ return ExperimentMetricsRecalculation.objects.create(team=self.team, experiment=exp, trigger=trigger)
def _attach_saved_metric(self, exp: Experiment, uuid: str, metric_type: str) -> None:
saved = ExperimentSavedMetric.objects.create(
@@ -335,6 +337,162 @@ class TestRecalculationActivities(BaseTest):
else:
assert recalc.query_to == now
+ @parameterized.expand(
+ [
+ # trigger, expect_reuse: only a metric-scoped change reuses the prior completed window.
+ (ExperimentMetricsRecalculation.Trigger.METRIC_CONFIG_CHANGE, True),
+ (ExperimentMetricsRecalculation.Trigger.EXPERIMENT_CONFIG_CHANGE, False),
+ (ExperimentMetricsRecalculation.Trigger.MANUAL, False),
+ (ExperimentMetricsRecalculation.Trigger.AUTO_REFRESH, False),
+ ]
+ )
+ @freeze_time("2026-06-23T05:00:00Z")
+ def test_mark_started_reuses_prior_window_only_for_metric_config_change(self, trigger: str, expect_reuse: bool):
+ # A running experiment has no end_date, so advancing triggers pin now while metric_config_change copies
+ # the latest completed run's query_to — the signal that keeps unchanged metrics on the cache.
+ now = timezone.now()
+ prior_window = now - timedelta(hours=6)
+ exp = self._experiment(flag_key=f"reuse-{trigger}")
+ ExperimentMetricsRecalculation.objects.create(
+ team=self.team,
+ experiment=exp,
+ status=ExperimentMetricsRecalculation.Status.COMPLETED,
+ query_to=prior_window,
+ completed_at=prior_window,
+ )
+ recalc = self._recalc(exp, trigger=trigger)
+
+ _update(
+ RecalculationProgressUpdate(
+ recalculation_id=str(recalc.id),
+ status="in_progress",
+ total_metrics=1,
+ metric_uuids=["m1"],
+ mark_started=True,
+ )
+ )
+
+ recalc.refresh_from_db()
+ assert recalc.query_to == (prior_window if expect_reuse else now)
+
+ @freeze_time("2026-06-23T05:00:00Z")
+ def test_mark_started_reuses_partial_failure_window(self):
+ # A run where one metric failed is marked FAILED but stamps completed_at and holds result rows for the
+ # metrics that succeeded. Reuse must anchor on that newest terminal window, not fall back to an older
+ # fully-completed one — otherwise the good metrics' displayed results move backward.
+ now = timezone.now()
+ older_completed = now - timedelta(hours=12)
+ newer_partial = now - timedelta(hours=2)
+ exp = self._experiment(flag_key="reuse-partial-failure")
+ ExperimentMetricsRecalculation.objects.create(
+ team=self.team,
+ experiment=exp,
+ status=ExperimentMetricsRecalculation.Status.COMPLETED,
+ query_to=older_completed,
+ completed_at=older_completed,
+ )
+ ExperimentMetricsRecalculation.objects.create(
+ team=self.team,
+ experiment=exp,
+ status=ExperimentMetricsRecalculation.Status.FAILED,
+ query_to=newer_partial,
+ completed_at=newer_partial,
+ )
+ recalc = self._recalc(exp, trigger=ExperimentMetricsRecalculation.Trigger.METRIC_CONFIG_CHANGE)
+
+ _update(
+ RecalculationProgressUpdate(
+ recalculation_id=str(recalc.id),
+ status="in_progress",
+ total_metrics=1,
+ metric_uuids=["m1"],
+ mark_started=True,
+ )
+ )
+
+ recalc.refresh_from_db()
+ assert recalc.query_to == newer_partial
+
+ @freeze_time("2026-06-23T05:00:00Z")
+ def test_mark_started_does_not_reuse_window_before_start_date(self):
+ # After a reset and relaunch the prior run's rows survive with a query_to from before the new start_date.
+ # Reusing that cutoff would begin the window before the experiment exists, so advance to now instead.
+ now = timezone.now()
+ exp = self._experiment(flag_key="reuse-before-start")
+ exp.start_date = now - timedelta(hours=1)
+ exp.save(update_fields=["start_date"])
+ ExperimentMetricsRecalculation.objects.create(
+ team=self.team,
+ experiment=exp,
+ status=ExperimentMetricsRecalculation.Status.COMPLETED,
+ query_to=now - timedelta(days=3),
+ completed_at=now - timedelta(days=3),
+ )
+ recalc = self._recalc(exp, trigger=ExperimentMetricsRecalculation.Trigger.METRIC_CONFIG_CHANGE)
+
+ _update(
+ RecalculationProgressUpdate(
+ recalculation_id=str(recalc.id),
+ status="in_progress",
+ total_metrics=1,
+ metric_uuids=["m1"],
+ mark_started=True,
+ )
+ )
+
+ recalc.refresh_from_db()
+ assert recalc.query_to == now
+
+ @freeze_time("2026-06-23T05:00:00Z")
+ def test_mark_started_metric_config_change_clamps_to_end_date_when_stopped(self):
+ # A stopped experiment has a fixed window: even metric_config_change resolves to end_date, so a stale
+ # prior window (recorded before the stop) can never push the recompute window past end_date.
+ now = timezone.now()
+ exp = self._experiment(flag_key="reuse-stopped")
+ exp.end_date = now - timedelta(days=2)
+ exp.save(update_fields=["end_date"])
+ ExperimentMetricsRecalculation.objects.create(
+ team=self.team,
+ experiment=exp,
+ status=ExperimentMetricsRecalculation.Status.COMPLETED,
+ query_to=now - timedelta(days=1),
+ completed_at=now - timedelta(days=1),
+ )
+ recalc = self._recalc(exp, trigger=ExperimentMetricsRecalculation.Trigger.METRIC_CONFIG_CHANGE)
+
+ _update(
+ RecalculationProgressUpdate(
+ recalculation_id=str(recalc.id),
+ status="in_progress",
+ total_metrics=1,
+ metric_uuids=["m1"],
+ mark_started=True,
+ )
+ )
+
+ recalc.refresh_from_db()
+ assert recalc.query_to == exp.end_date
+
+ @freeze_time("2026-06-23T05:00:00Z")
+ def test_mark_started_metric_config_change_advances_when_no_prior_window(self):
+ # First metric-scoped run: nothing to reuse, so it falls back to now rather than leaving query_to unset.
+ now = timezone.now()
+ exp = self._experiment(flag_key="reuse-no-prior")
+ recalc = self._recalc(exp, trigger=ExperimentMetricsRecalculation.Trigger.METRIC_CONFIG_CHANGE)
+
+ _update(
+ RecalculationProgressUpdate(
+ recalculation_id=str(recalc.id),
+ status="in_progress",
+ total_metrics=1,
+ metric_uuids=["m1"],
+ mark_started=True,
+ )
+ )
+
+ recalc.refresh_from_db()
+ assert recalc.query_to == now
+
def test_mark_completed_is_first_write_wins_on_retry(self):
# Symmetric to mark_started: a retried finish activity must not re-stamp completed_at.
recalc = self._recalc(self._experiment(flag_key="progress-retry-finish"))
diff --git a/products/experiments/frontend/generated/api.schemas.ts b/products/experiments/frontend/generated/api.schemas.ts
index 15528f9cf213..f6f23f80dfd3 100644
--- a/products/experiments/frontend/generated/api.schemas.ts
+++ b/products/experiments/frontend/generated/api.schemas.ts
@@ -2035,6 +2035,8 @@ export interface ExperimentFlagCleanupTaskApi {
* * `cold_run` - Cold Run
* * `stale_refresh` - Stale Refresh
* * `auto_refresh` - Auto Refresh
+ * * `experiment_config_change` - Experiment Config Change
+ * * `metric_config_change` - Metric Config Change
* * `config_change` - Config Change
* * `experiment_launch` - Experiment Launch
* * `experiment_stop` - Experiment Stop
@@ -2048,6 +2050,8 @@ export const TriggerEnumApi = {
ColdRun: 'cold_run',
StaleRefresh: 'stale_refresh',
AutoRefresh: 'auto_refresh',
+ ExperimentConfigChange: 'experiment_config_change',
+ MetricConfigChange: 'metric_config_change',
ConfigChange: 'config_change',
ExperimentLaunch: 'experiment_launch',
ExperimentStop: 'experiment_stop',
@@ -2065,6 +2069,8 @@ export interface RecalculateMetricsRequestApi {
* * `cold_run` - Cold Run
* * `stale_refresh` - Stale Refresh
* * `auto_refresh` - Auto Refresh
+ * * `experiment_config_change` - Experiment Config Change
+ * * `metric_config_change` - Metric Config Change
* * `config_change` - Config Change
* * `experiment_launch` - Experiment Launch
* * `experiment_stop` - Experiment Stop
@@ -2181,6 +2187,8 @@ export interface ExperimentMetricsRecalculationApi {
* * `cold_run` - Cold Run
* * `stale_refresh` - Stale Refresh
* * `auto_refresh` - Auto Refresh
+ * * `experiment_config_change` - Experiment Config Change
+ * * `metric_config_change` - Metric Config Change
* * `config_change` - Config Change
* * `experiment_launch` - Experiment Launch
* * `experiment_stop` - Experiment Stop
diff --git a/products/experiments/frontend/generated/api.zod.ts b/products/experiments/frontend/generated/api.zod.ts
index b9a07d12c2c1..294013718901 100644
--- a/products/experiments/frontend/generated/api.zod.ts
+++ b/products/experiments/frontend/generated/api.zod.ts
@@ -1037,17 +1037,19 @@ export const ExperimentsMetricsRecalculationCreateBody = /* @__PURE__ */ zod
'cold_run',
'stale_refresh',
'auto_refresh',
+ 'experiment_config_change',
+ 'metric_config_change',
'config_change',
'experiment_launch',
'experiment_stop',
'experiment_update',
])
.describe(
- '\* `manual` - Manual\n\* `agent_mcp` - Agent (MCP)\n\* `cold_run` - Cold Run\n\* `stale_refresh` - Stale Refresh\n\* `auto_refresh` - Auto Refresh\n\* `config_change` - Config Change\n\* `experiment_launch` - Experiment Launch\n\* `experiment_stop` - Experiment Stop\n\* `experiment_update` - Experiment Update'
+ '\* `manual` - Manual\n\* `agent_mcp` - Agent (MCP)\n\* `cold_run` - Cold Run\n\* `stale_refresh` - Stale Refresh\n\* `auto_refresh` - Auto Refresh\n\* `experiment_config_change` - Experiment Config Change\n\* `metric_config_change` - Metric Config Change\n\* `config_change` - Config Change\n\* `experiment_launch` - Experiment Launch\n\* `experiment_stop` - Experiment Stop\n\* `experiment_update` - Experiment Update'
)
.default(experimentsMetricsRecalculationCreateBodyTriggerDefault)
.describe(
- 'What triggered this recalculation (manual is the default for user-initiated runs)\n\n\* `manual` - Manual\n\* `agent_mcp` - Agent (MCP)\n\* `cold_run` - Cold Run\n\* `stale_refresh` - Stale Refresh\n\* `auto_refresh` - Auto Refresh\n\* `config_change` - Config Change\n\* `experiment_launch` - Experiment Launch\n\* `experiment_stop` - Experiment Stop\n\* `experiment_update` - Experiment Update'
+ 'What triggered this recalculation (manual is the default for user-initiated runs)\n\n\* `manual` - Manual\n\* `agent_mcp` - Agent (MCP)\n\* `cold_run` - Cold Run\n\* `stale_refresh` - Stale Refresh\n\* `auto_refresh` - Auto Refresh\n\* `experiment_config_change` - Experiment Config Change\n\* `metric_config_change` - Metric Config Change\n\* `config_change` - Config Change\n\* `experiment_launch` - Experiment Launch\n\* `experiment_stop` - Experiment Stop\n\* `experiment_update` - Experiment Update'
),
})
.describe('Request body for triggering a metrics recalculation.')
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index febae4b1d90e..e49ee2550846 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -34315,6 +34315,8 @@ export namespace Schemas {
* * `cold_run` - Cold Run
* * `stale_refresh` - Stale Refresh
* * `auto_refresh` - Auto Refresh
+ * * `experiment_config_change` - Experiment Config Change
+ * * `metric_config_change` - Metric Config Change
* * `config_change` - Config Change
* * `experiment_launch` - Experiment Launch
* * `experiment_stop` - Experiment Stop
@@ -34329,6 +34331,8 @@ export namespace Schemas {
ColdRun: 'cold_run',
StaleRefresh: 'stale_refresh',
AutoRefresh: 'auto_refresh',
+ ExperimentConfigChange: 'experiment_config_change',
+ MetricConfigChange: 'metric_config_change',
ConfigChange: 'config_change',
ExperimentLaunch: 'experiment_launch',
ExperimentStop: 'experiment_stop',
@@ -34414,6 +34418,8 @@ export namespace Schemas {
* * `cold_run` - Cold Run
* * `stale_refresh` - Stale Refresh
* * `auto_refresh` - Auto Refresh
+ * * `experiment_config_change` - Experiment Config Change
+ * * `metric_config_change` - Metric Config Change
* * `config_change` - Config Change
* * `experiment_launch` - Experiment Launch
* * `experiment_stop` - Experiment Stop
@@ -72870,6 +72876,8 @@ export namespace Schemas {
* * `cold_run` - Cold Run
* * `stale_refresh` - Stale Refresh
* * `auto_refresh` - Auto Refresh
+ * * `experiment_config_change` - Experiment Config Change
+ * * `metric_config_change` - Metric Config Change
* * `config_change` - Config Change
* * `experiment_launch` - Experiment Launch
* * `experiment_stop` - Experiment Stop