: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): add experiment_recalculation_times config field (#106467)
Juraj Majerik4fdd52c7e504
diff --git a/posthog/admin/inlines/team_experiments_config_inline.py b/posthog/admin/inlines/team_experiments_config_inline.pyindex 28e1bd133004..35cb40f1fb81 100644--- a/posthog/admin/inlines/team_experiments_config_inline.py+++ b/posthog/admin/inlines/team_experiments_config_inline.py@@ -1,7 +1,11 @@from django import formsfrom django.contrib import admin-from products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig+from products.experiments.backend.models.team_experiments_config import (+ TeamExperimentsConfig,+ legacy_from_recalculation_times,+ recalculation_times_from_legacy,+)class TeamExperimentsConfigInlineForm(forms.ModelForm):@@ -10,6 +14,17 @@ class TeamExperimentsConfigInlineForm(forms.ModelForm):# writes when precomputation_enabled_set_by is null or "auto".if "experiment_precomputation_enabled" in self.changed_data:self.instance.precomputation_enabled_set_by = TeamExperimentsConfig.PrecomputationEnabledSetBy.MANUAL+ # The two recalculation fields must stay coherent while both exist: writing one+ # syncs the other, matching the experiments_config serializer.+ if "experiment_recalculation_times" in self.changed_data:+ self.instance.experiment_recalculation_times = self.instance.experiment_recalculation_times or None+ self.instance.experiment_recalculation_time = legacy_from_recalculation_times(+ self.instance.experiment_recalculation_times+ )+ elif "experiment_recalculation_time" in self.changed_data:+ self.instance.experiment_recalculation_times = recalculation_times_from_legacy(+ self.instance.experiment_recalculation_time+ )return super().save(commit)@@ -26,6 +41,7 @@ class TeamExperimentsConfigInline(admin.StackedInline):{"fields": ["experiment_recalculation_time",+ "experiment_recalculation_times","default_experiment_confidence_level","default_experiment_stats_method","experiment_precomputation_enabled",diff --git a/posthog/admin/test_team_experiments_config_inline.py b/posthog/admin/test_team_experiments_config_inline.pynew file mode 100644index 000000000000..efca5912be99--- /dev/null+++ b/posthog/admin/test_team_experiments_config_inline.py@@ -0,0 +1,47 @@+from datetime import time++from posthog.test.base import BaseTest++from django.forms import ModelForm, modelform_factory++from posthog.admin.inlines.team_experiments_config_inline import TeamExperimentsConfigInlineForm+from posthog.models.team.extensions import get_or_create_team_extension++from products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig+++class TestTeamExperimentsConfigInlineForm(BaseTest):+ def _form(self, data: dict) -> ModelForm:+ # The admin builds the concrete form from the inline's fieldsets; mirror that here.+ form_class = modelform_factory(+ TeamExperimentsConfig,+ form=TeamExperimentsConfigInlineForm,+ fields=["experiment_recalculation_time", "experiment_recalculation_times"],+ )+ config = get_or_create_team_extension(self.team, TeamExperimentsConfig)+ return form_class(data=data, instance=config)++ def test_rejects_recalculation_times_the_api_would_reject(self):+ form = self._form({"experiment_recalculation_times": '["08:00:00", "09:00:00"]'})+ self.assertFalse(form.is_valid())+ self.assertIn("experiment_recalculation_times", form.errors)++ def test_admin_saves_keep_recalculation_fields_in_sync(self):+ # The hourly workflows read the legacy column; an admin edit that skips the+ # sync leaves recalculations running at the old hour.+ form = self._form({"experiment_recalculation_times": '["14:00:00", "02:00:00"]'})+ self.assertTrue(form.is_valid(), form.errors)+ config = form.save()+ self.assertEqual(config.experiment_recalculation_time, time(hour=14))++ # The admin submits every rendered field, so an edit to the legacy time arrives+ # with the list field holding its unchanged value.+ form = self._form(+ {+ "experiment_recalculation_time": "08:00:00",+ "experiment_recalculation_times": '["14:00:00", "02:00:00"]',+ }+ )+ self.assertTrue(form.is_valid(), form.errors)+ config = form.save()+ self.assertEqual(config.experiment_recalculation_times, ["08:00:00"])diff --git a/posthog/api/team.py b/posthog/api/team.pyindex dafcaa560cbc..aef2c0ffa662 100644--- a/posthog/api/team.py+++ b/posthog/api/team.py@@ -6,6 +6,7 @@ from functools import cached_propertyfrom typing import Any, Literal, castfrom django.conf import settings+from django.core.exceptions import ValidationError as DjangoValidationErrorfrom django.db import transactionfrom django.shortcuts import get_object_or_404from django.utils import timezone@@ -358,13 +359,38 @@ def handle_experiments_config(request: request.Request, team: Team) -> response."""Shared handler for the experiments_config action — exposed under both theteam/environment and project routers so both surfaces stay in parity."""# Keeps the products app import off this module's import path.- from products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig # noqa: PLC0415+ from products.experiments.backend.models.team_experiments_config import ( # noqa: PLC0415+ MAX_RECALCULATION_TIMES,+ MIN_RECALCULATION_GAP_HOURS,+ TeamExperimentsConfig,+ legacy_from_recalculation_times,+ recalculation_times_from_legacy,+ validate_recalculation_times,+ )class TeamExperimentsConfigSerializer(serializers.ModelSerializer):+ experiment_recalculation_times = serializers.ListField(+ child=serializers.RegexField(+ regex=r"^(?:[01]\d|2[0-3]):00:00$",+ error_messages={"invalid": "Recalculation times must be on the hour, in HH:00:00 format (UTC)."},+ ),+ required=False,+ allow_null=True,+ allow_empty=False,+ max_length=MAX_RECALCULATION_TIMES,+ help_text=(+ "Times of day (UTC) when experiment metrics are recalculated, as 'HH:00:00' strings "+ f"on the hour. At most {MAX_RECALCULATION_TIMES} entries, at least "+ f"{MIN_RECALCULATION_GAP_HOURS} hours apart. Null means the default time (02:00 UTC). "+ "Takes precedence over experiment_recalculation_time."+ ),+ )+class Meta:model = TeamExperimentsConfigfields = ["experiment_recalculation_time",+ "experiment_recalculation_times","default_experiment_confidence_level","default_experiment_stats_method","experiment_precomputation_enabled",@@ -377,11 +403,28 @@ def handle_experiments_config(request: request.Request, team: Team) -> response."flag_cleanup_repository",]+ def validate_experiment_recalculation_times(self, value: list[str] | None) -> list[str] | None:+ try:+ validate_recalculation_times(value)+ except DjangoValidationError as e:+ raise serializers.ValidationError(e.messages)+ return value+def update(self, instance: "TeamExperimentsConfig", validated_data: dict[str, Any]) -> "TeamExperimentsConfig":# A human toggling precomputation must stick: the auto-enrollment job only# writes when precomputation_enabled_set_by is null or "auto".if "experiment_precomputation_enabled" in validated_data:instance.precomputation_enabled_set_by = TeamExperimentsConfig.PrecomputationEnabledSetBy.MANUAL+ # The two recalculation fields must stay coherent while both exist: writing one+ # syncs the other, so old clients and the workflow reader never disagree.+ if "experiment_recalculation_times" in validated_data:+ validated_data["experiment_recalculation_time"] = legacy_from_recalculation_times(+ validated_data["experiment_recalculation_times"]+ )+ elif "experiment_recalculation_time" in validated_data:+ validated_data["experiment_recalculation_times"] = recalculation_times_from_legacy(+ validated_data["experiment_recalculation_time"]+ )return super().update(instance, validated_data)def validate_flag_cleanup_repository(self, value: str | None) -> str | None:diff --git a/posthog/api/test/test_project.py b/posthog/api/test/test_project.pyindex 4ad0b4fb4f62..da4f67d5f5b6 100644--- a/posthog/api/test/test_project.py+++ b/posthog/api/test/test_project.py@@ -1,4 +1,4 @@-from datetime import timedelta+from datetime import time, timedeltafrom unittest.mock import MagicMock, patch@@ -1159,6 +1159,59 @@ class TestProjectAPI(team_api_test_factory()): # type: ignoreconfig.refresh_from_db()self.assertEqual(config.precomputation_enabled_set_by, TeamExperimentsConfig.PrecomputationEnabledSetBy.MANUAL)+ def test_experiments_config_recalculation_times_sync_with_legacy_field(self):+ # The hourly workflow and older clients read experiment_recalculation_time while+ # newer clients read the list; if the sync breaks, recalcs run at the wrong hour.+ response = self.client.patch(+ f"/api/projects/{self.project.id}/experiments_config/",+ {"experiment_recalculation_times": ["14:00:00", "02:00:00"]},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())+ config = TeamExperimentsConfig.objects.get(team_id=self.project.id)+ self.assertEqual(config.experiment_recalculation_times, ["14:00:00", "02:00:00"])+ self.assertEqual(config.experiment_recalculation_time, time(hour=14))++ response = self.client.patch(+ f"/api/projects/{self.project.id}/experiments_config/",+ {"experiment_recalculation_time": "08:00:00"},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())+ config.refresh_from_db()+ self.assertEqual(config.experiment_recalculation_times, ["08:00:00"])+ self.assertEqual(config.experiment_recalculation_time, time(hour=8))++ response = self.client.patch(+ f"/api/projects/{self.project.id}/experiments_config/",+ {"experiment_recalculation_times": None},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())+ config.refresh_from_db()+ self.assertIsNone(config.experiment_recalculation_times)+ self.assertIsNone(config.experiment_recalculation_time)++ @parameterized.expand(+ [+ ("not_on_the_hour", ["08:30:00"]),+ ("bad_format", ["8am"]),+ ("hour_out_of_range", ["24:00:00"]),+ ("more_than_two", ["02:00:00", "10:00:00", "18:00:00"]),+ ("duplicate_hours", ["02:00:00", "02:00:00"]),+ ("closer_than_six_hours", ["08:00:00", "09:00:00"]),+ ("closer_than_six_hours_across_midnight", ["23:00:00", "01:00:00"]),+ ("empty_list", []),+ ]+ )+ def test_experiments_config_rejects_invalid_recalculation_times(self, _name, times):+ response = self.client.patch(+ f"/api/projects/{self.project.id}/experiments_config/",+ {"experiment_recalculation_times": times},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.json())+def test_tags_round_trip_and_land_in_the_project_team_namespace(self):# `tags` is not a Project column, so it must be pulled out before the serializer's# passthrough loop setattr()s everything left in validated_data onto the model.diff --git a/products/experiments/backend/migrations/0042_teamexperimentsconfig_experiment_recalculation_times_and_more.py b/products/experiments/backend/migrations/0042_teamexperimentsconfig_experiment_recalculation_times_and_more.pynew file mode 100644index 000000000000..dcd48fc27477--- /dev/null+++ b/products/experiments/backend/migrations/0042_teamexperimentsconfig_experiment_recalculation_times_and_more.py@@ -0,0 +1,30 @@+# Generated by Django 5.2.17 on 2026-09-25 07:31++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("experiments", "0041_alter_experimentmetricsrecalculation_trigger"),+ ]++ operations = [+ migrations.AddField(+ model_name="teamexperimentsconfig",+ name="experiment_recalculation_times",+ field=models.JSONField(+ blank=True,+ help_text="Times of day (UTC) when experiment metrics are recalculated, as a list of 'HH:00:00' strings on the hour, at most 2 entries at least 6 hours apart. Null means the default time (02:00 UTC).",+ null=True,+ ),+ ),+ migrations.AlterField(+ model_name="teamexperimentsconfig",+ name="experiment_recalculation_time",+ field=models.TimeField(+ blank=True,+ help_text="Deprecated in favor of experiment_recalculation_times, which takes precedence when set. Kept in sync with its first entry for older clients.",+ null=True,+ ),+ ),+ ]diff --git a/products/experiments/backend/migrations/0043_backfill_experiment_recalculation_times.py b/products/experiments/backend/migrations/0043_backfill_experiment_recalculation_times.pynew file mode 100644index 000000000000..0c17504603cb--- /dev/null+++ b/products/experiments/backend/migrations/0043_backfill_experiment_recalculation_times.py@@ -0,0 +1,21 @@+from django.db import migrations+++def backfill_recalculation_times(apps, schema_editor):+ # Rows exist only for teams that touched experiment settings, so this stays small.+ TeamExperimentsConfig = apps.get_model("experiments", "TeamExperimentsConfig")+ for config in TeamExperimentsConfig.objects.exclude(experiment_recalculation_time=None).filter(+ experiment_recalculation_times__isnull=True+ ):+ config.experiment_recalculation_times = [f"{config.experiment_recalculation_time.hour:02d}:00:00"]+ config.save(update_fields=["experiment_recalculation_times"])+++class Migration(migrations.Migration):+ dependencies = [+ ("experiments", "0042_teamexperimentsconfig_experiment_recalculation_times_and_more"),+ ]++ operations = [+ migrations.RunPython(backfill_recalculation_times, migrations.RunPython.noop, elidable=True),+ ]diff --git a/products/experiments/backend/migrations/0044_alter_teamexperimentsconfig_experiment_recalculation_times.py b/products/experiments/backend/migrations/0044_alter_teamexperimentsconfig_experiment_recalculation_times.pynew file mode 100644index 000000000000..77ae88a17ed1--- /dev/null+++ b/products/experiments/backend/migrations/0044_alter_teamexperimentsconfig_experiment_recalculation_times.py@@ -0,0 +1,24 @@+# Generated by Django 5.2.17 on 2026-09-25 08:41++from django.db import migrations, models++import products.experiments.backend.models.team_experiments_config+++class Migration(migrations.Migration):+ dependencies = [+ ("experiments", "0043_backfill_experiment_recalculation_times"),+ ]++ operations = [+ migrations.AlterField(+ model_name="teamexperimentsconfig",+ name="experiment_recalculation_times",+ field=models.JSONField(+ blank=True,+ help_text="Times of day (UTC) when experiment metrics are recalculated, as a list of 'HH:00:00' strings on the hour, at most 2 entries at least 6 hours apart. Null means the default time (02:00 UTC).",+ null=True,+ validators=[products.experiments.backend.models.team_experiments_config.validate_recalculation_times],+ ),+ ),+ ]diff --git a/products/experiments/backend/migrations/max_migration.txt b/products/experiments/backend/migrations/max_migration.txtindex 71f0b49b1fd7..f231fa3cafe9 100644--- a/products/experiments/backend/migrations/max_migration.txt+++ b/products/experiments/backend/migrations/max_migration.txt@@ -1 +1 @@-0041_alter_experimentmetricsrecalculation_trigger+0044_alter_teamexperimentsconfig_experiment_recalculation_timesdiff --git a/products/experiments/backend/models/team_experiments_config.py b/products/experiments/backend/models/team_experiments_config.pyindex 5df29eeccbbf..d8faacc53c76 100644--- a/products/experiments/backend/models/team_experiments_config.py+++ b/products/experiments/backend/models/team_experiments_config.py@@ -1,9 +1,52 @@+import re+from datetime import time++from django.core.exceptions import ValidationErrorfrom django.core.validators import MaxValueValidator, MinValueValidatorfrom django.db import modelsfrom posthog.models.organization import Organizationfrom posthog.models.team import Team+MAX_RECALCULATION_TIMES = 2+MIN_RECALCULATION_GAP_HOURS = 6++RECALCULATION_TIME_PATTERN = re.compile(r"^(?:[01]\d|2[0-3]):00:00$")+++def validate_recalculation_times(value: object) -> None:+ """Shared by the model field (admin forms) and the experiments_config serializer,+ so every write path enforces the same schedule contract."""+ if value is None:+ return+ if not isinstance(value, list) or not value:+ raise ValidationError("Recalculation times must be a non-empty list of 'HH:00:00' strings.")+ if len(value) > MAX_RECALCULATION_TIMES:+ raise ValidationError(f"At most {MAX_RECALCULATION_TIMES} recalculation times are allowed.")+ hours = []+ for entry in value:+ if not isinstance(entry, str) or not RECALCULATION_TIME_PATTERN.match(entry):+ raise ValidationError("Recalculation times must be on the hour, in HH:00:00 format (UTC).")+ hours.append(int(entry[:2]))+ if len(set(hours)) != len(hours):+ raise ValidationError("Recalculation times must be different.")+ for i, first in enumerate(hours):+ for second in hours[i + 1 :]:+ # Circular distance, so 23:00 and 01:00 count as 2 hours apart.+ gap = abs(first - second)+ if min(gap, 24 - gap) < MIN_RECALCULATION_GAP_HOURS:+ raise ValidationError(+ f"Recalculation times must be at least {MIN_RECALCULATION_GAP_HOURS} hours apart."+ )+++def recalculation_times_from_legacy(legacy: time | None) -> list[str] | None:+ return [f"{legacy.hour:02d}:00:00"] if legacy is not None else None+++def legacy_from_recalculation_times(times: list[str] | None) -> time | None:+ return time(hour=int(times[0][:2])) if times else None+class TeamExperimentsConfig(models.Model):class PrecomputationEnabledSetBy(models.TextChoices):@@ -15,7 +58,21 @@ class TeamExperimentsConfig(models.Model):experiment_recalculation_time = models.TimeField(null=True,blank=True,- help_text="Time of day (UTC) when experiment metrics should be recalculated. If not set, uses the default recalculation time.",+ help_text=(+ "Deprecated in favor of experiment_recalculation_times, which takes precedence when set. "+ "Kept in sync with its first entry for older clients."+ ),+ )++ experiment_recalculation_times = models.JSONField(+ null=True,+ blank=True,+ validators=[validate_recalculation_times],+ help_text=(+ "Times of day (UTC) when experiment metrics are recalculated, as a list of 'HH:00:00' "+ "strings on the hour, at most 2 entries at least 6 hours apart. Null means the default "+ "time (02:00 UTC)."+ ),)default_experiment_confidence_level = models.DecimalField(