: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
feat(experiments): experiment recalculation model (#60600)
Rodrigo Iloroe2cf45c362fb
diff --git a/.semgrep/rules/idor-team-scoped-models.yaml b/.semgrep/rules/idor-team-scoped-models.yamlindex a4443ea9f595..5b039af47e21 100644--- a/.semgrep/rules/idor-team-scoped-models.yaml+++ b/.semgrep/rules/idor-team-scoped-models.yaml@@ -121,6 +121,7 @@ rules:|Evaluation|Experiment|ExperimentHoldout+ |ExperimentMetricsRecalculation|ExperimentSavedMetric|ExportedAsset|ExportedRecording@@ -359,6 +360,7 @@ rules:|Evaluation|Experiment|ExperimentHoldout+ |ExperimentMetricsRecalculation|ExperimentSavedMetric|ExportedAsset|ExportedRecordingdiff --git a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambrindex ef19ca2debf4..4825fc46987a 100644--- a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr+++ b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr@@ -659,6 +659,7 @@'deleted','end_date','experimentmetricresult_set',+ 'experimentmetricsrecalculation_set','experimenttimeseriesrecalculation_set','experimenttosavedmetric_set','exposure_cohort_id',diff --git a/products/experiments/backend/migrations/0017_experimentmetricsrecalculation.py b/products/experiments/backend/migrations/0017_experimentmetricsrecalculation.pynew file mode 100644index 000000000000..b4b696c4959e--- /dev/null+++ b/products/experiments/backend/migrations/0017_experimentmetricsrecalculation.py@@ -0,0 +1,104 @@+# Generated by Django 5.2.14 on 2026-06-03 20:15++import django.db.models.deletion+from django.conf import settings+from django.db import migrations, models++import posthog.models.utils+++class Migration(migrations.Migration):+ dependencies = [+ (+ "experiments",+ "0016_teamexperimentsconfig_default_sequential_testing_enabled_and_more",+ ),+ ("posthog", "1207_migrate_ai_observability_models"),+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),+ ]++ operations = [+ migrations.CreateModel(+ name="ExperimentMetricsRecalculation",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ (+ "status",+ models.CharField(+ choices=[+ ("pending", "Pending"),+ ("in_progress", "In Progress"),+ ("completed", "Completed"),+ ("failed", "Failed"),+ ],+ default="pending",+ max_length=20,+ ),+ ),+ ("total_metrics", models.PositiveIntegerField(default=0)),+ ("metric_errors", models.JSONField(default=dict)),+ ("metric_uuids", models.JSONField(default=list)),+ ("query_to", models.DateTimeField(blank=True, null=True)),+ (+ "trigger",+ models.CharField(+ choices=[+ ("manual", "Manual"),+ ("experiment_launch", "Experiment Launch"),+ ("experiment_stop", "Experiment Stop"),+ ("experiment_update", "Experiment Update"),+ ],+ default="manual",+ max_length=30,+ ),+ ),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("started_at", models.DateTimeField(blank=True, null=True)),+ ("completed_at", models.DateTimeField(blank=True, null=True)),+ (+ "created_by",+ models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ (+ "experiment",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ to="experiments.experiment",+ ),+ ),+ (+ "team",+ models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="posthog.team"),+ ),+ ],+ options={+ "db_table": "posthog_experimentmetricsrecalculation",+ "indexes": [+ models.Index(+ fields=["experiment", "status"],+ name="posthog_exp_experim_54da5b_idx",+ ),+ ],+ "constraints": [+ models.UniqueConstraint(+ condition=models.Q(("status__in", ["pending", "in_progress"])),+ fields=("experiment",),+ name="unique_active_metrics_recalculation_per_experiment",+ )+ ],+ },+ ),+ ]diff --git a/products/experiments/backend/migrations/max_migration.txt b/products/experiments/backend/migrations/max_migration.txtindex d2426d41855c..8bfa9d1bc80c 100644--- a/products/experiments/backend/migrations/max_migration.txt+++ b/products/experiments/backend/migrations/max_migration.txt@@ -1 +1 @@-0016_teamexperimentsconfig_default_sequential_testing_enabled_and_more+0017_experimentmetricsrecalculationdiff --git a/products/experiments/backend/models/experiment.py b/products/experiments/backend/models/experiment.pyindex 8c331f9c525c..3b6640a95e1a 100644--- a/products/experiments/backend/models/experiment.py+++ b/products/experiments/backend/models/experiment.py@@ -8,6 +8,7 @@ from posthog.models.activity_logging.model_activity import ModelActivityMixinfrom posthog.models.file_system.constants import DEFAULT_SURFACEfrom posthog.models.file_system.file_system_mixin import FileSystemSyncMixinfrom posthog.models.file_system.file_system_representation import FileSystemRepresentation+from posthog.models.scoping.root_mixin import TeamScopedRootMixinfrom posthog.models.utils import RootTeamMixin, UUIDModelif TYPE_CHECKING:@@ -341,3 +342,64 @@ class ExperimentTimeseriesRecalculation(UUIDModel):def __str__(self):metric_uuid = self.metric.get("uuid", "unknown")return f"ExperimentTimeseriesRecalculation(exp={self.experiment_id}, metric={metric_uuid}, fingerprint={self.fingerprint}, status={self.status})"+++class ExperimentMetricsRecalculation(TeamScopedRootMixin, UUIDModel):+ """Tracks batch recalculation of all metrics for an experiment.++ The primary key (`id`, a uuid7 from UUIDModel) is the recalculation_id passed to the recalculation workflow.+ """++ class Status(models.TextChoices):+ PENDING = "pending", "Pending"+ IN_PROGRESS = "in_progress", "In Progress"+ COMPLETED = "completed", "Completed"+ FAILED = "failed", "Failed"++ class Trigger(models.TextChoices):+ MANUAL = "manual", "Manual"+ EXPERIMENT_LAUNCH = "experiment_launch", "Experiment Launch"+ EXPERIMENT_STOP = "experiment_stop", "Experiment Stop"+ EXPERIMENT_UPDATE = "experiment_update", "Experiment Update"++ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)+ experiment = models.ForeignKey("Experiment", on_delete=models.CASCADE)++ status = models.CharField(max_length=20, choices=Status, default=Status.PENDING)+ total_metrics = models.PositiveIntegerField(default=0)+ metric_errors = models.JSONField(default=dict)+ # Internal: written by the discovery activity, used by the service to recompute recalc fingerprints. Not exposed by the API serializer.+ metric_uuids = models.JSONField(default=list)++ # Internal: single data-window end shared by all metrics in the run. Set once when the run starts; every metric+ # (including retries) uses this value so all metrics cover the same window and retries overwrite rather than+ # orphan rows. Not exposed by the API serializer.+ query_to = models.DateTimeField(null=True, blank=True)++ trigger = models.CharField(max_length=30, choices=Trigger, default=Trigger.MANUAL)++ created_at = models.DateTimeField(auto_now_add=True)+ started_at = models.DateTimeField(null=True, blank=True)+ completed_at = models.DateTimeField(null=True, blank=True)+ created_by = models.ForeignKey(+ "posthog.User",+ on_delete=models.SET_NULL,+ null=True,+ blank=True,+ )++ class Meta:+ indexes = [+ models.Index(fields=["experiment", "status"]),+ ]+ constraints = [+ models.UniqueConstraint(+ fields=["experiment"],+ condition=models.Q(status__in=["pending", "in_progress"]),+ name="unique_active_metrics_recalculation_per_experiment",+ ),+ ]+ db_table = "posthog_experimentmetricsrecalculation"++ def __str__(self):+ return f"ExperimentMetricsRecalculation(exp={self.experiment_id}, status={self.status}, total={self.total_metrics})"diff --git a/products/experiments/backend/presentation/serializers.py b/products/experiments/backend/presentation/serializers.pyindex 59cb392b9588..c2f5db01155b 100644--- a/products/experiments/backend/presentation/serializers.py+++ b/products/experiments/backend/presentation/serializers.py@@ -28,7 +28,7 @@ from products.experiments.backend.hogql_queries.experiment_metric_fingerprint imfrom products.experiments.backend.hogql_queries.utils import get_experiment_stats_methodfrom products.experiments.backend.llm_metric_templates import TEMPLATE_NAMESfrom products.experiments.backend.metric_utils import refresh_action_names_in_metric-from products.experiments.backend.models.experiment import Experiment, ExperimentHoldout+from products.experiments.backend.models.experiment import Experiment, ExperimentHoldout, ExperimentMetricsRecalculationfrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom ee.clickhouse.views.experiment_holdouts import ExperimentHoldoutSerializer@@ -601,3 +601,29 @@ class CreateFromPromptInputSerializer(serializers.Serializer):)return attrs+++class ExperimentMetricsRecalculationSerializer(serializers.Serializer):+ """Serializer for metrics recalculation status responses."""++ id = serializers.UUIDField(read_only=True, help_text="Unique identifier for this recalculation job")+ experiment_id = serializers.IntegerField(read_only=True, help_text="ID of the experiment being recalculated")+ status = serializers.ChoiceField(+ choices=ExperimentMetricsRecalculation.Status.choices,+ read_only=True,+ help_text="Current status of the recalculation job",+ )+ total_metrics = serializers.IntegerField(read_only=True, help_text="Total number of metrics to recalculate")+ # Named metric_errors (not errors) to avoid shadowing DRF's reserved Serializer.errors property.+ metric_errors = serializers.JSONField(read_only=True, help_text="Map of metric_uuid to error details")+ trigger = serializers.ChoiceField(+ choices=ExperimentMetricsRecalculation.Trigger.choices,+ read_only=True,+ help_text="What triggered this recalculation",+ )+ created_at = serializers.DateTimeField(read_only=True, help_text="When the job was created")+ started_at = serializers.DateTimeField(read_only=True, allow_null=True, help_text="When processing started")+ completed_at = serializers.DateTimeField(read_only=True, allow_null=True, help_text="When processing completed")+ is_existing = serializers.BooleanField(+ read_only=True, required=False, help_text="True if returning an existing job rather than a newly created one"+ )diff --git a/products/experiments/backend/test/test_metrics_recalculation_model.py b/products/experiments/backend/test/test_metrics_recalculation_model.pynew file mode 100644index 000000000000..430ca535797d--- /dev/null+++ b/products/experiments/backend/test/test_metrics_recalculation_model.py@@ -0,0 +1,126 @@+from datetime import UTC, datetime++from posthog.test.base import BaseTest++from django.db import IntegrityError, transaction++from parameterized import parameterized++from posthog.models.scoping import team_scope+from posthog.models.utils import uuid7++from products.experiments.backend.models.experiment import Experiment, ExperimentMetricsRecalculation+from products.feature_flags.backend.models.feature_flag import FeatureFlag++Status = ExperimentMetricsRecalculation.Status+++class TestExperimentMetricsRecalculationModel(BaseTest):+ def _flag(self, key: str | None = None) -> FeatureFlag:+ # Unique key per call (BaseTest rolls back between methods, but the helper's default key would still+ # collide if two tests in the same transaction reused it). Full uuid7 hex — the truncated form+ # collides for back-to-back calls because uuid7's leading bytes are millisecond-aligned.+ key = key or f"recalc-flag-{uuid7().hex}"+ return FeatureFlag.objects.create(+ team=self.team,+ created_by=self.user,+ key=key,+ name=f"Flag for {key}",+ filters={+ "groups": [{"properties": [], "rollout_percentage": 100}],+ "multivariate": {+ "variants": [+ {"key": "control", "name": "Control", "rollout_percentage": 50},+ {"key": "test", "name": "Test", "rollout_percentage": 50},+ ]+ },+ },+ )++ def _experiment(self, flag_key: str | None = None) -> Experiment:+ return Experiment.objects.create(+ team=self.team, created_by=self.user, feature_flag=self._flag(flag_key), name="exp"+ )++ def test_defaults(self):+ with team_scope(self.team.id, canonical=True):+ recalc = ExperimentMetricsRecalculation.objects.create(team=self.team, experiment=self._experiment())+ assert recalc.status == Status.PENDING+ assert recalc.total_metrics == 0+ assert recalc.metric_errors == {}+ assert recalc.metric_uuids == []+ assert recalc.trigger == ExperimentMetricsRecalculation.Trigger.MANUAL+ assert recalc.started_at is None+ assert recalc.completed_at is None+ assert recalc.query_to is None++ @parameterized.expand(+ [+ (Status.PENDING, True),+ (Status.IN_PROGRESS, True),+ (Status.COMPLETED, False),+ (Status.FAILED, False),+ ]+ )+ def test_active_recalculation_uniqueness(self, existing_status: str, should_block: bool):+ exp = self._experiment(flag_key=f"recalc-uniq-{existing_status}")+ with team_scope(self.team.id, canonical=True):+ ExperimentMetricsRecalculation.objects.create(team=self.team, experiment=exp, status=existing_status)++ def _create_second() -> None:+ ExperimentMetricsRecalculation.objects.create(team=self.team, experiment=exp, status=Status.PENDING)++ if should_block:+ with self.assertRaises(IntegrityError), transaction.atomic():+ _create_second()+ else:+ _create_second()+ assert ExperimentMetricsRecalculation.objects.filter(experiment=exp).count() == 2++ def test_timestamps_and_window_round_trip(self):+ # Pin storage behavior for the lifecycle timestamps and the shared data-window end. The "set once+ # on start" invariant for query_to is enforced by the workflow's start-progress activity (covered+ # in PR2's activity tests); this test just confirms the model stores and returns the values intact.+ started = datetime(2026, 6, 3, 12, 0, 0, tzinfo=UTC)+ completed = datetime(2026, 6, 3, 12, 5, 0, tzinfo=UTC)+ query_to = datetime(2026, 6, 3, 12, 0, 0, tzinfo=UTC)+ with team_scope(self.team.id, canonical=True):+ recalc = ExperimentMetricsRecalculation.objects.create(+ team=self.team,+ experiment=self._experiment(),+ started_at=started,+ completed_at=completed,+ query_to=query_to,+ status=Status.COMPLETED,+ )+ recalc.refresh_from_db()+ assert recalc.started_at == started+ assert recalc.completed_at == completed+ assert recalc.query_to == query_to++ def test_created_by_nullable_and_survives_user_deletion(self):+ # created_by is on_delete=SET_NULL: explicit None on create works, and deleting the user later+ # nulls the FK without cascading to the recalc row.+ from posthog.models import User++ another_user = User.objects.create_user(+ email=f"recalc-author-{uuid7().hex}@example.com", password=None, first_name="Author"+ )+ with team_scope(self.team.id, canonical=True):+ # Explicit None on create.+ null_recalc = ExperimentMetricsRecalculation.objects.create(+ team=self.team, experiment=self._experiment(), created_by=None+ )+ assert null_recalc.created_by is None++ # SET_NULL on user deletion.+ owned_recalc = ExperimentMetricsRecalculation.objects.create(+ team=self.team, experiment=self._experiment(), created_by=another_user+ )+ owned_recalc_id = owned_recalc.id++ another_user.delete()+ with team_scope(self.team.id, canonical=True):+ owned_recalc.refresh_from_db()+ assert owned_recalc.created_by is None+ assert ExperimentMetricsRecalculation.objects.filter(id=owned_recalc_id).exists()diff --git a/products/experiments/backend/test/test_metrics_recalculation_serializer.py b/products/experiments/backend/test/test_metrics_recalculation_serializer.pynew file mode 100644index 000000000000..b53c22b12174--- /dev/null+++ b/products/experiments/backend/test/test_metrics_recalculation_serializer.py@@ -0,0 +1,76 @@+from posthog.test.base import BaseTest++from parameterized import parameterized++from posthog.models.scoping import team_scope++from products.experiments.backend.models.experiment import Experiment, ExperimentMetricsRecalculation+from products.experiments.backend.presentation.serializers import ExperimentMetricsRecalculationSerializer+from products.feature_flags.backend.models.feature_flag import FeatureFlag+++class TestExperimentMetricsRecalculationSerializer(BaseTest):+ def test_serializes_status_payload(self):+ payload = {+ "id": "00000000-0000-0000-0000-000000000001",+ "experiment_id": 7,+ "status": "in_progress",+ "total_metrics": 3,+ "metric_errors": {"m1": {"step": "calculation", "message": "boom"}},+ "trigger": "manual",+ "created_at": "2026-05-28T10:00:00Z",+ "started_at": "2026-05-28T10:00:01Z",+ "completed_at": None,+ }+ data = ExperimentMetricsRecalculationSerializer(payload).data+ assert data["status"] == "in_progress"+ assert data["total_metrics"] == 3+ assert data["experiment_id"] == 7+ assert data["trigger"] == "manual"+ assert data["completed_at"] is None+ # Field is metric_errors (not errors) to avoid shadowing DRF's Serializer.errors property.+ assert data["metric_errors"] == {"m1": {"step": "calculation", "message": "boom"}}+ assert "errors" not in data+ assert "completed_metrics" not in data+ assert "failed_metrics" not in data++ def test_serializes_model_instance(self):+ # Read off a real model instance, not a dict. Locks in that metric_errors round-trips through DRF+ # — the bug to avoid is the model attribute being named one thing and the serializer field another,+ # which silently yields None when DRF reads instance.metric_errors and finds nothing.+ flag = FeatureFlag.objects.create(+ team=self.team,+ created_by=self.user,+ key="serializer-instance-flag",+ name="flag",+ filters={"groups": [{"properties": [], "rollout_percentage": 100}]},+ )+ experiment = Experiment.objects.create(team=self.team, created_by=self.user, feature_flag=flag, name="exp")+ with team_scope(self.team.id, canonical=True):+ recalc = ExperimentMetricsRecalculation.objects.create(+ team=self.team,+ experiment=experiment,+ metric_errors={"m1": {"step": "calculation", "message": "boom"}},+ )+ data = ExperimentMetricsRecalculationSerializer(recalc).data+ assert data["metric_errors"] == {"m1": {"step": "calculation", "message": "boom"}}+ assert "errors" not in data++ @parameterized.expand(+ [+ ("explicit_true", True),+ ("explicit_false", False),+ ]+ )+ def test_is_existing_round_trips_when_set(self, name: str, value: bool):+ # is_existing is required=False; when the caller populates it, it must round-trip with that value.+ data = ExperimentMetricsRecalculationSerializer({"is_existing": value}).data+ assert data["is_existing"] is value++ def test_is_existing_omitted_when_absent_from_instance(self):+ # required=False + no default means Field.get_attribute() raises SkipField() for missing attributes,+ # and the field disappears from the output entirely (rather than serializing as None). Pins the+ # contract so a future refactor — adding default=, switching to ModelSerializer, flipping required —+ # can't silently start emitting is_existing on payloads that never asked for it.+ data = ExperimentMetricsRecalculationSerializer({}).data+ assert "is_existing" not in data