: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): record who set the precomputation toggle (#89176)
Juraj Majerik5d302947662c
diff --git a/posthog/admin/inlines/team_experiments_config_inline.py b/posthog/admin/inlines/team_experiments_config_inline.pyindex 2a11efb69d1c..28e1bd133004 100644--- a/posthog/admin/inlines/team_experiments_config_inline.py+++ b/posthog/admin/inlines/team_experiments_config_inline.py@@ -1,10 +1,21 @@+from django import formsfrom django.contrib import adminfrom products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig+class TeamExperimentsConfigInlineForm(forms.ModelForm):+ def save(self, commit: bool = True) -> 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 self.changed_data:+ self.instance.precomputation_enabled_set_by = TeamExperimentsConfig.PrecomputationEnabledSetBy.MANUAL+ return super().save(commit)++class TeamExperimentsConfigInline(admin.StackedInline):model = TeamExperimentsConfig+ form = TeamExperimentsConfigInlineFormextra = 0max_num = 1classes = ("collapse",)diff --git a/posthog/api/debug_ch_queries.py b/posthog/api/debug_ch_queries.pyindex f8ecf99f8f9f..21db4d239a6f 100644--- a/posthog/api/debug_ch_queries.py+++ b/posthog/api/debug_ch_queries.py@@ -493,7 +493,10 @@ class DebugCHQueries(viewsets.ViewSet):config = get_or_create_team_extension(team, TeamExperimentsConfig)config.experiment_precomputation_enabled = enabled- config.save(update_fields=["experiment_precomputation_enabled"])+ # A human toggling precomputation must stick: the auto-enrollment job only+ # writes when precomputation_enabled_set_by is null or "auto".+ config.precomputation_enabled_set_by = TeamExperimentsConfig.PrecomputationEnabledSetBy.MANUAL+ config.save(update_fields=["experiment_precomputation_enabled", "precomputation_enabled_set_by"])org_id = str(team.organization.id) if team.organization else Nonearr_by_org = self._fetch_org_arr({org_id}) if org_id else {}diff --git a/posthog/api/team.py b/posthog/api/team.pyindex a2cb7f7e4ae2..e5693fa05a9c 100644--- a/posthog/api/team.py+++ b/posthog/api/team.py@@ -212,6 +212,13 @@ def handle_experiments_config(request: request.Request, team: Team) -> response."flag_cleanup_repository",]+ 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+ return super().update(instance, validated_data)+def validate_flag_cleanup_repository(self, value: str | None) -> str | None:# Keeps the sandbox/LLM runtime the repo-selection module pulls in off the# request import path.diff --git a/posthog/api/test/test_debug_ch_queries.py b/posthog/api/test/test_debug_ch_queries.pyindex 3cc5a47eba9f..c406a7dfdeb7 100644--- a/posthog/api/test/test_debug_ch_queries.py+++ b/posthog/api/test/test_debug_ch_queries.py@@ -15,6 +15,8 @@ from posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.utils import generate_random_token_personal, hash_key_valuefrom posthog.settings.data_stores import CLICKHOUSE_AUX_CLUSTER, CLICKHOUSE_CLUSTER+from products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig+class TestDebugCHQuery(APIBaseTest):CLASS_DATA_LEVEL_SETUP = False@@ -204,3 +206,23 @@ class TestCacheTableStats(SimpleTestCase):self.assertNotIn("unavailable", exposures)self.assertTrue(metric_events["unavailable"])self.assertEqual(metric_events["total_rows"], 0)+++class TestPrecomputationTeamsUpdate(APIBaseTest):+ CLASS_DATA_LEVEL_SETUP = False++ def test_staff_toggle_stamps_manual_provenance(self):+ # A missing stamp would let the auto-enrollment job override a human's disable+ # on its next run.+ self.user.is_staff = True+ self.user.save()++ resp = self.client.post(+ "/api/debug_ch_queries/precomputation_teams/",+ {"team_id": self.team.id, "experiment_precomputation_enabled": False},+ )+ self.assertEqual(resp.status_code, HTTP_200_OK, resp.content)++ config = TeamExperimentsConfig.objects.get(team=self.team)+ self.assertFalse(config.experiment_precomputation_enabled)+ self.assertEqual(config.precomputation_enabled_set_by, TeamExperimentsConfig.PrecomputationEnabledSetBy.MANUAL)diff --git a/posthog/api/test/test_project.py b/posthog/api/test/test_project.pyindex d8b457c7c7c3..ad34938c5154 100644--- a/posthog/api/test/test_project.py+++ b/posthog/api/test/test_project.py@@ -16,6 +16,8 @@ from posthog.models.project import Projectfrom posthog.models.utils import generate_random_token_personal, hash_key_valuefrom posthog.test.persons import create_person, delete_person+from products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig+class TestProjectAPI(team_api_test_factory()): # type: ignore"""@@ -891,3 +893,24 @@ class TestProjectAPI(team_api_test_factory()): # type: ignoreresponse = self.client.get(f"/api/projects/{self.project.id}/experiments_config/")self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())self.assertIn("default_experiment_stats_method", response.json())++ def test_experiments_config_precomputation_toggle_stamps_manual_provenance(self):+ # A missing stamp would let the auto-enrollment job override a human's disable+ # on its next run. Other settings must not stamp it.+ response = self.client.patch(+ f"/api/projects/{self.project.id}/experiments_config/",+ {"default_cuped_enabled": True},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())+ config = TeamExperimentsConfig.objects.get(team_id=self.project.id)+ self.assertIsNone(config.precomputation_enabled_set_by)++ response = self.client.patch(+ f"/api/projects/{self.project.id}/experiments_config/",+ {"experiment_precomputation_enabled": True},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())+ config.refresh_from_db()+ self.assertEqual(config.precomputation_enabled_set_by, TeamExperimentsConfig.PrecomputationEnabledSetBy.MANUAL)diff --git a/products/experiments/backend/migrations/0033_teamexperimentsconfig_precomputation_enabled_set_by.py b/products/experiments/backend/migrations/0033_teamexperimentsconfig_precomputation_enabled_set_by.pynew file mode 100644index 000000000000..40f9aef48ff6--- /dev/null+++ b/products/experiments/backend/migrations/0033_teamexperimentsconfig_precomputation_enabled_set_by.py@@ -0,0 +1,23 @@+# Generated by Django 5.2.17 on 2026-08-26 12:08++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("experiments", "0032_teamexperimentsconfig_flag_cleanup_repository"),+ ]++ operations = [+ migrations.AddField(+ model_name="teamexperimentsconfig",+ name="precomputation_enabled_set_by",+ field=models.CharField(+ blank=True,+ choices=[("manual", "Manual"), ("auto", "Auto")],+ help_text="Who last set experiment_precomputation_enabled: a human (manual) or the auto-enrollment job (auto). Null means never set. The job only writes when this is null or auto, so a manual change in either direction sticks.",+ max_length=10,+ null=True,+ ),+ ),+ ]diff --git a/products/experiments/backend/migrations/0034_backfill_precomputation_enabled_set_by.py b/products/experiments/backend/migrations/0034_backfill_precomputation_enabled_set_by.pynew file mode 100644index 000000000000..81e4608110f5--- /dev/null+++ b/products/experiments/backend/migrations/0034_backfill_precomputation_enabled_set_by.py@@ -0,0 +1,20 @@+from django.db import migrations+++def backfill_manual(apps, schema_editor):+ # Every team enabled so far was enabled by a human via the staff endpoint.+ # Tiny update: only teams on the precomputation allowlist have this set.+ TeamExperimentsConfig = apps.get_model("experiments", "TeamExperimentsConfig")+ TeamExperimentsConfig.objects.filter(experiment_precomputation_enabled=True).update(+ precomputation_enabled_set_by="manual"+ )+++class Migration(migrations.Migration):+ dependencies = [+ ("experiments", "0033_teamexperimentsconfig_precomputation_enabled_set_by"),+ ]++ operations = [+ migrations.RunPython(backfill_manual, migrations.RunPython.noop, elidable=True),+ ]diff --git a/products/experiments/backend/migrations/max_migration.txt b/products/experiments/backend/migrations/max_migration.txtindex 59eab7f4a56e..8b2ebf8729a4 100644--- a/products/experiments/backend/migrations/max_migration.txt+++ b/products/experiments/backend/migrations/max_migration.txt@@ -1 +1 @@-0032_teamexperimentsconfig_flag_cleanup_repository+0034_backfill_precomputation_enabled_set_bydiff --git a/products/experiments/backend/models/team_experiments_config.py b/products/experiments/backend/models/team_experiments_config.pyindex 06de3bb024a4..a30058b8192b 100644--- a/products/experiments/backend/models/team_experiments_config.py+++ b/products/experiments/backend/models/team_experiments_config.py@@ -11,6 +11,10 @@ logger = logging.getLogger(__name__)class TeamExperimentsConfig(models.Model):+ class PrecomputationEnabledSetBy(models.TextChoices):+ MANUAL = "manual", "Manual"+ AUTO = "auto", "Auto"+team = models.OneToOneField(Team, on_delete=models.CASCADE, primary_key=True)experiment_recalculation_time = models.TimeField(@@ -41,6 +45,18 @@ class TeamExperimentsConfig(models.Model):help_text="Whether to precompute experiment exposure data for faster query execution.",)+ precomputation_enabled_set_by = models.CharField(+ max_length=10,+ choices=PrecomputationEnabledSetBy.choices,+ null=True,+ blank=True,+ help_text=(+ "Who last set experiment_precomputation_enabled: a human (manual) or the auto-enrollment "+ "job (auto). Null means never set. The job only writes when this is null or auto, so a "+ "manual change in either direction sticks."+ ),+ )+default_only_count_matured_users = models.BooleanField(default=False,help_text="Default value for 'only count matured users' on new experiments in this environment.",